AI智能
改变未来

JavaWeb拦截器配置

####页面请求拦截

import javax.servlet.*;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class SysFilter implements Filter {public void init(FilterConfig filterConfig) throws ServletException {System.out.println("权限拦截启动");}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest request1 = (HttpServletRequest) request;HttpServletResponse response1 = (HttpServletResponse) response;if (request1.getSession().getAttribute(Constants.USER_SESSION)==null) {request1.setAttribute("error","请先登录!");request1.getRequestDispatcher("/login.jsp").forward(request1,response1);}else {chain.doFilter(request,response);}}public void destroy() {System.out.println("拦截器销毁");}}

####请求及响应编码配置

import javax.servlet.*;import java.io.IOException;public class CharacterEncodingFilter implements Filter {public void init(FilterConfig filterConfig) throws ServletException {System.out.println("过滤器初始化");}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");chain.doFilter(request,response);}public void destroy() {}}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » JavaWeb拦截器配置