SpringMVC攔截器實現登入認證_java

來源:互聯網
上載者:User

部落格以Demo的形式講訴攔截器的使用

項目結構如圖:


需要的jar:有springMVC配置需要的jar和jstl需要的jar


SpringMVC包的作用說明:

aopalliance.jar:這個包是AOP同盟API包,裡麵包含了針對面向切面的介面。通常spring等其它具備動態織入功能的架構依賴這個jar

spring-core.jar:這個jar 檔案包含Spring 架構基本的核心工具類。Spring 其它組件要都要使用到這個包裡的類,是其它組件的基本核心,當然你也可以在自己的應用系統中使用這些工具類。
外部依賴Commons Logging, (Log4J)。

spring-beans.jar:這個jar 檔案是所有應用都要用到的,它包含訪問設定檔、建立和管理bean 以及進行Inversion of Control /
Dependency Injection(IoC/DI)操作相關的所有類。如果應用只需基本的IoC/DI 支援,引入spring-core.jar 及spring-beans.jar 檔案
就可以了。

spring-aop.jar:這個jar 檔案包含在應用中使用Spring 的AOP 特性時所需的類和源碼級中繼資料支援。使用基於AOP 的Spring特性,如聲明型交易管理(Declarative Transaction Management),也要在應用裡包含這個jar包。

外部依賴spring-core, (spring-beans,AOP Alliance, CGLIB,Commons Attributes)。

spring-context.jar:這個jar 檔案為Spring 核心提供了大量擴充。可以找到使用Spring ApplicationContext特性時所需的全部類,JDNI
所需的全部類,instrumentation組件以及校正Validation 方面的相關類。
外部依賴spring-beans, (spring-aop)。
spring-context-support:Spring-context的擴充支援,用於MVC方面

spring-web.jar:這個jar 檔案包含Web 應用程式開發時,用到Spring 架構時所需的核心類,包括自動載入Web Application Context 特性的類、Struts 與JSF整合類、檔案上傳的支援類、Filter 類和大量工具輔助類。

外部依賴spring-context, Servlet API, (JSP API, JSTL, Commons FileUpload, COS)。

spring-webmvc.jar:這個jar 檔案包含Spring MVC 架構相關的所有類。包括架構的Servlets,Web MVC架構,控制器和視圖支援。當然,如果你的應用使用了獨立的MVC 架構,則無需這個JAR 檔案裡的任何類。

外部依賴spring-web, (spring-support,Tiles,iText,POI)。

spring-aspects.jar:提供對AspectJ的支援,以便可以方便的將面向方面的功能整合進IDE中,比如Eclipse AJDT。
外部依賴。

spring-jdbc.jar:這個jar 檔案包含對Spring 對JDBC 資料訪問進行封裝的所有類。
外部依賴spring-beans,spring-dao。

spring-test.jar:對Junit等測試架構的簡單封裝

spring-tx.jar:Spring的tx交易處理的jar

spring-expression.jar:Spring運算式語言

編寫控制器:

package com.mvc.action;  import javax.servlet.http.HttpSession;  import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;  /**  * 登入認證的控制器  */ @Controller public class LoginControl {   /**   * 登入   * @param session   *   HttpSession   * @param username   *   使用者名稱   * @param password   *   密碼   * @return   */  @RequestMapping(value="/login")  public String login(HttpSession session,String username,String password) throws Exception{    //在Session裡儲存資訊   session.setAttribute("username", username);   //重新導向   return "redirect:hello.action";  }    /**   * 退出系統   * @param session   *   Session   * @return   * @throws Exception   */  @RequestMapping(value="/logout")  public String logout(HttpSession session) throws Exception{   //清除Session   session.invalidate();      return "redirect:hello.action";  }       } 

編寫攔截器:

package com.mvc.interceptor;  import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;  import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; /**  * 登入認證的攔截器  */ public class LoginInterceptor implements HandlerInterceptor{   /**   * Handler執行完成之後調用這個方法   */  public void afterCompletion(HttpServletRequest request,    HttpServletResponse response, Object handler, Exception exc)    throws Exception {     }   /**   * Handler執行之後,ModelAndView返回之前調用這個方法   */  public void postHandle(HttpServletRequest request, HttpServletResponse response,    Object handler, ModelAndView modelAndView) throws Exception {  }   /**   * Handler執行之前調用這個方法   */  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,    Object handler) throws Exception {   //擷取請求的URL   String url = request.getRequestURI();   //URL:login.jsp是公開的;這個demo是除了login.jsp是可以公開訪問的,其它的URL都進行攔截控制   if(url.indexOf("login.action")>=0){    return true;   }   //擷取Session   HttpSession session = request.getSession();   String username = (String)session.getAttribute("username");      if(username != null){    return true;   }   //不合格,跳轉到登入介面   request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);      return false;  }  } 

SpringMVC的設定檔:

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"  xmlns:aop="http://www.springframework.org/schema/aop"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:context="http://www.springframework.org/schema/context"  xmlns:mvc="http://www.springframework.org/schema/mvc"  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd   http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">      <!-- 使用組件掃描 -->   <!-- 將action掃描出來,在spring容器中進行註冊,自動對action在spring容器中進行配置 -->   <context:component-scan base-package="com.mvc.action" />      <!-- 項目的Handler   <bean name="/hello.action" class="com.mvc.action.HelloAction"></bean>    -->   <!-- 處理器映射器HandlerMapping -->   <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>      <!-- 處理器設配器HandlerAdapter -->   <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">    <property name="messageConverters">     <list>      <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>     </list>    </property>   </bean>    <!-- 視圖解析器ViewResolver -->   <!-- 解析jsp,預設支援jstl -->   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>    <property name="prefix" value="/WEB-INF/jsp/" />    <property name="suffix" value=".jsp" />   </bean>      <!-- 在實際開發中通常都需配置 mvc:annotation-driven標籤,這個標籤是開啟註解 -->   <mvc:annotation-driven></mvc:annotation-driven>   <!-- 攔截器 -->   <mvc:interceptors>    <!-- 多個攔截器,順序執行 -->    <mvc:interceptor>     <mvc:mapping path="/**"/>     <bean class="com.mvc.interceptor.LoginInterceptor"></bean>    </mvc:interceptor>   </mvc:interceptors>   </beans> 

登入介面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html>  <head>  <base href="<%=basePath%>">    <title>My JSP 'login.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">  <meta http-equiv="cache-control" content="no-cache">  <meta http-equiv="expires" content="0">   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  <meta http-equiv="description" content="This is my page">  <!--  <link rel="stylesheet" type="text/css" href="styles.css">  -->   </head>   <body>   <form action="${pageContext.request.contextPath}/login.action" method="post">   使用者名稱:<input type="text" name="username" /><br>   密碼:<input type="text" name="password" /><br>   <input type="submit" value="登入" />   </form>  </body> </html> 

登入成功後,跳轉的介面
hello.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://www.springframework.org/tags" prefix="spring" %> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html>  <head>  <base href="<%=basePath%>">    <title>My JSP 'hello.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">  <meta http-equiv="cache-control" content="no-cache">  <meta http-equiv="expires" content="0">   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  <meta http-equiv="description" content="This is my page">  <!--  <link rel="stylesheet" type="text/css" href="styles.css">  -->   </head>   <body>  目前使用者:${username}  <c:if test="${username!=null}">   <a href="${pageContext.request.contextPath }/logout.action">退出</a>  </c:if>  ${message}  </body> </html> 

HelloControl.java,我寫成HelloWorld形式的,自己要根據項目去改哦

package com.mvc.action;  import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping;  //標記這個類是一個Handler處理器 @Controller public class HelloAction{   @RequestMapping("/hello")//制定這個控制類對應的url  public String hello(Model model){   String message = "SpringMVC";   //為model添加Attribute   model.addAttribute("message",message);   return "hello";  } // public ModelAndView handleRequest(HttpServletRequest request, //   HttpServletResponse response) throws Exception { //  //  //在頁面上提示一行資訊 //  String message = "hello world!"; //  //  //通過request對象將資訊在頁面上展示 //  //request.setAttribute("message", message); //  //  ModelAndView modelAndView = new ModelAndView(); //  // 相當於request.setAttribute(), 將資料傳到頁面展示 //  //model資料 //  modelAndView.addObject("message", message); //  //設定視圖 //  modelAndView.setViewName("hello"); //  //  return modelAndView; // }        } 

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.