拦截器概念
在HttpServletRequest 到达Servlet 之前,拦截客户的HttpServletRequest 。
根据需要检查HttpServletRequest ,也可以修改HttpServletRequest 头和数据。
编写拦截器
package com.filter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author 19745
*/
public class FirstFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
request.setCharacterEncoding("UTF-8");
// String ip = request.getRemoteAddr();
// String url = request.getRequestURL().toString();
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Date d = new Date();
// String date = sdf.format(d);
//
// System.out.printf("%s %s 访问了 %s%n", date, ip, url);
filterChain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
配置web.xml
<filter>
<filter-name>FirstFilter</filter-name>
<filter-class>com.filter.FirstFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>FirstFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
url-pattern内的/* 代表拦截所有资源
中文处理
在通过Servlet获取中文参数 的章节中知道,可以通过
request.setCharacterEncoding(“UTF-8”);
正确获取UTF-8编码的中文。但是如果有很多servlet都需要获取中文,那么就必须在每个Servlet中增加这段代码。
有一个简便的办法,那就是通过Filter过滤器进行中文处理 ,那么所有的Servlet都不需要单独处理了。
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
request.setCharacterEncoding("UTF-8");
注意,需要重启tomcat服务。
在拦截器中添加request中文处理
取消拦截器和servlert中的request的中文处理
登录验证
如果session中没有保存username,强制跳转回登录界面。
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String uri = request.getRequestURI();
System.out.println("uri=" + uri);
if (uri.endsWith("login.html") || uri.endsWith("login")) {
chain.doFilter(request, response);
return;
}
String userName = (String) request.getSession().getAttribute("userName");
if (null == userName) {
response.sendRedirect("login.html");
return;
}
chain.doFilter(request, response);
}