SpringMVC 使用注解完成登录拦截
为了实现用户登录拦截你是否写过如下代码呢?
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 使用注解完成登录拦截的更多相关文章
- 基于springmvc开发注解式ip拦截器
一.注解类 @Documented @Target({ElementType.TYPE,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) ...
- 大型运输行业实战_day05_1_登录+注销+表单重复提交+登录拦截器
1.登录 登录实现如下步骤: 1.在首页中添加登录按钮 html代码如下: <%@ page contentType="text/html;charset=UTF-8" la ...
- 在springMVC中使用自定义注解来进行登录拦截控制
1:java注解使用是相当频繁,特别是在搭建一些框架时,用到类的反射获取方法和属性,用的尤其多. java中元注解有四个: @Retention @Target @Document ...
- springMvc基于注解登录拦截器
1.首先先定义一个拦截器注解 @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) p ...
- 04springMVC结构,mvc模式,spring-mvc流程,spring-mvc的第一个例子,三种handlerMapping,几种控制器,springmvc基于注解的开发,文件上传,拦截器,s
1. Spring-mvc介绍 1.1市面上流行的框架 Struts2(比较多) Springmvc(比较多而且属于上升的趋势) Struts1(即将被淘汰) 其他 1.2 spring-mv ...
- springboot+springmvc拦截器做登录拦截
springboot+springmvc拦截器做登录拦截 LoginInterceptor 实现 HandlerInterceptor 接口,自定义拦截器处理方法 LoginConfiguration ...
- springmvc 自定义注解
1. 自定义一个注解 @Documented //文档生成时,该注解将被包含在javadoc中,可去掉 @Target(ElementType.METHOD)//目标是方法 @Retention(Re ...
- 用户登录拦截器查询到登录用户后如何将用户信息传递到后面的Controller
taotao创建订单代码中之前忘了加入用户信息,那么加上呢? 分析:用户创建订单的时候,我们会强制要求用户先登录,也就是说,创建订单的Controller执行时,一定是用户已经登录了的,而用户只要登录 ...
- springMVC自定义注解实现用户行为验证
最近在进行项目开发的时候需要对接口做Session验证 1.自定义一个注解@AuthCheckAnnotation @Documented @Target(ElementType.METHOD) @I ...
随机推荐
- windows安装theano和keras
系统: Windows 2008 python版本: Anaconda3 1. theano 安装 pip install theano 2. 安装g++ 下载安装mingw, 推荐版本tdm64-g ...
- 嵌入式开发为什么选择C语言作为开发语言?
了解嵌入式开发的朋友们都非常的清楚其核心的开发语言为C语言,C语言在嵌入式开发的过程中占有十分重要的地位,可以说两者之间“你中有我,我中有你”.但是有很多人会想,有那么多的开发语言为什么会单单的选择C ...
- E. Arson In Berland Forest(思维,找二维阵列中的矩阵,二分)
题:https://codeforces.com/contest/1262/problem/E 分析:预处理出阵列中的矩阵,然后二分答案还原题目的烧火过程,判断是否满足要求 #include<b ...
- PAT甲级——1152.Google Recruitment (20分)
1152 Google Recruitment (20分) In July 2004, Google posted on a giant billboard along Highway 101 in ...
- memory barrier 内存栅栏 并发编程
并发编程 memory barrier (内存栅栏) CPU级 1.CPU中有多条流水线,执行代码时,会并行进行执行代码,所以CPU需要把程序指令 分配给每个流水线去分别执行,这个就是乱序执行: 2. ...
- python基础——认识(if __name__ == ‘__main__’:)
我们在写代码时,经常会用到这一句:if __name__ == '__main__',那么加这一句有什么用呢?实际上,它起到到了一个代码保护功能,它能够让别人在导入你写的模块情况下,无法看到和运行if ...
- 【Python杂货铺】速学python基础
"人生苦短,我学python"是编程届的名言.用python写小脚本的便捷性,让很多其他语言的学习者把python当作辅助语言.拥有了某一个语言的功底,再来学习另外一种语言应该是十 ...
- 领导力 / LeaderShip
领导力 / LeaderShip 什么是领导力? 结合我自己的经验,谈谈理解. 我们人类社会,发展到现在,已经成为了一个集合体,这一点在工业革命之前,表现的极为明显. 常见的社会发展形态,会按照人与人 ...
- idea整合mybatis逆向工程
--pom.xml添加插件 <build> <finalName>hnapi</finalName> <plugins> <plugin> ...
- 43)PHP,mysql_fetch_row 和mysql_fetch_assoc和mysql_fetch_array
mysql_fetch_row 提取的结果是没有查询中的字段名了(也就是没有键id,GoodsName,只有值),如下图: mysql_fetch_assoc 提取的结果有键值,如下图: mysq ...