com.jsj.filter====新闻发布系统(7)
2020-05-15
这个是拦截器,可以看做保安
com.jsj.filter
AdminFilter
1 package com.jsj.filter; 2 3 import javax.servlet.*; 4 import javax.servlet.annotation.WebFilter; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 import java.io.IOException; 8 9 /** 10 * 管理员认证拦截 11 */ 12 @WebFilter(urlPatterns = "/admin/manage/*") 13 public class AdminFilter implements Filter { 14 15 @Override 16 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 17 HttpServletRequest request = (HttpServletRequest) servletRequest; 18 HttpServletResponse response = (HttpServletResponse) servletResponse; 19 if (request.getSession().getAttribute("adminStatus")!=null&& (boolean) request.getSession().getAttribute("adminStatus")) 20 filterChain.doFilter(servletRequest, servletResponse); 21 else { 22 response.setContentType("text/html;charset=UTF-8"); 23 response.getWriter().println("您不是管理员,无权访问该资源!请进行<a href='/admin'>管理员登录</a>"); 24 } 25 } 26 27 }
CharterEncodingFilter
1 package com.jsj.filter; 2 3 import javax.servlet.*; 4 import javax.servlet.annotation.WebFilter; 5 import javax.servlet.annotation.WebInitParam; 6 import javax.servlet.http.HttpServletRequest; 7 import java.io.IOException; 8 9 /** 10 * 请求编码过滤器 11 */ 12 @WebFilter(urlPatterns = "/*",initParams = { @WebInitParam(name = "CharacterEncoding", value = "UTF-8")}) 13 public class CharacterEncodingFilter implements Filter { 14 15 private String characterEncoding; 16 17 @Override 18 public void init(FilterConfig filterConfig) { 19 this.characterEncoding = filterConfig.getInitParameter("CharacterEncoding"); 20 } 21 22 @Override 23 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 24 HttpServletRequest request = (HttpServletRequest) servletRequest; 25 request.setCharacterEncoding(characterEncoding); 26 filterChain.doFilter(request,servletResponse); 27 } 28 }
会当凌绝顶,一览众山小