Spring Security第1部分–具有數據庫的簡單登錄應用程序

什么是Spring Security?

Spring Security是一個提供安全解決方案的框架,可在Web請求級別和方法級別上處理身份驗證和授權。 Spring安全性通過兩種方式處理安全性。 一種是安全的Web請求,另一種是在URL級別限制訪問。 Spring Security使用Servlet過濾器。

在這篇文章中,我將創建一個處理登錄身份驗證和授權的簡單Web應用程序。

下載項目: http : //www.mediafire.com/?bb9x88uxvkb0uuv或http://dl.dropbox.com/u/7215751/JavaCodeGeeks/SpringSecurityTutorialPart1/spring-security-login-example.rar

在創建項目之前,需要對mysql執行一些查詢以創建一個新的數據庫,表并添加一些示例數據。

創建表

CREATE DATABASE IF NOT EXISTS `spring-test`;  -- create user  CREATE USER 'user'@'localhost' IDENTIFIED BY 'test';  GRANT ALL ON spring-test.* TO 'user'@'localhost';  USE `spring-test`;  CREATE TABLE USER_DETAILS (  USERNAME VARCHAR(10) NOT NULL,  PASSWORD VARCHAR(32) NOT NULL,  PRIMARY KEY (USERNAME)  );  CREATE TABLE USER_AUTH (  USERNAME VARCHAR(10) NOT NULL,  AUTHORITY VARCHAR(10) NOT NULL,  FOREIGN KEY (USERNAME) REFERENCES USER_DETAILS(USERNAME)  );

測試數據

insert into USER_DETAILS values ('user','123');  insert into USER_DETAILS values ('admin','admin');  insert into USER_AUTH values ('user', 'ROLE_USER');  insert into USER_AUTH values ('admin', 'ROLE_ADMIN');

之后,我使用maven創建一個Web項目,并將以下依賴項添加到pom.xml中

<properties><spring.version>3.0.5.RELEASE</spring.version>
</properties>
<dependencies>  <dependency>  <groupId>javax.validation</groupId>  <artifactId>validation-api</artifactId>  <version>1.0.0.GA</version>  </dependency>  <dependency>  <groupId>org.springframework</groupId>  <artifactId>spring-core</artifactId>  <version>${spring.version}</version>  </dependency>  <dependency>  <groupId>org.springframework</groupId>  <artifactId>spring-web</artifactId>  <version>${spring.version}</version>  </dependency>  <dependency>  <groupId>org.springframework</groupId>  <artifactId>spring-webmvc</artifactId>  <version>${spring.version}</version>  </dependency>  <dependency>  <groupId>org.springframework</groupId>  <artifactId>spring-jdbc</artifactId>  <version>${spring.version}</version>  </dependency>  <!-- Spring Security -->  <dependency>  <groupId>org.springframework.security</groupId>  <artifactId>spring-security-core</artifactId>  <version>${spring.version}</version>  </dependency>  <dependency>  <groupId>org.springframework.security</groupId>  <artifactId>spring-security-web</artifactId>  <version>${spring.version}</version>  </dependency>  <dependency>  <groupId>org.springframework.security</groupId>  <artifactId>spring-security-config</artifactId>  <version>${spring.version}</version>  </dependency>  <dependency>  <groupId>org.springframework.security</groupId>  <artifactId>spring-security-taglibs</artifactId>  <version>${spring.version}</version>  </dependency>  <dependency>  <groupId>org.springframework.security</groupId>  <artifactId>spring-security-acl</artifactId>  <version>${spring.version}</version>  </dependency>  <!-- jstl -->  <dependency>  <groupId>javax.servlet</groupId>  <artifactId>jstl</artifactId>  <version>1.2</version>  </dependency>  <!-- MySQL database driver -->  <dependency>  <groupId>mysql</groupId>  <artifactId>mysql-connector-java</artifactId>  <version>5.1.9</version>  </dependency>  <dependency>  <groupId>c3p0</groupId>  <artifactId>c3p0</artifactId>  <version>0.9.1</version>  </dependency>  </dependencies>

之后,像這樣更改web.xml

<!DOCTYPE web-app PUBLIC  '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN'  'http://java.sun.com/dtd/web-app_2_3.dtd' >  <web-app>  <display-name>spring-security-login</display-name>  <servlet>  <servlet-name>login</servlet-name>  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  <load-on-startup>1</load-on-startup>  </servlet>  <servlet-mapping>  <servlet-name>login</servlet-name>  <url-pattern>/</url-pattern>  </servlet-mapping>  <listener>  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <context-param>  <param-name>contextConfigLocation</param-name>  <param-value>  /WEB-INF/login-servlet.xml,  /WEB-INF/login-security.xml,  /WEB-INF/login-service.xml  </param-value>  </context-param>  <!-- Spring Security -->  <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>  <welcome-file-list>  <welcome-file>login.jsp</welcome-file>  </welcome-file-list>  </web-app>

現在,我需要創建login-servlet.xml,login-security.xml和login-service.xml彈簧配置文件。 在此示例中,我們將c3p0連接池與Mysql數據庫一起使用。

這是login-servlet.xml文件

<?xml version='1.0' encoding='UTF-8'?>  <beans xmlns='http://www.springframework.org/schema/beans'  xmlns:context='http://www.springframework.org/schema/context'  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/context  http://www.springframework.org/schema/context/spring-context-3.0.xsd'>  <context:component-scan base-package='rd.controller'/>  <bean id='internalResourceResolver'  class='org.springframework.web.servlet.view.InternalResourceViewResolver'>  <property name='prefix' value='/WEB-INF/views/'/>  <property name='suffix' value='.jsp'/>  </bean>  <bean class='org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping'></bean>  <bean class='org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter'/>  <bean id='placeholderConfig'  class='org.springframework.beans.factory.config.PropertyPlaceholderConfigurer'>  <property name='locations'>  <list>  <value>classpath:login.properties</value>  </list>  </property>  </bean>  </beans>

這是login-security.xml

<?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.xsd'>  <beans:import resource='login-service.xml'/>  <http>  <intercept-url pattern='/home*' access='ROLE_USER,ROLE_ADMIN' />  <intercept-url pattern='/admin*' access='ROLE_ADMIN' />  <form-login login-page='/login.jsp' default-target-url='/home' authentication-failure-url='/login.jsp?error=true'/>  <logout logout-success-url='/login.jsp' />  <anonymous username='guest' granted-authority='ROLE_GUEST'/>  <remember-me/>  </http>  <authentication-manager>  <authentication-provider>  <!--<user-service>-->  <!--<user name='admin' password='secret' authorities='ROLE_ADMIN,ROLE_USER' />-->  <!--<user name='user1' password='1111' authorities='ROLE_USER' />-->  <!--</user-service>-->  <jdbc-user-service data-source-ref='dataSource'  users-by-username-query='select username,password, 'true' as enabled from USER_DETAILS where username=?'  authorities-by-username-query='select USER_DETAILS.username , USER_AUTH.AUTHORITY as authorities from USER_DETAILS,USER_AUTH  where USER_DETAILS.username = ? AND USER_DETAILS.username=USER_AUTH.USERNAME '/>  </authentication-provider>  </authentication-manager>  </beans:beans>

這是login-service.xml

<beans xmlns='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'>  <bean id='dataSource' class='com.mchange.v2.c3p0.ComboPooledDataSource'>  <!--Driver name to connect to the database-->  <property name='driverClass'>  <value>${login.jdbc.driver}</value>  </property>  <!--DB URL-->  <property name='jdbcUrl'>  <value>${login.url}</value>  </property>  <!--DB User used to connect to the schema-->  <property name='user'>  <value>${login.username}</value>  </property>  <!--Password required to access for the above user-->  <property name='password'>  <value>${login.password}</value>  </property>  <!-- configuration pool via c3p0-->  <property name='acquireIncrement'>  <value>${login.c3p0.acquireIncrement}</value>  </property>  <property name='idleConnectionTestPeriod'>  <value>${login.c3p0.idleConnectionTestPeriod}</value>  <!-- seconds -->  </property>  <property name='maxPoolSize'>  <value>${login.c3p0.maxPoolSize}</value>  </property>  <property name='maxStatements'>  <value>${login.c3p0.maxStatements}</value>  </property>  <property name='minPoolSize'>  <value>${login.c3p0.minPoolSize}</value>  </property>  <property name='initialPoolSize'>  <value>${login.c3p0.initialPoolSize}</value>  </property>  <property name='maxIdleTime'>  <value>${login.c3p0.maxIdleTime}</value>  </property>  <property name='acquireRetryAttempts'>  <value>${login.c3p0.acquireRetryAttempts}</value>  </property>  <property name='acquireRetryDelay'>  <value>${login.c3p0.acquireRetryDelay}</value>  </property>  <property name='breakAfterAcquireFailure'>  <value>${login.c3p0.breakAfterAcquireFailure}</value>  </property>  </bean>  </beans>

login.jsp頁面如下所示。 (需要放置在webapp目錄下。但不在WEB_INF目錄下)

<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>  <html>  <head>  <title>Login</title>  </head>  <body>  <c:if test='${not empty param.error}'>  <font color='red'>  Login error. <br />  Reason : ${sessionScope['SPRING_SECURITY_LAST_EXCEPTION'].message}  </font>  </c:if>  <form method='POST' action='<c:url value='/j_spring_security_check' />'>  <table>  <tr>  <td align='right'>Username</td>  <td><input type='text' name='j_username' /></td>  </tr>  <tr>  <td align='right'>Password</td>  <td><input type='password' name='j_password' /></td>  </tr>  <tr>  <td colspan='2' align='right'>  <input type='submit' value='Login' />  </td>  </tr>  </table>  </form>  </body>  </html>

home.jsp頁面

<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>  <%@ taglib prefix='sec' uri='http://www.springframework.org/security/tags' %>  <html>  <head>  <title>Home</title>  </head>  <body>  <a href=<c:url value='/j_spring_security_logout'/>>Logout</a><br/>  <sec:authorize ifAnyGranted='ROLE_ADMIN'>  <h1>Only admin can see this</h1><br/>  <a href='admin'> Admin Home </a>  </sec:authorize>  <h1>Welcome</h1>  </body>  </html>

admin-home.jsp頁面

<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>  <%@ page contentType='text/html;charset=UTF-8' language='java' %>  <html>  <head>  <title>Admin</title>  </head>  <body>  <a href=<c:url value='/j_spring_security_logout'/>>Logout</a><br/>  <h1>Only Admin allowed here</h1>  </body>  </html>

之后,您需要編寫兩個控制器來檢索主頁和admin-home頁面。 這是HomeController.java

package rd.controller;  import org.springframework.stereotype.Controller;  import org.springframework.ui.Model;  import org.springframework.web.bind.annotation.RequestMapping;  import org.springframework.web.bind.annotation.RequestMethod;  @Controller  public class HomeController {  @RequestMapping(value = '/home' , method = RequestMethod.GET)  public String setUp(Model model){  return 'home';  }  }

這是AdminController.java

package rd.controller;  import org.springframework.stereotype.Controller;  import org.springframework.ui.Model;  import org.springframework.web.bind.annotation.RequestMapping;  import org.springframework.web.bind.annotation.RequestMethod;  @Controller  public class AdminController {  @RequestMapping(value = '/admin' , method = RequestMethod.GET)  public String setUp(Model model){  return 'admin-home';  }  }

而已。 運行mvn clean install命令創建war文件。 將war文件復制到tomcat / webapps目錄下,然后在您喜歡的瀏覽器中訪問該Web應用程序。
網址:本地主機:<端口> /spring-login/login.jsp

測試案例1:嘗試使用用戶名123和密碼登錄。 您將獲得用戶主頁。
測試案例2:嘗試使用admin作為用戶名admin作為密碼登錄。 您將獲得帶有可見管理頁面鏈接的用戶主頁。

在Spring安全性第2部分中,我將修改此項目并添加“記住我”功能和md5密碼加密功能。

在不久的將來,Ill會嘗試發布有關CAS集成和LDAP集成的Spring安全性的有趣文章。 敬請關注 :)

參考: Spring Security第1部分–與我們的JCG合作伙伴 Rajith Delantha在帶有Rajith…博客的Looping博客中的數據庫簡單登錄應用程序 。


翻譯自: https://www.javacodegeeks.com/2012/07/spring-security-part-1-simple-login.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/371947.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/371947.shtml
英文地址,請注明出處:http://en.pswp.cn/news/371947.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

計算機應用 winxp,2017年職稱計算機考試模塊WindowsXP試題

2017年職稱計算機考試模塊WindowsXP試題全國專業技術人員計算機應用能力考試是專業技術人員資格考試的一種。接下來應屆畢業生小編為大家搜索整理了2017年職稱計算機考試模塊WindowsXP試題&#xff0c;希望大家有所幫助。1. Windows XP中刪除某個文件的快捷方式【 A 】。A. 對原…

Python基礎(8)_迭代器、生成器、列表解析

一、迭代器 1、什么是迭代 1 重復   2 下次重復一定是基于上一次的結果而來 1 l[1,2,3,4] 2 count0 3 while count < len(l): 4 print(l[count]) 5 count1 迭代舉例2、可迭代對象 可進行.__iter__()操作的為可迭代對象 #print(isinstance(str1,Iterable)),判斷str…

Angularjs2-EXCEPTION: Response with status: 200 Ok for URL:

利用jsonp跨域請求數居&#xff0c;報錯 core.umd.js:3070 EXCEPTION: Response with status: 200 Ok for URL: 參考&#xff1a;stackoverflow 未解決。。。腦仁疼。。。有小伙伴也碰到過這個問題么&#xff1f; 16/11/30 問題解決 1.服務器端API允許跨域訪問(返回的數據添加允…

圖片無法刪除要計算機管理員,存在桌面的圖片刪不掉,怎么處理?提示是需要管理員權限。...

將下面代碼復制到記事本里&#xff0c;重命名為1.bat&#xff0c;然后打開&#xff0c;這時你右鍵圖片會出現管理員取得所有權&#xff0c;然后取得所有權后再刪除試試Windows Registry Editor Version 5.00[HKEY_CLASSES_ROOT\*\shell\runas]管理員取得所有權NoWorkingDirecto…

Java對象序列化的本機C / C ++類似性能

您是否曾經希望過像使用C 這樣的本地語言將Java對象轉換成字節流一樣快的速度&#xff1f; 如果您使用標準的Java序列化&#xff0c;您可能會對性能感到失望。 Java序列化的目的是與盡可能快而緊湊地序列化對象的目的截然不同。 為什么我們需要快速緊湊的序列化&#xff1f; 我…

WebStrom Sass 編譯配置 windows

第一步&#xff1a; 先安裝Ruby下載 一路next 安裝完成后打開開始菜單 打開后輸入 gem install sass sass -v 出現版本號說明成功 第二部配置webstorm 在webstorm中settings中搜索file watchers工具&#xff0c;在此工具中添加一個scss的watcher 確定&#xff0c;打開一個scss…

非本地跳轉之setjmp與longjmp

非本地跳轉(unlocal jump)是與本地跳轉相對應的一個概念。 本地跳轉主要指的是類似于goto語句的一系列應用&#xff0c;當設置了標志之后&#xff0c;可以跳到所在函數內部的標號上。然而&#xff0c;本地跳轉不能將控制權轉移到所在程序的任意地點&#xff0c;不能跨越函數&am…

清華計算機自主招生試題,2017年清華大學自主招生筆試題

2017年清華大學自主招生筆試題2017高考結束后&#xff0c;全國各大高校自主招生面試開始了&#xff0c;以下是百分網小編搜索整理的關于2017年清華大學自主招生筆試題&#xff0c;供各位參考&#xff0c;希望對大家有所幫助!想了解更多相關信息請持續關注我們應屆畢業生考試網!…

擴展劑:模式還是反模式?

擴展器模式在最近幾年變得很流行&#xff0c;甚至已經在OSGi標準&#xff08;例如&#xff0c;藍圖服務和Web應用程序規范&#xff09;中使用。 在處女座&#xff0c;我們從一開始就與擴展程序一起工作&#xff0c;但是盡管它們具有優勢&#xff0c;但它們仍有一些明顯的缺點。…

python html格式編碼

web應用如用到ace等網絡編輯器的時候&#xff0c;如要支持html,xml等格式的文件編輯&#xff0c;輸入ace 的文本內容必須先進行html格式編碼&#xff1a; def html_escape(content): import cgi return cgi.escape(content)轉載于:https://www.cnblogs.com/zhouxiaoming/p/703…

字符串替換

題目: 給定一個英文的字符串, 要求你將其中的元音刪除掉, 返回新的字符串. 例如:"This website is for losers LOL!" --> "Ths wbst s fr lsrs LL!" 當看到這個題目的時候, 第一個想起的就是re模塊的正則表達式. 不過由于最近使用過字符串的replace方…

小學計算機技術指導綱要,《中小學信息技術課程指導綱要(試行)》

《中小學信息技術課程指導綱要(試行)》2000年11月教育部頒發的《中小學信息技術課程指導綱要(試行)》教學目標&#xff1a;1、 增強信息意識&#xff0c;了解信息技術的發展變化及其對工作和社會的影響。2、 初步了解計算機基本工作原理&#xff0c;學會使用與學習和實際生活直…

JavaFX 2.0布局窗格– FlowPane和TilePane

FlowPanes和TilePanes是不錯的布局窗格&#xff0c;如果您想一個接一個地連續地水平或垂直地布局子級&#xff0c;則可以。 它們彼此非常相似&#xff0c;因為它們都將子級布置成列&#xff08;在水平Flow / TilePane的情況下&#xff09;并按其寬度或行&#xff08;在垂直Flow…

EasyRMS錄播管理服務器項目實戰:windows上開機自啟動NodeJS服務

本文轉自EasyDarwin開源團隊成員Penggy的博客&#xff1a;http://www.jianshu.com/p/ef840505ae06 近期在EasyDarwin開源團隊開發一款基于EasyDarwin在錄播服務器EasyRMS過程中,我采用node作為EasyRMS錄播服務器錄播管理服務器的開發平臺,基于node開發關于設備管理,錄像計劃,錄…

windows10搭建django1.10.3+Apache2.4

很多教程都是在linux上搭建&#xff0c;windows上似乎天生不太適合&#xff0c;但是我還是愿意試試這個坑。 首先 交代一下自己的環境 python3.5.2 64位 django 1.10.3 apache 2.4 64位 windows 10 重點在apache上。 python 和django 相信有興趣看這篇文章的基本上也都已經了解…

深入理解計算機系統 視頻教程,深入理解計算機系統1

第一章 計算機系統漫游代碼段的生命周期hello.c#include int main(){printf("hello world!\n");return 0;}1.1 前序源程序(源文件)實際上就是一個由0和1組成的位(又成比特bit)序列,8個位被組組成一組,稱為字節。每個字節表示程序中的某些文本字符(大部分的現代計算機…

Java與iOS對話:Java對象與Apple plist序列化

我很高興地宣布我的第一個開源項目java-plist-serializer可以幫助您將Java&#xff08;尤其是基于Spring的應用程序&#xff09;與iOS應用程序集成。 背景 我正在將Java Webapp作為后端并且客戶端是iOS設備的項目。 最近&#xff0c;我收到了創建Web服務的任務&#xff0c;該服…

web.cofing(新手必看)

花了點時間整理了一下ASP.NET Web.config配置文件的基本使用方法。很適合新手參看&#xff0c;由于Web.config在使用很靈活&#xff0c;可以自定義一些節點。所以這里只介紹一些比較常用的節點。 <?xml version"1.0"?> <!--注意: 除了手動編輯此文件以外&…

MIPS下CPU和RAM的數據流動情況詳解

這是計算機硬件間的數據路徑&#xff08;即數據流動的路徑&#xff09;&#xff0c;下面將較詳細分析此圖&#xff1a; PC&#xff08;program counter&#xff0c; 程序計數器&#xff09;是一個用于記錄當前計算機正在執行的指令的地址的寄存器&#xff08;register&#xff…

計算機亂程序怎么辦,我的電腦程序亂了怎么辦

我的電腦程序亂了&#xff0c;想用光盤恢復一下系統的修復安裝方法第一種方法&#xff1a;1、點擊“開始”菜單&#xff0c;點擊“運行”2、輸入CMD回車3、輸入命令SFC/SCANNOW4、插入系統光盤系統會自動將硬盤中的系統文件于系統盤中的文件比較并進行修復如果不行&#xff0c;…