为了实现用户登录拦截你是否写过如下代码呢?

1. 基于Filter

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; public class AuthenticationFilter implements Filter {
private FilterConfig filterConfig;
private String onErrorUrl; public void init(FilterConfig filterConfig) throws ServletException {
// 从 filterConfig 中的得到错误页
this.filterConfig = filterConfig;
this.onErrorUrl = filterConfig.getInitParameter("onError");
if(this.onErrorUrl == null || "".equals(this.onErrorUrl))
this.onErrorUrl = "onError";
} public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest)request;
session = httpRequest.getSession();
if(null == session.getAttribute("_LOGIN_USER_") && !"/login".equals(httpRequest.getServletPath())) {
httpRequest.getRequestDispatcher("/"+this.onErrorUrl).forward(request, response);
}else{
chain.doFilter(request, response);
}
} public void destroy() { } }

2. 基于Struts

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor; @SuppressWarnings("serial")
public class LoginInterceptor extends AbstractInterceptor { @Override
public String intercept(ActionInvocation invocation) throws Exception {
String currentUser="currentUser";
HttpServletRequest request=ServletActionContext.getRequest();
HttpServletResponse response=ServletActionContext.getResponse();
HttpSession session=request.getSession();
if(request.getRequestURI().endsWith("login.action")){
return invocation.invoke();
} else {
if(session.getAttribute(currentUser)!=null){
return invocation.invoke();
}else{
response.sendRedirect(request.getContextPath()+"/login.jsp");
}
}
return null;
}
}

3. 基于SpringMVC

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import cn.edu.hdc.util.Constants; /**
* @ClassName: LoginInterceptor
* @Description: 登录拦截器
* @author loweir hbloweir@163.com
* @date 2016年4月27日 上午8:06:11
*/
public class LoginInterceptor implements HandlerInterceptor {
/**
* 在目标方法前被调用,返回 true 继续
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
try {
String url = request.getRequestURI();
// 如果不是登录操作 判断 session
if (!url.endsWith("login")) {
if (request.getSession().getAttribute(Constants.CURRENT_USER) == null) {
response.sendRedirect(request.getContextPath() + "/login.jsp");
return false;
}
} }
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} @Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
} @Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception { }
}

如何使用自定义注解完成自定义拦截呢?

登录注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; /**
* Created by loweir on 2017/5/14 17:19
* <p>
* author: 张瑀楠
* email: hbloweir@163.com
* 负责登录拦截
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface WebLoginRequired {
String value() default ""; // 未登录时需要跳转的路径
}

SpringMVC 拦截器设置

import com.ainsoft.globalshoperp.component.constant.WebLogin;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Created by loweir on 2017/5/14 17:14
* <p>
* author: 张瑀楠
* email: hbloweir@163.com
*/
public class LoginInterceptor implements HandlerInterceptor { private static Log logger = LogFactory.getLog(LoginInterceptor.class); public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception { if (logger.isDebugEnabled()) {
logger.debug("拦截器启动");
}
/*
* 判断是否为 HandlerMethod.class
* 如果不是说明当前请求并不是 SpringMVC 管理,
* 如果不是再自行根据业务做响应操作,这里直接返回 true
*/
if (HandlerMethod.class.isInstance(handler)) {
HandlerMethod handlerMethod = (HandlerMethod) handler; // 判断该 handler 是否有WebLoginRequired注解
WebLoginRequired webLoginRequired = handlerMethod.getMethod().getDeclaredAnnotation(WebLoginRequired.class); // 如果该 handler 没有WebLoginRequired注解,判断所属Controller 是否包含注解
if (null == webLoginRequired) {
webLoginRequired = handlerMethod.getBeanType().getAnnotation(WebLoginRequired.class);
} // 如果需要 WebLoginRequired 判断 session
if (null != webLoginRequired) {
if (httpServletRequest.getSession().getAttribute(WebLogin.CURRENTUSER) == null) {
String executeURL = webLoginRequired.value();
if (StringUtils.isBlank(executeURL)) {
executeURL = WebLogin.LOGIN;
} httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + executeURL);
return false;
}
}
}
return true;
} public void postHandle(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("postHandler");
}
} public void afterCompletion(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("afterCompletion");
}
}
}

最终 controller 写法

1. 不需要登录权限的

类和方法都不需要注解

@Controller
@RequestMapping("auth")
public class AuthController { @RequestMapping("login")
public String login() {
return "login";
}
}

2. 整个 controller 内都需要登录权限

在类上添加注解即可

@Controller
@WebLoginRequired
@RequestMapping("order")
public class OrderController { @RequestMapping("index")
public String index() {
return "index";
}
}

3. controller 某个方法需要登录权限

只在需要登录权限的方法上添加注解

在注解上可以指定需要重定向的链接

如果不指定则默认到 login

@Controller
@RequestMapping("order")
public class OrderController { @RequestMapping("index")
public String index() {
return "index";
} // 需要登录
@WebLoginRequired
@RequestMapping("add")
public String index() {
return "index";
} // 需要登录,如果未登录跳到 error
@WebLoginRequired("error")
@RequestMapping("delete")
public String index() {
return "index";
}
}

SpringMVC 使用注解完成登录拦截的更多相关文章

  1. 基于springmvc开发注解式ip拦截器

    一.注解类 @Documented @Target({ElementType.TYPE,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) ...

  2. 大型运输行业实战_day05_1_登录+注销+表单重复提交+登录拦截器

    1.登录 登录实现如下步骤: 1.在首页中添加登录按钮 html代码如下: <%@ page contentType="text/html;charset=UTF-8" la ...

  3. 在springMVC中使用自定义注解来进行登录拦截控制

    1:java注解使用是相当频繁,特别是在搭建一些框架时,用到类的反射获取方法和属性,用的尤其多. java中元注解有四个: @Retention     @Target     @Document  ...

  4. springMvc基于注解登录拦截器

    1.首先先定义一个拦截器注解 @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) p ...

  5. 04springMVC结构,mvc模式,spring-mvc流程,spring-mvc的第一个例子,三种handlerMapping,几种控制器,springmvc基于注解的开发,文件上传,拦截器,s

     1. Spring-mvc介绍 1.1市面上流行的框架 Struts2(比较多) Springmvc(比较多而且属于上升的趋势) Struts1(即将被淘汰) 其他 1.2  spring-mv ...

  6. springboot+springmvc拦截器做登录拦截

    springboot+springmvc拦截器做登录拦截 LoginInterceptor 实现 HandlerInterceptor 接口,自定义拦截器处理方法 LoginConfiguration ...

  7. springmvc 自定义注解

    1. 自定义一个注解 @Documented //文档生成时,该注解将被包含在javadoc中,可去掉 @Target(ElementType.METHOD)//目标是方法 @Retention(Re ...

  8. 用户登录拦截器查询到登录用户后如何将用户信息传递到后面的Controller

    taotao创建订单代码中之前忘了加入用户信息,那么加上呢? 分析:用户创建订单的时候,我们会强制要求用户先登录,也就是说,创建订单的Controller执行时,一定是用户已经登录了的,而用户只要登录 ...

  9. springMVC自定义注解实现用户行为验证

    最近在进行项目开发的时候需要对接口做Session验证 1.自定义一个注解@AuthCheckAnnotation @Documented @Target(ElementType.METHOD) @I ...

随机推荐

  1. poj1386单词连接(欧拉欧拉欧拉)

    ///单词连接,欧拉回路通路都可以(有向图) ///主要构图:比如possibilities就构造p->s的边////题目大意:给你若干个字符串,一个单词的尾部和一个单词的头部相同那么这两个单词 ...

  2. UML-各阶段如何编写用例

    1.前文回顾 用例的根本价值:发现谁是关键参与者,他要实现什么目标? 需求分类,见<进化式需求>:制品,见<初始不是需求阶段>中的表4-1 2.各阶段编写何种用例,均针对下图展 ...

  3. 求Fibonacii数列的第40个数

    public class Fibonacii{ public int m1(int n){ if(n == 1||n == 2){ return 1; } return m1(n-1) + m1(n- ...

  4. Sqlite教程(4) Activity

    之前我们已经有了DbHelper.Data Access Object.Configuration. 那麽现在就是由Activity去创建它们,然後就可以存取Sqlite. 架构图表示了它们的关系. ...

  5. PyTorch基础——预测共享单车的使用量

    预处理实验数据 读取数据 下载数据 网盘链接:https://pan.baidu.com/s/1n_FtZjAswWR9rfuI6GtDhA 提取码:y4fb #导入需要使用的库 import num ...

  6. django框架进阶-分页-长期维护

    ##################   分页    ####################### 分页, django有自己内置的分页,但是功能不是很强大,所以自己写一个分页, web页面数据非常 ...

  7. DAG Optimal Coin Change

    题目描述 In a 10-dollar shop, everything is worthy 10 dollars or less. In order to serve customers more ...

  8. [LC] 437. Path Sum III

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  9. centos 6.* 修改时间

    一.查看Centos的时区和时间 1.使用date命令查看Centos时区 [root@VM_centos ~]# date -R Mon, 26 Mar 2018 19:14:03 +0800 2. ...

  10. Python-scapy学习

    scapy-arpspoof from scapy.all import Ether,ARP,sendp,getmacbyip Ether:用来构建以太网数据包 ARP:构建ARP数据包的类 send ...