Filter过滤器为客户端和服务器之间的过滤器,两端之间进行信息交互的时候需要这个过滤器来进行信息过滤
登陆页面 点击登陆后跳转到登陆成功页面 为了防止不通过登陆页面直接进入登陆成功页面,需要增加一个防止直接使用http://localhost:8080/ssm/logsucess.jsp进行登陆,需要增加一个过滤器
过滤器代码如下 Logfilter.java
package com.filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class Logfilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; HttpSession session = httpServletRequest.getSession(); String name = (String) session.getAttribute("name"); System.out.println("filter:"+name); if (name == null){ //不是登陆状态 httpServletResponse.sendRedirect("/ssm/log.jsp"); }else { filterChain.doFilter(servletRequest,servletResponse); } } @Override public void destroy() { } }web.xml中加入
<!--过滤器 --> <filter> <filter-name>logfilter</filter-name> <filter-class>com.filter.Logfilter</filter-class> </filter> <filter-mapping> <filter-name>logfilter</filter-name> <!-- 是去除项目名称之后的url --> <url-pattern>/logsucess.jsp</url-pattern> </filter-mapping>filter类中加入注解
@WebFilter("/*")然后在启动类中加入该注解
@ServletComponentScan