基于注释的Spring Security实战指南

简介: 《基于注释的Spring Security实战指南》 版权声明:本文属于原创,版权归作者chszs所有,使用源码无任何限制,但转载文章需经作者同意。 一、准备工作 预准备的工具及软件有: 1.

《基于注释的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.jarcommons-logging-1.1.1.jarcglib-nodep-2.2.jar

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


说明:

1. Eclipse IDEJDK 7的版本可以更高一些,不影响开发和调试。

2. Eclipse一定要下载JEE版。

3. EclipseJDKTomcat的安装过程省略。

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类,内容如下:

[java]   view plain copy print ?
  1. package com.ch.configuration;  
  2.   
  3. import org.springframework.context.annotation.Bean;  
  4. import org.springframework.context.annotation.ComponentScan;  
  5. import org.springframework.context.annotation.Configuration;  
  6. import org.springframework.context.annotation.ImportResource;  
  7. import org.springframework.web.servlet.ViewResolver;  
  8. import org.springframework.web.servlet.config.annotation.EnableWebMvc;  
  9. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;  
  10. import org.springframework.web.servlet.view.InternalResourceViewResolver;  
  11.   
  12. @EnableWebMvc  
  13. @Configuration  
  14. @ComponentScan(basePackages = "com.jverstry")  
  15. @ImportResource("/WEB-INF/MyServlet-security.xml")  
  16. public class WebConfig extends WebMvcConfigurerAdapter {  
  17.   
  18.     @Bean  
  19.     public ViewResolver getViewResolver() {  
  20.         InternalResourceViewResolver resolver = new InternalResourceViewResolver();  
  21.         resolver.setPrefix("WEB-INF/pages/");  
  22.         resolver.setSuffix(".jsp");  
  23.   
  24.         return resolver;  
  25.     }  
  26.   
  27. }  

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


[java]   view plain copy print ?
  1. package com.ch.configuration.controller;  
  2.   
  3. import com.ch.configuration.service.MyService;  
  4.   
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.stereotype.Controller;  
  7. import org.springframework.ui.Model;  
  8. import org.springframework.web.bind.annotation.RequestMapping;  
  9.   
  10. @Controller  
  11. public class MyController {  
  12.   
  13.     private MyService myService;  
  14.   
  15.     @Autowired  
  16.     public void setMyService(MyService myService) {  
  17.         this.myService = myService;  
  18.     }  
  19.   
  20.     @RequestMapping(value = "/")  
  21.     public String home() {  
  22.         return "index";  
  23.     }  
  24.   
  25.     @RequestMapping(value = "/getTime")  
  26.     public String helloWorld(Model model) {  
  27.         model.addAttribute("TimeIs", myService.getCurrentTimeInMilliseconds());  
  28.         return "getTime";  
  29.     }  
  30.   
  31. }  


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

[java]   view plain copy print ?
  1. package com.ch.configuration.service;  
  2.   
  3. public interface MyService {  
  4.     long getCurrentTimeInMilliseconds();  
  5. }  

4. com.ch.configuration.service包新建MyServiceImpl.java类,内容如下:

[java]   view plain copy print ?
  1. package com.ch.configuration.service;  
  2.   
  3. public class MyServiceImpl implements MyService {  
  4.   
  5.     @Override  
  6.     public long getCurrentTimeInMilliseconds() {  
  7.         return System.currentTimeMillis();  
  8.     }  
  9.   
  10. }  

5. com.ch.configuration.service包新建MyServicesConfiguration.java类,内容如下:

[java]   view plain copy print ?
  1. package com.ch.configuration.service;  
  2.   
  3. import org.springframework.context.annotation.Bean;  
  4. import org.springframework.context.annotation.Configuration;  
  5.   
  6. @Configuration  
  7. public class MyServicesConfiguration {  
  8.   
  9.     private MyService myService = new MyServiceImpl();  
  10.   
  11.     @Bean  
  12.     public MyService getMyService() {  
  13.         return myService;  
  14.     }  
  15.   
  16. }  

五、前台页面层开发

1. WebContent\WEB-INF目录新建pages文件夹,接着在pages目录下新建getTime.jsp文件,内容如下:

[html]   view plain copy print ?
  1. %@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. %@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  4. nbsp;html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  5. html>  
  6. head>  
  7. meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  8. title>Get Time !!!title>  
  9. head>  
  10. body>  
  11.     The time in milliseconds is:  
  12.     c:out value="${TimeIs}" />  
  13.     !  
  14. body>  
  15. html>  

2. pages目录下新建index.jsp文件,内容如下:

[html]   view plain copy print ?
  1. %@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. nbsp;html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. html>  
  5. head>  
  6. meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. title>Welcome !!!title>  
  8. head>  
  9. body>  
  10.     h1>Welcome To Spring MVC With Annotations !!!h1>  
  11.     h1>(with login...)h1>  
  12. body>  
  13. html>  

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

[html]   view plain copy print ?
  1. xml version="1.0" encoding="UTF-8"?>  
  2. web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
  5.     id="WebApp_ID" version="3.0">  
  6.     display-name>SpringSecurityDemodisplay-name>  
  7.     context-param>  
  8.         param-name>contextClassparam-name>  
  9.         param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContextparam-value>  
  10.     context-param>  
  11.   
  12.     context-param>  
  13.         param-name>contextConfigLocationparam-name>  
  14.         param-value>com.ch.configurationparam-value>  
  15.     context-param>  
  16.   
  17.     filter>  
  18.         filter-name>springSecurityFilterChainfilter-name>  
  19.         filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>  
  20.     filter>  
  21.   
  22.     filter-mapping>  
  23.         filter-name>springSecurityFilterChainfilter-name>  
  24.         url-pattern>/*url-pattern>  
  25.     filter-mapping>  
  26.   
  27.     listener>  
  28.         listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>  
  29.     listener>  
  30.   
  31.     servlet>  
  32.         servlet-name>MyServletservlet-name>  
  33.         servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>  
  34.         init-param>  
  35.             param-name>contextConfigLocationparam-name>  
  36.             param-value>param-value>  
  37.         init-param>  
  38.         load-on-startup>1load-on-startup>  
  39.     servlet>  
  40.   
  41.     servlet-mapping>  
  42.         servlet-name>MyServletservlet-name>  
  43.         url-pattern>/url-pattern>  
  44.     servlet-mapping>  
  45.   
  46.     welcome-file-list>  
  47.         welcome-file>welcome-file>  
  48.     welcome-file-list>  
  49. web-app>  

4. WEB-INF下新建MyServlet-security.xml文件,内容如下:

[html]   view plain copy print ?
  1. beans:beans xmlns="http://www.springframework.org/schema/security"  
  2.     xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  4.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  5.     http://www.springframework.org/schema/security  
  6.     http://www.springframework.org/schema/security/spring-security-3.1.xsd">  
  7.   
  8.     http auto-config="true">  
  9.         intercept-url pattern="/*" access="ROLE_USER" />  
  10.     http>  
  11.   
  12.     authentication-manager alias="authenticationManager">  
  13.         authentication-provider>  
  14.             user-service>  
  15.                 user authorities="ROLE_USER" name="guest" password="guest" />  
  16.             user-service>  
  17.         authentication-provider>  
  18.     authentication-manager>  
  19.   
  20. beans:beans>  

至此,Demo项目的开发已经完成。项目的整体结构图如图所示:




六、部署和运行


1. Eclipse选择项目SpringSecurityDemo,右键选择“Run As”,再选择“Run on Server”,选择Apache Tomcat v7.0Eclipse IDE自动完成部署并运行。

在浏览器上输入地址:http://localhost:8080/SpringSecurityDemo/

显示如下:

注:地址自动被重定向到http://localhost:8080/SpringSecurityDemo/spring_security_login

User/Password输入guest/guest,显示:

如果输入错误,显示:

OK!本文就到这里,对于Spring的注释,可以参考官方文档加以理解。

目录
相关文章
|
JSON 安全 Java
什么是JWT?如何使用Spring Boot Security实现它?
什么是JWT?如何使用Spring Boot Security实现它?
2475 5
|
8月前
|
负载均衡 监控 Java
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
本文详细介绍了 Spring Cloud Gateway 的核心功能与实践配置。首先讲解了网关模块的创建流程,包括依赖引入(gateway、nacos 服务发现、负载均衡)、端口与服务发现配置,以及路由规则的设置(需注意路径前缀重复与优先级 order)。接着深入解析路由断言,涵盖 After、Before、Path 等 12 种内置断言的参数、作用及配置示例,并说明了自定义断言的实现方法。随后重点阐述过滤器机制,区分路由过滤器(如 AddRequestHeader、RewritePath、RequestRateLimiter 等)与全局过滤器的作用范围与配置方式,提
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
|
9月前
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
1354 3
|
7月前
|
监控 Cloud Native Java
Spring Boot 3.x 微服务架构实战指南
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Spring Boot 3.x与微服务架构,探索云原生、性能优化与高可用系统设计。以代码为笔,在二进制星河中谱写极客诗篇。关注我,共赴技术星辰大海!(238字)
1263 2
Spring Boot 3.x 微服务架构实战指南
|
人工智能 搜索推荐 Java
Spring AI与DeepSeek实战三:打造企业知识库
本文基于Spring AI与RAG技术结合,通过构建实时知识库增强大语言模型能力,实现企业级智能搜索场景与个性化推荐,攻克LLM知识滞后与生成幻觉两大核心痛点。
1498 7
|
7月前
|
XML Java 测试技术
《深入理解Spring》:IoC容器核心原理与实战
Spring IoC通过控制反转与依赖注入实现对象间的解耦,由容器统一管理Bean的生命周期与依赖关系。支持XML、注解和Java配置三种方式,结合作用域、条件化配置与循环依赖处理等机制,提升应用的可维护性与可测试性,是现代Java开发的核心基石。
|
12月前
|
人工智能 Java API
Spring AI 实战|Spring AI入门之DeepSeek调用
本文介绍了Spring AI框架如何帮助Java开发者轻松集成和使用大模型API。文章从Spring AI的初探开始,探讨了其核心能力及应用场景,包括手动与自动发起请求、流式响应实现打字机效果,以及兼容不同AI服务(如DeepSeek、通义千问)的方法。同时,还详细讲解了如何在生产环境中添加监控以优化性能和成本管理。通过Spring AI,开发者可以简化大模型调用流程,降低复杂度,为企业智能应用开发提供强大支持。最后,文章展望了Spring AI在未来AI时代的重要作用,鼓励开发者积极拥抱这一技术变革。
4181 71
Spring AI 实战|Spring AI入门之DeepSeek调用
|
安全 Java 数据库
Spring Security 实战指南:从入门到精通
本文详细介绍了Spring Security在Java Web项目中的应用,涵盖登录、权限控制与安全防护等功能。通过Filter Chain过滤器链实现请求拦截与认证授权,核心组件包括AuthenticationProvider和UserDetailsService,负责用户信息加载与密码验证。文章还解析了项目结构,如SecurityConfig配置类、User实体类及自定义登录逻辑,并探讨了Method-Level Security、CSRF防护、Remember-Me等进阶功能。最后总结了Spring Security的核心机制与常见配置,帮助开发者构建健壮的安全系统。
2165 0
|
9月前
|
人工智能 监控 安全
如何快速上手【Spring AOP】?核心应用实战(上篇)
哈喽大家好吖~欢迎来到Spring AOP系列教程的上篇 - 应用篇。在本篇,我们将专注于Spring AOP的实际应用,通过具体的代码示例和场景分析,帮助大家掌握AOP的使用方法和技巧。而在后续的下篇中,我们将深入探讨Spring AOP的实现原理和底层机制。 AOP(Aspect-Oriented Programming,面向切面编程)是Spring框架中的核心特性之一,它能够帮助我们解决横切关注点(如日志记录、性能统计、安全控制、事务管理等)的问题,提高代码的模块化程度和复用性。