导包,实现javax.servlet.Filter接口
重写init、doFilter、destroy三个方法
public class CharacterEncodingFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
//服务器启动时初始化
System.out.println("CharacterEncodingFilter初始化!");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
System.out.println("CharacterEncodingFilter执行前...");
//让请求继续走,如果不写,程序到这里就被拦截停止了
chain.doFilter(request, response);
System.out.println("CharacterEncodingFilter执行后...");
}
public void destroy() {
//服务器关闭时销毁
System.out.println("CharacterEncodingFilter销毁!");
}
}
在web.xml中配置
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.yhr.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<!--过滤/servlet/下的任何请求-->
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取前端请求的参数
String username = req.getParameter("username");
if(username.equals("admin")){
req.getSession().setAttribute(Constant.USER_SESSION, req.getSession().getId());
resp.sendRedirect("/sys/success.jsp");
} else{
resp.sendRedirect("/error.jsp");
}
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if(httpRequest.getSession().getAttribute(Constant.USER_SESSION) == null){
httpResponse.sendRedirect("/error.jsp");
}
chain.doFilter(request,response);
}
原文:https://www.cnblogs.com/xiafrog/p/14344350.html