filter过滤器Filter(筛请求的)public class QuickFilter implements Filter {
public void destroy() {
System.out.println("QuickFilter1销毁");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("QuickFilter1 doFilter调用");
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("QuickFilter1初始化");
}
}<!--web.xml-->
<filter>
<filter-name>QuickFilter</filter-name>
<filter-class>com.itcast.filter.QuickFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>QuickFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>filter的访问流程客户端发送请求给服务器时,tomcat请求会先获取到请求信息,创建对应点request和response对象 如果不添加过滤的话,tomcat引擎会带着request和response对象创建servlet,并把参数传递过去 如果添加了filter,则会在servlet之间设置了过滤器 在过滤器中需要调用chain.doFilter(request,response)后,请求才能被放行去找资源文件
filter作用对request和response进行配置值 权限过滤
filter的APIfilter生命周期及其与生命周期相关的方法 Filter的AP详解 init(FilterConfig):其中参数config代表该Filter对象的配置信息的对象,内部封装是该filter的配置信息 destory()方法:filter对象销毁时执行 doFilter方法:doFilter(ServletRequest,ServletResponse,FilterChain) 其中的参数: ServletRequest/ServletResponse:每次在执行doFilter方法时web容器负责创建一个request和一个response对象作为doFilter的参数传递进来 该request和response就是在访问目标资源的service方法时的request和response(其实不是同一个对象,但是里面的数据是一样的) FilterChain:过滤器链对象,通过该对象的doFilter方法可以放行该请求
Filter的配置url-pattern配置时 注意:url-pattern可以使用servlet-name替代,也可以混用(开发中url-pattern用的多) dispatcher:访问的方式(了解,基本不用,面试也不问) 总结Filter的作用?
登陆的基本实现<!--用于提示用户名和密码错误-->
<div>
<span style="color: red">${info }</span>
</div>//web层
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
UserService service = new UserService();
User user = service.login(username,password);
if (user == null) {
//登陆失败
request.setAttribute("info", "用户名或密码错误");
request.setAttribute("username", username);//把用户名带回去页面
request.getRequestDispatcher("/login.jsp").forward(request, response);
}else {
//登陆成功,把用户对象存放在session中
request.getSession().setAttribute("user", user);
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
}<!--index.jsp-->
<c:if test="${sessionScope.user == null }"> <!--${empty user }-->
<li><a href="login.jsp">登录</a></li>
<li><a href="register.jsp">注册</a></li>
</c:if>
<c:if test="${sessionScope.user != null }"> <!--${not empty user }-->
<li>欢迎:${sessionScope.user.realname }</li>
<li><a href="javascript:void(0)">退出</a></li>
</c:if>自动登录后期开发会接触到token来记住登陆 把用户信息存放到cookie,访问的时候带过去自动帮你登陆.但是这样做的话,每个servlet都要加上自动登录的逻辑 在filter中一般都会对request进行强转-->HttpServletRequest
//登陆成功后
String autoLogin = request.getParameter("autoLogin");//null or "autoLogin"
if(autoLogin != null && autoLogin.equals("autoLogin")) {
Cookie cookie_username = new Cookie("username", username);
Cookie cookie_pwd = new Cookie("password", password);
cookie_username.setMaxAge(60 * 24 * 3);
cookie_pwd.setMaxAge(60 * 24 * 3);
response.addCookie(cookie_username);
response.addCookie(cookie_pwd);
}//filter
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
User user = (User) req.getSession().getAttribute("user");
if(user != null) {
chain.doFilter(request, response);
return;
}
String usrename = null;
String password = null;
Cookie[] cookies = req.getCookies();
if (cookies == null) {
chain.doFilter(request, response);
return;
}
for (Cookie co : cookies) {
if ("username".equals(co.getName())) {
usrename = co.getValue();
}
if ("password".equals(co.getName())) {
password = co.getValue();
}
}
if(usrename != null && password != null) {
UserService service = new UserService();
user = service.login(usrename, password);
}
if(user == null) {
chain.doFilter(request, response);
return;
}else {
req.getSession().setAttribute("user", user);
chain.doFilter(req, response);
}
}解决全局乱码问题class EncoderRequest extends HttpServletRequestWrapper {
private HttpServletRequest request = null;
private boolean isGet = false;
public EncoderRequest(HttpServletRequest request) {
super(request);
this.request = request;
isGet = "get".equals(request.getMethod().toLowerCase())? true:false;
}
@Override
public String getParameter(String name) {
String parameter = request.getParameter(name);
if (isGet) {
try {
parameter = new String(parameter.getBytes("iso8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return parameter;
}
}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
req.setCharacterEncoding("utf-8");
res.setContentType("utf-8");
EncoderRequest enRequest = new EncoderRequest(req);
chain.doFilter(enRequest, response);
}
|
|