web开发中经常会遇到浏览网页时,需要用户登陆之后才能访问一些重要的页面,当你访问一些“非法”页面时,也就是如果检查你还没有登录进该系统,则需要先登录,只要你成功登录就可以访问信管内容,实现该功能需要
继承拦截器HandlerInterceptorAdapter,这个类中有三个重要的方法,灰色老哥方法可以先不关注,主要代码实现是绿色那一部分,代码如下:
/**
* @author tony
* @date 2014-12-17
*/
/**
* 登录拦截器,只有登录之后才能访问
*/
public class LoginInterceptor extends HandlerInterceptorAdapter{
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
super.afterCompletion(request, response, handler, ex);
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
}
// 应许通过的URL
private static final String[] IGNORE_URI = {"/login.from","/toLogin.from"};
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String url = request.getRequestURI().toString();
System.out.println(url);
boolean flag = false;
for (String s : IGNORE_URI) {
if (url.contains(s)) { // 如果是登陆页面的请求 则放过
flag = true;
break;
}}
if(!flag){
User user = (User)request.getSession().getAttribute("user");
System.out.println(user);
if(user == null){ // 检查是否登陆,否则跳回登陆页面
PrintWriter out = response.getWriter();
StringBuilder builder = new StringBuilder();
builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
builder.append("alert(\"您还未登录,请先登录.\");");
builder.append("window.top.location.href=\"");
builder.append("/StudentSystem/login/toLogin.from\";</script>");
out.print(builder.toString());
out.close();
return false;
}}
return true;
}}
当然实现了登录检查之后,需要将自定义这个拦截器在主配置文件中注册
spring_mvc.xml注册拦截器代码如下:
<!-- 配置登陆拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<!--path="/**"//**表示所有文件夹及子文件夹 -->
<mvc:mapping path="/**"/>
<bean id="loginInterceptor" class="edu.nwsuaf.xc.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
这个是在springMVC下实现的。