SpringMVC-Interceptor攔截Session登錄
背景:
開發的項目都須要賬號password登錄才幹夠查看站點的內容,所以我們設計時須要考慮,用戶進入站點僅僅能從一個我們設計的規範通道進入即通過註冊的賬號password登錄,其它方法都是非法的和不同意的,所以我們就要對非法的訪問進行攔截並跳轉到用戶登錄頁面。
這裏主要是講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 { //創建session HttpSession 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; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // TODO Auto-generated method stub } @Override public 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) @ResponseBody public 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 登陸成功,保存session HttpSession session =request.getSession(); UserToken userToken =new UserToken("admin","admin", "bucketName"); session.setAttribute("userToken",userToken); //設置超時無效 //session.setMaxInactiveInterval(20); }else{ result.setSuccess(false); result.setMsg("username或password錯誤!"); } } catch (Exception e) { result.setSuccess(false); result.setMsg("系統內部異常!"); } return result.getResult(); } }
這樣就能夠實現對用戶非法訪問站點進行攔截,保證站點的安全性。
SpringMVC-Interceptor攔截Session登錄