在java web工程中实现登入和安全验证

登入页面的话我们之前做过直接可以拿来用翻一翻之前的博客就可以找到

在这个基础上添加验证功能

代码如下:

 1 package security;
 2 /**
 3  * @author 鐜嬭儨鍗?
 4  */
 5 import java.io.IOException;
 6 import javax.servlet.Filter;
 7 import javax.servlet.FilterChain;
 8 import javax.servlet.FilterConfig;
 9 import javax.servlet.ServletException;
10 import javax.servlet.ServletRequest;
11 import javax.servlet.ServletResponse;
12 import javax.servlet.annotation.WebFilter;
13 import javax.servlet.annotation.WebInitParam;
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 
17 import org.apache.commons.lang3.ObjectUtils;
18 
19 @WebFilter(urlPatterns = { "/console/*", "/admin/*" }, initParams = {
20         @WebInitParam(name = "INDEX_VIEW", value = "/index.jsp") })
21 public class MemberFilter implements Filter {
22 
23     private String INDEX_VIEW;
24 
25     @Override
26     public void init(FilterConfig config) throws ServletException {
27         this.INDEX_VIEW = config.getInitParameter("INDEX_VIEW");
28     }
29 
30     @Override
31     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
32             throws IOException, ServletException {
33         HttpServletRequest req = (HttpServletRequest) request;
34 
35         if (ObjectUtils.anyNotNull(req.getSession().getAttribute("user"))) {
36             chain.doFilter(request, response);
37         } else {
38             HttpServletResponse resp = (HttpServletResponse) response;
39             resp.sendRedirect(req.getContextPath() + INDEX_VIEW);
40         }
41     }
42 
43     @Override
44     public void destroy() {
45     }
46 
47 }

如果账号和密码输入正确就可以进入后台反之如果输入错误就返回登入页面

转载于:https://www.cnblogs.com/q2546/p/11066457.html

你可能感兴趣的:(在java web工程中实现登入和安全验证)