实现思路是编写过滤器,如果用户登录之后session中会存一个user。如果未登录就为null,就可以通过过滤器将用户重定向到登陆页面,让用户进行登陆,当然过滤器得判断用户访问的如果是登陆请求需要放行,如果不是就需要进行拦截并进行验证。登陆成功再session存存入user,这样过滤器每次都会通过。
1.首先编写验证登陆的过滤器
packagedanger.filter;importjava.io.IOException;importjavax.servlet.Filter;importjavax.servlet.FilterChain;importjavax.servlet.FilterConfig;importjavax.servlet.ServletException;importjavax.servlet.ServletRequest;importjavax.servlet.ServletResponse;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importdanger.bean.sys.User;/*** Servlet Filter implementation class LoginFilter*/
public class LoginFilter implementsFilter {/*** Default constructor.*/
publicLoginFilter() {//TODO Auto-generated constructor stub
}/***@seeFilter#destroy()*/
public voiddestroy() {//TODO Auto-generated method stub
}/***@seeFilter#doFilter(ServletRequest, ServletResponse, FilterChain)*/
public voiddoFilter(ServletRequest request, ServletResponse response, FilterChain chain)throwsIOException, ServletException {
HttpServletRequest req=(HttpServletRequest) request;
String path=req.getRequestURI();
System.out.println("reqURL----------" +path);//如果包含login.jsp证明是登陆就放行
if (path.contains("login") || path.contains("/js/") || path.contains("/image/") || path.contains("/css/")|| path.contains("message.jsp")|| path.contains("404.jsp")|| path.contains("/images/")) {
chain.doFilter(request, response);//放行
return;
}
HttpServletResponse res=(HttpServletResponse) response;
HttpSession session=req.getSession();
User user= (User) session.getAttribute("user");//如果session中存在user证明用户登录,可以放行。否则认为未登陆重定向到login.jsp
if (user == null) {
res.sendRedirect(req.getContextPath()+ "/login/login.jsp");
}else{
System.out.println("user----------"+user);
chain.doFilter(request, response);
}
}/***@seeFilter#init(FilterConfig)*/
public void init(FilterConfig fConfig) throwsServletException {//TODO Auto-generated method stub
}
}
if (path.contains("login") || path.contains("/js/") || path.contains("/image/") || path.contains("/css/") || path.contains("message.jsp")|| path.contains("404.jsp")|| path.contains("/images/")) { chain.doFilter(request, response); //放行 return; } 相当于是对登陆请求以及一些静态资源放行。(可以将一些静态资源放到统一的文件夹下面)
2.web.xml进行配置
loginFilter
danger.filter.LoginFilter
loginFilter
/*
3.进行测试:
项目名字为danger。再浏览器访问:http://localhost/danger/
控制台打印:
reqURL----------/danger/login/login.jsp
reqURL----------/danger/js/jquery-1.11.js
reqURL----------/danger/controls/login/js/gVerify.js
reqURL----------/danger/controls/login/css/login2.css
reqURL----------/danger/controls/login/js/login.js
reqURL----------/danger/image/logo.png
reqURL----------/danger/controls/login/images/1.jpg
页面被送到登陆界面。
4.对登陆的处理:(判断用户名与密码,并在session中添加user属性)
登陆表单(用户名与密码的name与Action的属性名字一样)
/login.action"name="loginform"accept-charset="utf-8"id="login_form"class="loginForm"method="post">
帐 号: