<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Spring Security 登錄表單示例 > 原文: [https://howtodoinjava.com/spring-security/login-form-b??ased-spring-3-security-example/](https://howtodoinjava.com/spring-security/login-form-based-spring-3-security-example/) 學習使用[ Spring Security 教程](https://howtodoinjava.com/spring-security-tutorial/)中討論的詳細信息,將 **Spring Security 登錄表單**添加到任何 Spring Web 應用程序。 > 閱讀更多: [Spring Security 5 登錄表單示例[為 Spring 5 更新]](https://howtodoinjava.com/spring5/security5/login-form-example/) ## 1\. 背景資料 我們學會了在鏈接的帖子中集成 [**Spring 3 和 Hibernate**](https://howtodoinjava.com/spring/spring-orm/spring-3-and-hibernate-integration-tutorial-with-example/) 之間。 該應用程序是簡單的 Web 應用程序,它提供了一個視圖,用戶可以在其中添加/編輯員工。 使該應用程序安全。 本教程的**范圍**是: * 只有授權用戶才能訪問編輯員工屏幕。 * 未經授權的用戶應顯示登錄屏幕。 * 成功的憑據應轉發到編輯員工屏幕。 * 不成功的憑據應轉發到拒絕訪問屏幕。 * 應該有一個注銷應用程序的鏈接。 ## 2\. Spring Security Maven 依賴項 讓我們從第一步開始,即更新項目依賴項。 由于以下原因,它將在演示中添加以下`four sub-modules`: 1. `spring-security-core`:它包含核心身份驗證以及訪問控制類和接口。 2. `spring-security-web`:包含過濾器和相關的 Web 安全基礎結構代碼。 它還啟用了基于 URL 的安全性,我們將在此演示中使用它。 3. `spring-security-config`:它包含安全名稱空間解析代碼。 如果您使用 Spring Security XML 文件進行配置,則需要它。 4. `spring-security-taglibs`:它為訪問安全信息和在 JSP 中應用安全約束提供基本支持。 `pom.xml` ```java <properties> <org.springframework.version>3.0.5.RELEASE</org.springframework.version> </properties> <!-- Spring Security --> <dependency> <groupid>org.springframework.security</groupid> <artifactid>spring-security-core</artifactid> <version>${org.springframework.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupid>org.springframework.security</groupid> <artifactid>spring-security-web</artifactid> <version>${org.springframework.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupid>org.springframework.security</groupid> <artifactid>spring-security-config</artifactid> <version>${org.springframework.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupid>org.springframework.security</groupid> <artifactid>spring-security-taglibs</artifactid> <version>${org.springframework.version}</version> <type>jar</type> <scope>compile</scope> </dependency> ``` 現在使用“ `mvn compile`”命令更新項目中的依賴項。 ## 3\. 在`web.xml`中配置`DelegatingFilterProxy` Spring Security 的 Web 基礎結構完全基于標準 Servlet 過濾器。 這些過濾器在`web.xml`文件中定義,否則 servlet 容器將忽略它們。 在 Spring Security 中,過濾器類也是在應用程序上下文中定義的 Spring Bean,因此能夠利用 Spring 豐富的依賴注入機制和生命周期接口。 Spring 的 [`DelegatingFilterProxy`](http://static.springsource.org/spring/docs/2.0.8/api/org/springframework/web/filter/DelegatingFilterProxy.html) 提供了`web.xml`和應用上下文之間的鏈接。 `web.xml` ```java <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ``` 如果您沒有使用任何明確的過濾器定義,并且希望 spring 為您配置基本的基礎架構,則如上例所示,將過濾器名稱用作“ `springSecurityFilterChain`”。 請注意,您不應自己使用此 bean 名稱。 將其添加到`web.xml`后,就可以開始編輯 Spring Security 配置文件了。 Web 安全服務是使用元素配置的。 同樣不要忘記將安全配置文件放在上下文配置位置設置中。 `web.xml` ```java <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/employee-servlet.xml /WEB-INF/application-security.xml </param-value> </context-param> ``` 完整的`web.xml`文件如下所示: `web.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Archetype Created Web Application</display-name> <welcome-file-list> <welcome-file>/WEB-INF/index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>employee</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>employee</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/employee-servlet.xml /WEB-INF/application-security.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app> ``` ## 4\. 配置登錄注銷安全性 正如我們在上一節中了解到的那樣,將過濾器名稱用作`springSecurityFilterChain`可以幫助您使用元素配置基本基礎結構。 讓我們先看看它是如何配置的? 我已經為這個演示編寫了一個基本配置: `application-security.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.3.xsd"> <http auto-config="true" use-expressions="true"> <intercept-url pattern="/login" access="permitAll" /> <intercept-url pattern="/logout" access="permitAll" /> <intercept-url pattern="/accessdenied" access="permitAll" /> <intercept-url pattern="/**" access="hasRole('ROLE_USER')" /> <form-login login-page="/login" default-target-url="/list" authentication-failure-url="/accessdenied" /> <logout logout-success-url="/logout" /> </http> <authentication-manager alias="authenticationManager"> <authentication-provider> <user-service> <user name="lokesh" password="password" authorities="ROLE_USER" /> </user-service> </authentication-provider> </authentication-manager> </beans:beans> ``` 讓我們看看這個配置的實際含義。 * `http`:包括與配置相關的網址級別安全性。 此元素是所有與 Web 相關的名稱空間功能的父級。 * `auto-config`:包括一些基本服務。 它是 ```java <http> <form-login /> <http-basic /> <logout /> </http> ``` 的簡寫 * `use-expressions`:這里使用表達式來保護單個 URL。 這些表達式可以是例如 `hasRole([role])`,`hasAnyRole([role1,role2])`,`permitAll`,`denyAll`等。 * `intercept-url`:這將匹配請求中請求的網址格式,并根據訪問值決定要采取的操作。 * `form-login`: 當用戶嘗試訪問任何安全的 URL 時,這將成為圖片。 映射到`login-page`屬性的登錄頁面將用于身份驗證檢查。 它是 spring security `login-processing-url`。 如果未提供,spring 將為用戶提供內置的登錄頁面。 如果登錄成功或由于無效的用戶/密碼匹配而導致登錄失敗,它也包含默認目標的屬性。 * `logout`:如果在應用程序中調用注銷,這將有助于查找下一個視圖。 我正在使用基于 XML 的用戶服務,即我不會去數據庫進行密碼驗證,而是將用戶名/密碼組合存儲在配置文件本身中。 要使用此設置王,請使用內置的內置用戶詳細信息服務來設置`authentication-manager`。 在更實時的應用程序中,這將是一些從遠程數據庫中獲取數據的用戶服務。 ## 5\. Spring 控制器 我將重用控制器,并將在控制器中添加其他映射和處理器方法。 這些其他 URL 是`/login`,`/logout`和`/accessdenied`。 具有所有方法處理器的更新后的控制器如下所示: `EditEmployeeController.java` ```java package com.howtodoinjava.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.howtodoinjava.entity.EmployeeEntity; import com.howtodoinjava.service.EmployeeManager; @Controller public class EditEmployeeController { @Autowired private EmployeeManager employeeManager; public void setEmployeeManager(EmployeeManager employeeManager) { this.employeeManager = employeeManager; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String login(ModelMap model) { return "login"; } @RequestMapping(value = "/accessdenied", method = RequestMethod.GET) public String loginerror(ModelMap model) { model.addAttribute("error", "true"); return "denied"; } @RequestMapping(value = "/logout", method = RequestMethod.GET) public String logout(ModelMap model) { return "logout"; } @RequestMapping(value = "/", method = RequestMethod.GET) public String defaultPage(ModelMap map) { return "redirect:/list"; } @RequestMapping(value = "/list", method = RequestMethod.GET) public String listEmployees(ModelMap map) { map.addAttribute("employee", new EmployeeEntity()); map.addAttribute("employeeList", employeeManager.getAllEmployees()); return "editEmployeeList"; } @RequestMapping(value = "/add", method = RequestMethod.POST) public String addEmployee( @ModelAttribute(value = "employee") EmployeeEntity employee, BindingResult result) { employeeManager.addEmployee(employee); return "redirect:/list"; } @RequestMapping("/delete/{employeeId}") public String deleteEmplyee(@PathVariable("employeeId") Integer employeeId) { employeeManager.deleteEmployee(employeeId); return "redirect:/list"; } } ``` ## 6\. Spring 的視圖 現在,我們已經使用安全配置和控制器處理器配置了我們的應用程序。 是時候編寫本質上是 JSP 文件的視圖了。 jsp 文件中最重要的附加內容是`login.jsp`文件。 該文件的格式包含用戶名和密碼字段的文本框。 讓我們看看它是怎么寫的: #### 6.1. `login.jsp` `login.jsp` ```java <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %> <html> <body> <h1 id="banner">Login to Security Demo</h1> <form name="f" action="<c:url value='j_spring_security_check'/>" method="POST"> <table> <tr> <td>Username:</td> <td><input type='text' name='j_username' /></td> </tr> <tr> <td>Password:</td> <td><input type='password' name='j_password'></td> </tr> <tr> <td colspan="2">&nbsp;</td> </tr> <tr> <td colspan='2'><input name="submit" type="submit">&nbsp;<input name="reset" type="reset"></td> </tr> </table> </form> </body> </html> ``` 默認情況下,spring 會自動生成并配置一個[`UsernamePasswordAuthenticationFilter`](http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.html) bean。 默認情況下,此過濾器在處理 Web 表單中的登錄 POST 時響應 URL `/j_spring_security_check`。 用戶名字段使用“ `j_username`”,密碼字段使用“ `j_password`”。 提交此表單時,`UsernamePasswordAuthenticationFilter`將匹配`application-security.xml`中身份驗證提供程序設置中配置的用戶名和密碼。 #### 6.2. `logout.jsp` `logout.jsp` ```java < % session.invalidate(); %> You are now logged out!! <a href="//howtodoinjava.com/spring/spring-security/login-form-based-spring-3-security-example/">go back</a> ``` 該視圖僅使會話無效,并提供一個鏈接以返回登錄頁面。 #### 6.3. `denied.jsp` 當用戶嘗試使用無效的用戶名和密碼組合進行身份驗證時,此 jsp 文件將出現在用戶屏幕中。 它將在類路徑中顯示`message.properties`中配置的相應消息。 `denied.jsp` ```java <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <body> <h1 id="banner">Unauthorized Access !!</h1> <hr /> <c:if test="${not empty error}"> <div style="color:red"> Your fake login attempt was bursted, dare again !!<br /> Caused : ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message} </div> </c:if> <p class="message">Access denied!</p> <a href="//howtodoinjava.com/spring/spring-security/login-form-based-spring-3-security-example/">Go back to login page</a> </body> </html> ``` ## 7\. Spring Security 登錄表單演示 是時候測試應用程序了。 只需將應用程序部署在任何服務器中,例如就我而言,我正在使用 Tomcat 7.0. 現在,執行以下步驟: **7.1. 在瀏覽器`http://localhost:8080/Spring3HibernateIntegration`中輸入 URL** 除了`/login`,`/logout`和`/accessdeni`之外,它將顯示登錄屏幕,所有其他 URL 都是受保護的 URL。 ![default-login-screen-spring-security](https://img.kancloud.cn/6b/53/6b53a0136248ab1e8dc5705c6555b17c_342x181.jpg) 默認登錄界面 **7.2. 嘗試使用用戶名`"demo"`和密碼`"1234"`進行身份驗證** ![unauthorized-access-spring-security](https://img.kancloud.cn/9b/9d/9b9d5cd576f9709367bc76dbd971e080_383x207.jpg) 無效的用戶名和密碼的未經授權訪問 由于用戶名和密碼無效,它將給出拒絕訪問錯誤。 **7.3. 嘗試使用用戶名`"lokesh"`和密碼`"password"`進行身份驗證** ![employee-management-screen](https://img.kancloud.cn/06/e9/06e9babbc586b97be3f515200825fad0_346x361.jpg) 成功驗證后的員工編輯界面 因為用戶名和密碼正確,它將顯示員工管理屏幕。 **7.4. 單擊注銷鏈接** ![logout-spring-security](https://img.kancloud.cn/cd/e7/cde7a4c589be5484797b7b5c09933a91_227x62.jpg) 注銷消息 用戶將被注銷,并出現登錄屏幕。 我希望這個 **spring mvc 登錄示例**能夠對使用 xml 配置的基本 Spring Security 機制有所啟發。 如果您對此 **Spring Security 登錄表單示例**有任何疑問,請給我評論。 [**下載源碼**](https://docs.google.com/file/d/0B7yo2HclmjI4NkU5T3NiQzdzc2s/edit?usp=sharing) 學習愉快!
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看