本文主要是介绍SpringMVC-Interceptor拦截Session登录,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
背景:
开发的项目都需要账号密码登录才可以查看网站的内容,所以我们设计时需要考虑,用户进入网站只能从一个我们设计的规范通道进入即通过注册的账号密码登录,其他方法都是非法的和不允许的,所以我们就要对非法的访问进行拦截并跳转到用户登录页面。
这里主要是讲SpringMVC拦截器Interceptor的相关配置和介绍。
首先新建一个自定义的拦截器:
LoginInterceptor.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;import com.sgcc.uds.fs.client.UserToken;/*** @author lyx* * 2015-8-17上午9:53:23***登录拦截器*/
public class LoginInterceptor implements HandlerInterceptor {//日志protected Logger log = Logger.getLogger(getClass());public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handle) throws Exception {//创建sessionHttpSession session =request.getSession();//无需登录,允许访问的地址String[] allowUrls =new String[]{"/toLogin","/login"};//获取请求地址String url =request.getRequestURL().toString();//获得session中的用户UserToken user =(UserToken) session.getAttribute("userToken");for (String strUrl : allowUrls) {if(url.contains(strUrl)){return true;}}if(user ==null){throw new UnLoginException("您尚未登录!"); }//重定向//response.sendRedirect(request.getContextPath()+"/toLogin");return true;}@Overridepublic void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {// TODO Auto-generated method stub}@Overridepublic void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)throws Exception {// TODO Auto-generated method stub}}
新建一个登录失败异常类:
(注:也可以不建这个类直接在拦截器中进行重定向)
UnLoginException.java
import java.io.IOException;/*** @author lyx* * 2015-8-17上午10:57:24**fs-config-web.com.sgcc.uds.fs.config.web.interceptor.UnLoginException*登录失败异常类*/
public class UnLoginException extends Exception{/*** */private static final long serialVersionUID = 1L;public UnLoginException() {super();// TODO Auto-generated constructor stub}public UnLoginException(String message) throws IOException {super(message);// TODO Auto-generated constructor stub}}
SpringMVC配置文件:
ApplicationContext-config-web.xml
<!-- 拦截器 --><mvc:interceptors><mvc:interceptor> <!-- 拦截全部地址 --><mvc:mapping path="/**"/> <!-- 登录拦截类 --><bean id="loginInterceptor" class="com.sgcc.uds.fs.config.web.interceptor.LoginInterceptor"></bean></mvc:interceptor> </mvc:interceptors><!-- 异常 --><bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <登录失败异常类><prop key="com.sgcc.uds.fs.config.web.interceptor.UnLoginException">redirect:/toLogin</prop> </props> </property> </bean>
LoginController.java
import java.util.Map;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;import com.sgcc.uds.fs.client.UserToken;
import com.sgcc.uds.fs.config.web.util.ResultUtil;@Controller
public class LoginController {@RequestMapping(value = "/", method = RequestMethod.GET)public String welcome(HttpServletRequest request){//TODO 判断有无session,有直接到首页if(request.getSession().getAttribute("userToken")!=null){return "/index";}return "login";}@RequestMapping(value = "/toLogin", method = RequestMethod.GET)public String toLogin(HttpServletRequest request){//TODO 判断有无session,有直接到首页if(request.getSession().getAttribute("userToken")!=null){return "/index";}return "login";}@RequestMapping(value = "/login", method = RequestMethod.POST)@ResponseBodypublic Map<String, Object> login(@RequestParam(required=true,value="loginName") String loginName, @RequestParam(required=true,value="pwd") String pwd,HttpServletRequest request){ResultUtil result = new ResultUtil();try { if(null != loginName && loginName.equals("admin") && null != pwd && pwd.equals("admin") ){//TODO 登陆成功,保存sessionHttpSession session =request.getSession();UserToken userToken =new UserToken("admin","admin", "bucketName");session.setAttribute("userToken",userToken);//设置超时无效//session.setMaxInactiveInterval(20);}else{result.setSuccess(false);result.setMsg("用户名或密码错误!");}} catch (Exception e) {result.setSuccess(false);result.setMsg("系统内部异常!");}return result.getResult();}}
这样就可以实现对用户非法访问网站进行拦截,保证网站的安全性。
这篇关于SpringMVC-Interceptor拦截Session登录的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!