天天看點

基于注釋的Spring Security實戰指南

版權聲明:本文為部落客chszs的原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/chszs/article/details/7997858

《基于注釋的Spring Security實戰指南》

版權聲明:本文屬于原創,版權歸作者chszs所有,使用源碼無任何限制,但轉載文章需經作者同意。

一、準備工作

預準備的工具及軟體有:

1. Eclipse IDE:我使用Eclipse JEE 3.7版,即eclipse-jee-indigo-SR2-win32-x86_64.zip

2. JDK 7:我使用JDK 7u4版,即jdk-7u4-windows-x64.exe

3. Spring Framework:我使用Spring Framework 3.1.2版,即spring-framework-3.1.2.RELEASE-with-docs.zip

4. Spring Security:我使用Spring Security 3.1.2版,即spring-security-3.1.2.RELEASE-dist

5. 其它JAR包:jstl-1.2.jar,commons-logging-1.1.1.jar,cglib-nodep-2.2.jar

6. Tomcat應用伺服器:我使用Tomcat 7.0.29版,即apache-tomcat-7.0.29-windows-x64.zip

說明:

1. Eclipse IDE和JDK 7的版本可以更高一些,不影響開發和調試。

2. Eclipse一定要下載下傳JEE版。

3. Eclipse、JDK和Tomcat的安裝過程省略。

4. 我的作業系統是64位版本,故開發環境對應的工具都是下載下傳64位的安裝包。

二、建立項目

在Eclipse環境下建立Dynamic Web Project。

項目名為:SpringSecurityDemo,

Target runtime選擇New Runtime,然後選擇Apache Tomcat v7.0,并設定好Tomcat的安裝目錄。

連續點選兩次Next,在“Generate web.xml deployment descriptor”處打勾選擇,并點選Finish。

三、添加庫檔案

把下列JAR檔案添加到項目的WebContent\WEB-INF\lib目錄下。

四、業務層開發

1. 在項目src處,建立com.ch.configuration包,并建立WebConfig.java類,内容如下:

package com.ch.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
@ImportResource("/WEB-INF/MyServlet-security.xml")
public class WebConfig extends WebMvcConfigurerAdapter {

	@Bean
	public ViewResolver getViewResolver() {
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix("WEB-INF/pages/");
		resolver.setSuffix(".jsp");

		return resolver;
	}

}           

2. 建立com.ch.configuration.controller包,并建立MyController.java類,内容如下:

package com.ch.configuration.controller;

import com.ch.configuration.service.MyService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {

	private MyService myService;

	@Autowired
	public void setMyService(MyService myService) {
		this.myService = myService;
	}

	@RequestMapping(value = "/")
	public String home() {
		return "index";
	}

	@RequestMapping(value = "/getTime")
	public String helloWorld(Model model) {
		model.addAttribute("TimeIs", myService.getCurrentTimeInMilliseconds());
		return "getTime";
	}

}           

3. 建立com.ch.configuration.service包,并建立MyService.java接口類,内容如下:

package com.ch.configuration.service;

public interface MyService {
	long getCurrentTimeInMilliseconds();
}           

4. 在com.ch.configuration.service包建立MyServiceImpl.java類,内容如下:

package com.ch.configuration.service;

public class MyServiceImpl implements MyService {

	@Override
	public long getCurrentTimeInMilliseconds() {
		return System.currentTimeMillis();
	}

}           

5. 在com.ch.configuration.service包建立MyServicesConfiguration.java類,内容如下:

package com.ch.configuration.service;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyServicesConfiguration {

	private MyService myService = new MyServiceImpl();

	@Bean
	public MyService getMyService() {
		return myService;
	}

}           

五、前台頁面層開發

1. 在WebContent\WEB-INF目錄建立pages檔案夾,接着在pages目錄下建立getTime.jsp檔案,内容如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Get Time !!!</title>
</head>
<body>
	The time in milliseconds is:
	<c:out value="${TimeIs}" />
	!
</body>
</html>           

2. 在pages目錄下建立index.jsp檔案,内容如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome !!!</title>
</head>
<body>
	<h1>Welcome To Spring MVC With Annotations !!!</h1>
	<h1>(with login...)</h1>
</body>
</html>           

3. 修改WEB-INF下的web.xml檔案,内容如下:

<?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_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>SpringSecurityDemo</display-name>
	<context-param>
		<param-name>contextClass</param-name>
		<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
	</context-param>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>com.ch.configuration</param-value>
	</context-param>

	<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>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<servlet>
		<servlet-name>MyServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value></param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>MyServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file></welcome-file>
	</welcome-file-list>
</web-app>           

4. 在WEB-INF下建立MyServlet-security.xml檔案,内容如下:

<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.1.xsd">

	<http auto-config="true">
		<intercept-url pattern="/*" access="ROLE_USER" />
	</http>

	<authentication-manager alias="authenticationManager">
		<authentication-provider>
			<user-service>
				<user authorities="ROLE_USER" name="guest" password="guest" />
			</user-service>
		</authentication-provider>
	</authentication-manager>

</beans:beans>           

至此,Demo項目的開發已經完成。項目的整體結構圖如圖所示:

六、部署和運作

1. 在Eclipse選擇項目SpringSecurityDemo,右鍵選擇“Run As”,再選擇“Run on Server”,選擇Apache Tomcat v7.0,Eclipse IDE自動完成部署并運作。

在浏覽器上輸入位址:

http://localhost:8080/SpringSecurityDemo/

顯示如下:

注:位址自動被重定向到

http://localhost:8080/SpringSecurityDemo/spring_security_login

User/Password輸入guest/guest,顯示:

如果輸入錯誤,顯示:

OK!本文就到這裡,對于Spring的注釋,可以參考官方文檔加以了解。

繼續閱讀