為了實現(xiàn)用戶登錄攔截你是否寫過如下代碼呢?
1. 基于Filter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
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 { /** * 在目標方法前被調(diào)用,返回 true 繼續(xù) */ @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 { } } |
如何使用自定義注解完成自定義攔截呢?
登錄注解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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 * 負責(zé)登錄攔截 */ @Retention (RetentionPolicy.RUNTIME) @Target ({ElementType.TYPE,ElementType.METHOD}) public @interface WebLoginRequired { String value() default "" ; // 未登錄時需要跳轉(zhuǎn)的路徑 } |
SpringMVC 攔截器設(shè)置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
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 管理, * 如果不是再自行根據(jù)業(yè)務(wù)做響應(yīng)操作,這里直接返回 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. 不需要登錄權(quán)限的
類和方法都不需要注解
1
2
3
4
5
6
7
8
9
|
@Controller @RequestMapping ( "auth" ) public class AuthController { @RequestMapping ( "login" ) public String login() { return "login" ; } } |
2. 整個 controller 內(nèi)都需要登錄權(quán)限
在類上添加注解即可
1
2
3
4
5
6
7
8
9
10
|
@Controller @WebLoginRequired @RequestMapping ( "order" ) public class OrderController { @RequestMapping ( "index" ) public String index() { return "index" ; } } |
3. controller 某個方法需要登錄權(quán)限
只在需要登錄權(quán)限的方法上添加注解
在注解上可以指定需要重定向的鏈接
如果不指定則默認到 login
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
@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 如何使用注解完成登錄攔截的詳細內(nèi)容,更多關(guān)于SpringMVC 使用注解完成登錄攔截的資料請關(guān)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://www.cnblogs.com/zyndev/p/7613006.html