How SpringMVC uses annotations to complete login interception (with code)

This article mainly introduces how SpringMVC uses annotations to complete login interception, to help everyone better understand and learn to use springMVC, interested friends can understand

In order to achieve user login interception, have you written the following code?

1. Based on 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. Based on 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. Based on 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 [email protected]
 * @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 {
    
    
		
	}
}

How to use custom annotations to complete custom interception?

Login note

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: [email protected]
 * 负责登录拦截
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({
    
    ElementType.TYPE,ElementType.METHOD})
public @interface WebLoginRequired {
    
    
 String value() default ""; // 未登录时需要跳转的路径
}

SpringMVC interceptor settings

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: [email protected]
 */
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");
  }
 }
}

Final controller writing

1. No need to log in

No annotations are required for classes and methods

@Controller
@RequestMapping("auth")
public class AuthController {
    
    

 @RequestMapping("login")
 public String login() {
    
    
  return "login";
 }
}

####2. The entire controller requires login permission. Just
add a comment on the class

@Controller
@WebLoginRequired
@RequestMapping("order")
public class OrderController {
    
    

 @RequestMapping("index")
 public String index() {
    
    
  return "index";
 }
}

3. A method of the controller requires login permission

Only add a comment
on the method that requires login permission . You can specify the link that needs to be redirected on the comment.
If not specified, it will default to 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";
 }
}

The above is the detailed content of how SpringMVC uses annotations to complete login interception. I hope it will be helpful to everyone's learning, and I hope you can support it

The latest high-frequency interview questions collected in 2021 (all organized into documents), there are a lot of dry goods, including mysql, netty, spring, thread, spring cloud, jvm, source code, algorithm and other detailed explanations. There are also detailed learning plans and interviews. Questions, etc., friends who need to obtain these content, please add Q Junyang: 547998459

Guess you like

Origin blog.csdn.net/p1830095583/article/details/114746336