SpringSecurity整合ssm

news2024/11/14 15:17:02

SpringSecurity

1. SpringSecurity 框架简介

Spring 是非常流行和成功的 Java 应用开发框架,Spring Security 正是 Spring 家族中的成员。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方 案。

正如你可能知道的关于安全方面的两个主要区域是“认证”和“授权”(或者访问控 制),一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权 **(Authorization)**两个部分,这两点也是 Spring Security 重要核心功能。

(1)用户认证指的是:验证某个用户是否为系统中的合法主体,也就是说用户能否访问 该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认 证过程。通俗点说就是系统认为用户是否能登录

(2)用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户 所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以 进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的 权限。通俗点讲就是系统判断用户是否有权限去做某些事情。

2. SpringSecurity入门案例 (认证)

2.1. 创建maven工程(web工程)加入依赖

  <properties> 
    <maven.compiler.source>8</maven.compiler.source>  
    <maven.compiler.target>8</maven.compiler.target>  
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>5.0.4.RELEASE</spring.version>
    <spring.security.version>5.0.1.RELEASE</spring.security.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.6</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</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-context-support</artifactId>
      <version>5.1.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-web</artifactId>
      <version>${spring.security.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.annotation</groupId>
      <artifactId>jsr250-api</artifactId>
      <version>1.0</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-config</artifactId>
      <version>${spring.security.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

  </dependencies>
  <build>
    <plugins>
      <!-- java编译插件 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <configuration>
          <!-- 指定端口 -->
          <port>8080</port>
          <!-- 请求路径 -->
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
  </build>

2.2 创建页面

  1. 登录页面(login.jsp)

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
        <link rel="icon" href="图标路径;base64,aWNv">
    </head>
    <body>
        <h1>login.jsp</h1>
        <form action="/login" method="post">
            用户名:<input type="text" name="username" value=""><br>
            密码:<input type="password" name="password" value=""><br>
            <input type="submit" value="登录">
        </form>
    </body>
    </html>
    
    
  2. 登录失败页面(fail.jsp)

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <h1>登录失败</h1>
    </body>
    </html>
    
  3. 登录成功页面(index.jsp)

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
      <h1>登录成功</h1>
    </body>
    </html>
    

2.3 resource下创建spring-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       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.xsd
       http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security.xsd">
    
    <!-- 配置不过滤的资源(静态资源及登录相关) -->
    <security:http pattern="/login.jsp" security="none"/>
    <security:http pattern="/fail.jsp" security="none"/>
    <security:http pattern="/css/**" security="none"/>
    <security:http pattern="/img/**" security="none"/>
    <security:http pattern="/js/**" security="none"/>
    <!--
    http:用于定义相关权限控制
    auto-config:是否自动配置
        设置为true时框架会提供默认的一些配置,例如提供默认的登录页面、登出处理等
        设置为false时需要显示提供登录表单配置,否则会报错
	use-expressions:用于指定intercept-url中的access属性是否使用SPEL表达式-->
    <security:http auto-config="true" use-expressions="false">
		<!--intercept-url: 指定哪些资源不需要进行权限校验,可以使用通配符-->
        <!-- 配置资源连接,访问任何资源,都需要拥有ROLE_USER或者ROLE_ADMIN任意一个角色 -->
        <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>

        <!--登录:
        1. login-page 自定义登录页url,默认为/login
        2. login-processing-url form表单提交时指定的action
        3. default-target-url 默认登录成功后跳转的url
        4. authentication-failure-url 登录失败后跳转的url
        5. username-parameter 用户名的请求字段 默认为userName
        6. password-parameter 密码的请求字段 默认为password-->
        <security:form-login login-page="/login.jsp"
                             login-processing-url="/login" username-parameter="username"
                             password-parameter="password"
                             authentication-failure-url="/fail.jsp"
                             default-target-url="/index.jsp" />
        <!-- 登出:
         invalidate-session 是否删除session
         logout-url:登出处理链接
         logout-success-url:登出成功页面
         注:登出操作 只需要链接到 logout即可登出当前用户 -->
        <security:logout invalidate-session="true" logout-url="/logout"
                         logout-success-url="/login.jsp"/>
        <!-- 关闭CSRF,默认是开启的 跨域攻击-->
        <!--csrf:对应CsrfFilter过滤器
        disabled:是否启用CsrfFilter过滤器,如果使用自定义登录页面需要关闭此项,
        否则登录操作会被禁用(403)
        (自定义登录页面,,框架认为我们的页面不安全,
        需要关闭验证过滤器,默认登录页面有隐藏域,_scrf ,如果使用自定义登录页面,
        没有关闭验证过滤器,框架会拒绝访问.)
        -->
        <security:csrf disabled="true"/>
    </security:http>

    <!--authentication-manager:认证管理器,用于处理认证操作-->
    <security:authentication-manager>
        <!--authentication-provider:认证提供者,执行具体的认证逻辑-->
        <security:authentication-provider>
           <!-- user-service:用于获取用户信息,提供给authentication-provider进行认证-->
            <security:user-service>
                <!--自定义用户名密码-->
                <!--
                user:定义用户信息,可以指定用户名、密码、角色,后期可以改为从数据库查询用户信息
                {noop}:表示当前使用的密码为明文
                -->
                <!--{noop}:spring security默认是加密认证,添加此字段表示不加密认证。
				user用户拥有book:add权限和ROLE_USER角色-->
                <security:user name="user" password="{noop}user123"
                               authorities="book:add,ROLE_USER"/>
                <security:user name="admin" password="{noop}admin123"
                               authorities="ROLE_ADMIN"/>
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>

</beans>

2.4 web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <display-name>Archetype Created Web Application</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-security.xml</param-value>
    </context-param>
    <!--
		1. DelegatingFilterProxy用于整合第三方框架
           整合Spring Security时过滤器的名称必须为springSecurityFilterChain,
           否则会抛出NoSuchBeanDefinitionException异常
        2. DelegatingFilterProxy是Spring的Web模块中的一个类,
           它提供了让HTTP请求在到达实际目的地之前通过过滤器的功能。
    -->
    <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>
</web-app>

2.5 项目结构

1686239520695

2.6 启动tomcat

1686239611284

2.7 访问页面

1686239719480

登录成功后跳转到:http://localhost:8080/ 根路径中,展示的是index.jsp页面:

1686240127652

3. 权限管理

3.1 创建maven的web工程并加入依赖

<properties> 
    <maven.compiler.source>8</maven.compiler.source>  
    <maven.compiler.target>8</maven.compiler.target>  
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>5.0.4.RELEASE</spring.version>
    <spring.security.version>5.0.1.RELEASE</spring.security.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.6</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</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-context-support</artifactId>
      <version>5.1.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-web</artifactId>
      <version>${spring.security.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.annotation</groupId>
      <artifactId>jsr250-api</artifactId>
      <version>1.0</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-config</artifactId>
      <version>${spring.security.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

  </dependencies>
  <build>
    <plugins>
      <!-- java编译插件 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <configuration>
          <!-- 指定端口 -->
          <port>8080</port>
          <!-- 请求路径 -->
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

3.2 创建springmvc.xml文件

<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xmlns:p="http://www.springframework.org/schema/p"
	   xmlns:mvc="http://www.springframework.org/schema/mvc"
	   xmlns:aop="http://www.springframework.org/schema/aop"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
	<context:component-scan base-package="com.jz" use-default-filters="false">
		<context:include-filter type="annotation"
								expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
	<mvc:annotation-driven></mvc:annotation-driven>
	<mvc:default-servlet-handler></mvc:default-servlet-handler>
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	<!--
		支持AOP的注解支持,AOP底层使用代理技术
		JDK动态代理,要求必须有接口
		cglib代理,生成子类对象,proxy-target-class="true" 默认使用cglib的方式
	-->
	<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>

3.3 spring-security.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       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.xsd
       http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security.xsd">
    <!-- 配置不过滤的资源(静态资源及登录相关) -->
    <security:http pattern="/login.jsp" security="none"/>
    <security:http pattern="/fail.jsp" security="none"/>
    <security:http pattern="/css/**" security="none"/>
    <security:http pattern="/img/**" security="none"/>
    <security:http pattern="/js/**" security="none"/>
    <!--
    http:用于定义相关权限控制
    auto-config:是否自动配置
        设置为true时框架会提供默认的一些配置,例如提供默认的登录页面、登出处理等
        设置为false时需要显示提供登录表单配置,否则会报错
   use-expressions="false":禁用spEL表达式-->
    <security:http auto-config="true" use-expressions="false">

        <!-- 配置资源连接,访问任何资源,都需要拥有ROLE_USER或者ROLE_ADMIN任意一个角色 -->
        <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>

        <!--登录:
        1. login-page 自定义登录页url,默认为/login
        2. login-processing-url form表单提交时指定的action
        3. default-target-url 默认登录成功后跳转的url
        4. authentication-failure-url 登录失败后跳转的url
        5. username-parameter 用户名的请求字段 默认为userName
        6. password-parameter 密码的请求字段 默认为password-->
        <security:form-login login-page="/login.jsp"
                             login-processing-url="/login" username-parameter="username"
                             password-parameter="password" authentication-failure-url="/fail.jsp"
                             default-target-url="/index.jsp" />
        <!-- 登出:
         invalidate-session 是否删除session
         logout-url:登出处理链接
         logout-success-url:登出成功页面
         注:登出操作 只需要链接到 logout即可登出当前用户 -->
        <security:logout invalidate-session="true" logout-url="/logout"
                         logout-success-url="/login.jsp"/>
        <!-- 关闭CSRF,默认是开启的 跨域攻击-->
        <security:csrf disabled="true"/>
        <!-- 尝试访问没有权限的页面时跳转的页面 -->
        <security:access-denied-handler error-page="/error-noauth.jsp"/>
    </security:http>

    <!--SpringSecurity认证管理器-->
    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <!--自定义用户名密码-->
                <!--{noop}:spring security默认是加密认证,添加此字段表示不加密认证。-->
                <security:user name="user" password="{noop}user123"
                               authorities="book:add,ROLE_USER"/>
                <security:user name="admin" password="{noop}admin123"
                               authorities="ROLE_ADMIN"/>
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>

    <!--开启jsr250注解-->
    <security:global-method-security jsr250-annotations="enabled"
                                     pre-post-annotations="enabled"
                                     secured-annotations="enabled"/>
</beans>

3.4 创建以下页面

  1. index.jsp (登录成功主页)

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    <span style="color: blue;font-size: 20px">
      【当前登录用户[${sessionScope.SPRING_SECURITY_CONTEXT.authentication.principal.username}]】
    </span>
    <h1>主页--->登录成功</h1>
      <a href="/logout">退出</a><br/><hr>
      <a href="/book/list">书籍列表</a><br/><hr>
      <a href="/book/add">新增书籍</a><br/><hr>
      <a href="/book/update">书籍用户</a><br/><hr>
      <a href="/book/delete">删除书籍</a><br/><hr>
    </body>
    </html>
    
  2. login.jsp(登录页面)

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
        <link rel="icon" href="图标路径;base64,aWNv">
    </head>
    <body>
        <h1>login.jsp</h1>
        <form action="/login" method="post">
            用户名:<input type="text" name="username" value=""><br>
            密码:<input type="password" name="password" value=""><br>
            <input type="submit" value="登录">
        </form>
    </body>
    </html>
    
    
  3. main.jsp(书籍管理主页)

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <h1>书籍管理页面</h1>
        <h2>${msg}</h2>
    </body>
    </html>
    
    
  4. fail.jsp(登录失败页面)

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <h1 style="background: hotpink">登录失败</h1>
    </body>
    </html>
    
    
  5. error-noauth.jsp(没有权限跳转页面)

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <h1 style="color: red">您无权访问</h1>
    </body>
    </html>
    
    

3.5 创建BookController

package com.jz.controller;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("book")
public class BookController {
    @GetMapping("/list")
    //@PreAuthorize("hasAnyAuthority('book:list')")
    public String bookList(Model model) {
        System.out.println("访问书籍查询界面成功!");
        model.addAttribute("msg","访问书籍查询界面成功!");
        return "main";
    }
    @GetMapping("/add")
    //@PreAuthorize("hasAnyAuthority('book:add','book:insert')")
    public String bookAdd(Model model) {
        System.out.println("访问书籍新增界面成功!");
        model.addAttribute("msg","访问书籍新增界面成功!");
        return "main";
    }
    @GetMapping("/update")
    //必须有book:edit权限才能访问bookUpdate方法
    //@PreAuthorize("hasAnyAuthority('book:edit')")
    public String bookUpdate(Model model) {
        System.out.println("访问书籍修改界面成功!");
        model.addAttribute("msg","访问书籍修改界面成功!");
        return "main";
    }
    @GetMapping("/delete")
    //只要具有"ROLE_USER","ROLE_ADMIN"任意一种角色就可以访问。
    //@Secured({"ROLE_USER", "ROLE_ADMIN"})
    public String bookDelete(Model model) {
        System.out.println("访问书籍删除界面成功!");
        model.addAttribute("msg","访问书籍删除界面成功!");
        return "main";
    }
}

3.6 web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <display-name>Archetype Created Web Application</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-security.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

    <!--
        DelegatingFilterProxy是Spring的Web模块中的一个类,
        它提供了让HTTP请求在到达实际目的地之前通过过滤器的功能。
    -->
    <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>

    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>



    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

3.7 测试

登录:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0p78F2Pz-1687834244153)(image/1686296507798.png)]

主页:

1686296537121

权限测试:点击书籍列表由于user用户没有book:list权限所以访问失败:

1686296596685

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QIlWoTTs-1687834244154)(image/1686296621698.png)]

4. 数据库读取用户、权限、角色信息

由于用户名和密码都是设置的固定的,正常我们应该从数据库读取用户名密码信息;

由于权限角色也是设置的固定的,正常也应该从数据库中读取;下面说一下如何从数据库读取用户名、密码、角色、权限信息;

4.1 表结构

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IFwQY7dv-1687834244154)(image/1686493595955.png)]

4.2 创建表

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sARELHbb-1687834244155)(image/1686493657040.png)]

4.3 创建maven的web工程并加入依赖

  <properties> 
    <maven.compiler.source>8</maven.compiler.source>  
    <maven.compiler.target>8</maven.compiler.target>  
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
    <spring.version>5.0.4.RELEASE</spring.version>  
    <spring.security.version>5.0.1.RELEASE</spring.security.version> 
  </properties>  
  <dependencies>
    <!--mysql的驱动包-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>
    <!--mybatis核心-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>
    <!--spring整合mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.2</version>
    </dependency>
    <!--加入分页的依赖-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.10</version>
    </dependency>
    <!--导入C3P0连接池-->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>
    <!--junit-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!--日志包-->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.6</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</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>
    <!--Jackson依赖-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.9</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>5.1.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-web</artifactId>
      <version>${spring.security.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.annotation</groupId>
      <artifactId>jsr250-api</artifactId>
      <version>1.0</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-config</artifactId>
      <version>${spring.security.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency> 
  </dependencies>  
  <build> 
    <plugins> 
      <!-- java编译插件 -->  
      <plugin> 
        <groupId>org.apache.maven.plugins</groupId>  
        <artifactId>maven-compiler-plugin</artifactId>  
        <configuration> 
          <source>1.8</source>  
          <target>1.8</target>  
          <encoding>UTF-8</encoding> 
        </configuration> 
      </plugin>  
      <plugin> 
        <groupId>org.apache.tomcat.maven</groupId>  
        <artifactId>tomcat7-maven-plugin</artifactId>  
        <configuration> 
          <!-- 指定端口 -->  
          <port>8080</port>  
          <!-- 请求路径 -->  
          <path>/</path> 
        </configuration> 
      </plugin> 
    </plugins> 
  </build> 
</project>

4.3 创建实体类

user类:

package com.jz.pojo;
import java.io.Serializable;
public class User implements Serializable {

  private Integer id;
  private String email;
  private String username;
  private String password;
  private String phoneNum;
  private Integer status;//是否可用(1 可用  2不可用)


  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }


  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }


  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }


  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }


  public String getPhoneNum() {
    return phoneNum;
  }

  public void setPhoneNum(String phoneNum) {
    this.phoneNum = phoneNum;
  }


  public Integer getStatus() {
    return status;
  }

  public void setStatus(Integer status) {
    this.status = status;
  }

}

Permission类

package com.jz.pojo;


import java.io.Serializable;

public class Permission  implements Serializable {

  private Integer id;
  private String permissionName;
  private String url;


  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }


  public String getPermissionName() {
    return permissionName;
  }

  public void setPermissionName(String permissionName) {
    this.permissionName = permissionName;
  }


  public String getUrl() {
    return url;
  }

  public void setUrl(String url) {
    this.url = url;
  }

}

Role类:

package com.jz.pojo;


import java.io.Serializable;

public class Role  implements Serializable {

  private Integer id;
  private String roleName;
  private String roleDesc;


  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }


  public String getRoleName() {
    return roleName;
  }

  public void setRoleName(String roleName) {
    this.roleName = roleName;
  }


  public String getRoleDesc() {
    return roleDesc;
  }

  public void setRoleDesc(String roleDesc) {
    this.roleDesc = roleDesc;
  }

}

4.4 mapper接口

UserMapper

package com.jz.mapper;

import com.jz.pojo.User;

public interface UserMapper {
    //登录的方法
    public User getUserByUsernamePassword(String username);
}

RoleMapper

package com.jz.mapper;

import com.jz.pojo.Role;

import java.util.List;

public interface RoleMapper {
    /**
     * 根据用户ID查询角色信息
     * @param userId
     * @return
     */
    List<Role> selectRolesByUserId(Integer userId);

}

PermissionMapper

package com.jz.mapper;

import com.jz.pojo.Permission;

import java.util.List;

public interface PermissionMapper {
    /**
     * 根据用户ID查询权限
     * @param userId
     * @return
     */
    List<Permission> selectPermissionsByUserId(Integer userId);
}

4.5 mapper.xml文件

UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jz.mapper.UserMapper">
    <!--根据用户名和密码查询可用的用户-->
    <select id="getUserByUsernamePassword" resultType="User">
        select * from users where username=#{username}
        and status=1
    </select>
</mapper>

RoleMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jz.mapper.RoleMapper">
    <select id="selectRolesByUserId" resultType="Role">
        SELECT * FROM role WHERE id
         IN (SELECT r.id FROM role r,users_role ur
             WHERE r.id=ur.roleId AND userId=#{userId})
    </select>
</mapper>

Permission.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jz.mapper.PermissionMapper">
    <select id="selectPermissionsByUserId" resultType="Permission">
        SELECT * FROM permission WHERE id IN(
        SELECT permissionId FROM role_permission WHERE  roleId IN(
        SELECT roleId  FROM users_role WHERE userId=#{userId}));
    </select>
</mapper>

4.6 权限角色查询的配置类

MyUserDetailsService.java

package com.jz.service;

import com.jz.mapper.PermissionMapper;
import com.jz.mapper.RoleMapper;
import com.jz.mapper.UserMapper;
import com.jz.pojo.Permission;
import com.jz.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    //数据库查询权限角色信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //认证用户
      com.jz.pojo.User user= userMapper.getUserByUsernamePassword(username);
        //判断用户名是否存在
        if(user==null){
            throw new UsernameNotFoundException("用户不存在!");
        }
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        //用户存在的话查询角色
        List<Role> roles = roleMapper.selectRolesByUserId(user.getId());
        System.out.println("============角色================");
        for (Role role : roles) {
            System.out.println(role.getRoleDesc());
            SimpleGrantedAuthority authority=new
                						SimpleGrantedAuthority(role.getRoleDesc());
            authorities.add(authority);
        }
        //查询权限
        List<Permission> permissions = 
            				permissionMapper.selectPermissionsByUserId(user.getId());
        System.out.println("============权限================");
        for (Permission permission : permissions) {
            System.out.println(permission.getUrl());
            SimpleGrantedAuthority authority=
                				new SimpleGrantedAuthority(permission.getUrl());
            authorities.add(authority);
        }
        return new User(username,user.getPassword(), authorities);
    }
}

4.7 相关配置文件

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/securitydemo
jdbc.username=root
jdbc.password=1704

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
	<context:component-scan base-package="com.jz">
		<context:exclude-filter type="annotation"
								expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
	<!--配置数据源-->
	<context:property-placeholder location="classpath:db.properties"/>
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driver}"></property>
		<property name="jdbcUrl" value="${jdbc.url}"></property>
		<property name="user" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>
	</bean>
	<!--配置事务控制器-->
	<bean id="transactionManager"
		  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!--开启注解事务管理-->
	<tx:annotation-driven transaction-manager="transactionManager"/>
	<!--mybatis相关配置-->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!--配置数据源-->
		<property name="dataSource" ref="dataSource"></property>
		<!--加载sql映射文件-->
		<property name="mapperLocations" value="classpath:mappers/*.xml"></property>
		<!--设置别名-->
		<property name="typeAliasesPackage" value="com.jz"></property>
	</bean>
	<bean id="scannerConfigurer"
		  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.jz.mapper"></property>
	</bean>
	<!-- 配置加密类 -->
	<bean id="passwordEncoder"
		  class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
</beans>

springmvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xmlns:p="http://www.springframework.org/schema/p"
	   xmlns:mvc="http://www.springframework.org/schema/mvc"
	   xmlns:aop="http://www.springframework.org/schema/aop"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
	<context:component-scan base-package="com.jz" use-default-filters="false">
		<context:include-filter type="annotation"
								expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
	<mvc:annotation-driven></mvc:annotation-driven>
	<mvc:default-servlet-handler></mvc:default-servlet-handler>
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	<!--
		支持AOP的注解支持,AOP底层使用代理技术
		JDK动态代理,要求必须有接口
		cglib代理,生成子类对象,proxy-target-class="true" 默认使用cglib的方式
	-->
	<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>

spring-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       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.xsd
       http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security.xsd">


    <!-- 配置不过滤的资源(静态资源及登录相关) -->
    <security:http pattern="/login.jsp" security="none"/>
    <security:http pattern="/fail.jsp" security="none"/>
    <security:http pattern="/css/**" security="none"/>
    <security:http pattern="/img/**" security="none"/>
    <security:http pattern="/plugins/**" security="none"/>
    <!--
    http:用于定义相关权限控制
    auto-config:是否自动配置
        设置为true时框架会提供默认的一些配置,例如提供默认的登录页面、登出处理等
        设置为false时需要显示提供登录表单配置,否则会报错
   use-expressions="false":禁用spEL表达式-->
    <security:http auto-config="true" use-expressions="false">

        <!-- 配置资源连接,访问任何资源,都需要拥有ROLE_USER -->
        <security:intercept-url pattern="/**" access="ROLE_USER"/>

        <!--登录:
        1. login-page 自定义登录页url,默认为/login
        2. login-processing-url form表单提交时指定的action
        3. default-target-url 默认登录成功后跳转的url
        4. authentication-failure-url 登录失败后跳转的url
        5. username-parameter 用户名的请求字段 默认为userName
        6. password-parameter 密码的请求字段 默认为password-->
        <security:form-login login-page="/login.jsp"
                             login-processing-url="/login"
                             username-parameter="username"
                             password-parameter="password"
                             authentication-failure-url="/fail.jsp"
                             default-target-url="/index.jsp"
                             />
        <!-- 登出:
         invalidate-session 是否删除session
         logout-url:登出处理链接
         logout-success-url:登出成功页面
         注:登出操作 只需要链接到 logout即可登出当前用户 -->
        <security:logout invalidate-session="true" logout-url="/logout"
                         logout-success-url="/login.jsp"/>
        <!-- 关闭CSRF,默认是开启的 跨域攻击-->
        <security:csrf disabled="true"/>
        <!-- 尝试访问没有权限的页面时跳转的页面 -->
        <security:access-denied-handler error-page="/error-noauth.jsp"/>
    </security:http>
    <!--认证管理器-->
    <security:authentication-manager>
        <security:authentication-provider user-service-ref="myUserDetailsService">
            <!-- 配置加密的方式 -->
            <security:password-encoder ref="passwordEncoder"/>
        </security:authentication-provider>

    </security:authentication-manager>
    <!--开启jsr250注解-->
    <security:global-method-security jsr250-annotations="enabled"
                                     pre-post-annotations="enabled"
                                     secured-annotations="enabled"/>
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
		 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
		 version="4.0">


	<display-name>Archetype Created Web Application</display-name>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml,classpath:spring-security.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!--
        DelegatingFilterProxy是Spring的Web模块中的一个类,
        它提供了让HTTP请求在到达实际目的地之前通过过滤器的功能。
    -->
	<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>

	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>



	<servlet>
		<servlet-name>dispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

4.8 创建页面

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<span style="color: blue;font-size: 20px">
  【当前登录用户[${sessionScope.SPRING_SECURITY_CONTEXT.authentication.principal.username}]】
</span>
<h1>主页--->登录成功</h1>
  <a href="/logout">退出</a><br/><hr>
  <a href="/book/list">书籍列表</a><br/><hr>
  <a href="/book/add">新增书籍</a><br/><hr>
  <a href="/book/update">书籍修改</a><br/><hr>
  <a href="/book/delete">删除书籍</a><br/><hr>
</body>
</html>

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link rel="icon" href="图标路径;base64,aWNv"/>
</head>
<body>
    <h1>login.jsp</h1>
    <form action="/login" method="post">
        用户名:<input type="text" name="username" value=""><br>
        密码:<input type="password" name="password" value=""><br>
        <input type="submit" value="登录">
    </form>
</body>
</html>

fail.jsp(登录失败页面)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1 style="background: hotpink">登录失败</h1>
</body>
</html>

error-noauth.jsp(没有权限页面)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1 style="color: red">您无权访问</h1>
</body>
</html>

main.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>书籍管理页面</h1>
    <h2>${msg}</h2>
</body>
</html>

4.9 创建controller

package com.jz.controller;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("book")
public class BookController {
    @GetMapping("/list")
    @PreAuthorize("hasAnyAuthority('book:list')")
    public String bookList(Model model) {
        System.out.println("访问书籍查询界面成功!");
        model.addAttribute("msg","访问书籍查询界面成功!");
        return "main";
    }
    @GetMapping("/add")
    @PreAuthorize("hasAnyAuthority('book:add','book:insert')")
    public String bookAdd(Model model) {
        System.out.println("访问书籍新增界面成功!");
        model.addAttribute("msg","访问书籍新增界面成功!");
        return "main";
    }
    @GetMapping("/update")
    //必须有book:edit权限才能访问bookUpdate方法
    @PreAuthorize("hasAnyAuthority('book:edit')")
    public String bookUpdate(Model model) {
        System.out.println("访问书籍修改界面成功!");
        model.addAttribute("msg","访问书籍修改界面成功!");
        return "main";
    }
    @GetMapping("/delete")
    //只要具有"ROLE_USER","ROLE_ADMIN"任意一种角色就可以访问。
    @Secured({"ROLE_USER", "ROLE_ADMIN"})
    public String bookDelete(Model model) {
        System.out.println("访问书籍删除界面成功!");
        model.addAttribute("msg","访问书籍删除界面成功!");
        return "main";
    }
}

5.1 项目结构

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GawiOlgH-1687834244156)(image/1686498532587.png)]

5.2 ssm整合springsecurity流程

1. 加入依赖包
2. 创建包结构(pojo、mapper、service、controller)
3. spring整合springmvc(springmvc.xml、applicationContext.xml)
4. 在web.xml文件中配置spring监听器、前端控制器、解决中文乱码的过滤器、DelegatingFilterProxy
5. spring整合mybatis(db.properties指定数据源,applicationContext.xml文件中配置整合mybatis)
6. 创建securitydemo数据库和表
7. 创建表对应的实体类
8. 创建实体类对应的mapper接口和xml文件
9. 在mapper接口和xml文件中写用户查询、角色查询、权限查询
10. 自定义认证管理器类:MyUserDetailsService(查询用户、角色、权限)进行认证
11. 创建spring-security.xml文件配置认证和授权
12. 创建BookController和一些jsp页面进行测试

5. 获取当前登陆了用户的方式

https://www.freesion.com/article/79481159731/

6. springsecurity认证流程

https://blog.csdn.net/msq16021/article/details/126143791

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/690768.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

nexus 配置pypi代理

在研发环境中由于网络限制&#xff0c;无法访问外网&#xff0c;但经常使用npm、maven、pip等工具&#xff0c;这种场景中使用nexus 做代理是一个比较好的解决办法。 在配置pypi代理时&#xff0c;和配置npm、maven代理有所不同&#xff0c;在配置远程地址时&#xff0c;需要将…

我的IDEA插件

文章目录 前言一、.ignore二、Adapter for Eclipse Code Formatter三、Convert YAML and Properties File四、EasyCode五、Free MyBatis Tool六、Maven Helper七、Rainbow Brackets 前言 目前使用比较顺手的插件&#xff0c;具体使用方法自行查阅 一、.ignore git 忽略文件&…

【算法与数据结构】344、LeetCode反转字符串

文章目录 一、题目二、解法三、完整代码 所有的LeetCode题解索引&#xff0c;可以看这篇文章——【算法和数据结构】LeetCode题解。 一、题目 二、解法 思路分析&#xff1a;关于变量交换有两种办法&#xff0c;一种是最常见的引入一个临时变量方法&#xff0c;另一种是使用位运…

【Java面试题】Java基础——集合

文章目录 集合的形式List和Set的区别ArrayList和LinkedList的区别ArrayList和数组的区别ArrayList的扩容机制是什么&#xff1f;ArrayList有哪些特点List和Map的区别如何让map存储有序数据如何创建Map?常用的Map有哪些?如何在HashMap中插入一个数据遍历一个 List 有哪些不同的…

高清音频文件如何压缩?分享轻松压缩音频文件的方法!

如何进行音频压缩&#xff1f;在我们日常生活中&#xff0c;音频文件扮演着重要的角色&#xff0c;我们可以通过它们享受音乐、收听播客或处理语音录音等。然而&#xff0c;有时候这些音频文件的大小可能会成为问题&#xff0c;特别是当我们需要在有限的存储空间中存储更多的文…

深入浅出设计模式 - 原型模式

博主介绍&#xff1a; ✌博主从事应用安全和大数据领域&#xff0c;有8年研发经验&#xff0c;5年面试官经验&#xff0c;Java技术专家✌ Java知识图谱点击链接&#xff1a;体系化学习Java&#xff08;Java面试专题&#xff09; &#x1f495;&#x1f495; 感兴趣的同学可以收…

STM32模拟I2C获取TCS34725光学颜色传感器数据

STM32模拟I2C获取TCS34725光学颜色传感器数据 TCS34725是RGB三色颜色传感器&#xff0c;和TCS34727都属于TCS3472系列&#xff0c;在电气特性上略有差别&#xff0c;TCS34727相比TCS34725在I2C总线的访问电平上可以更低&#xff0c;而在I2C软件访问地址方面则一致。 TCS3472内…

leetcode:1431. 拥有最多糖果的孩子(python3解法)

难度&#xff1a;简单 给你一个数组 candies 和一个整数 extraCandies &#xff0c;其中 candies[i] 代表第 i 个孩子拥有的糖果数目。 对每一个孩子&#xff0c;检查是否存在一种方案&#xff0c;将额外的 extraCandies 个糖果分配给孩子们之后&#xff0c;此孩子有 最多 的糖…

Spring Boot中的@RequestMapping注解,如何使用

Spring Boot中的RequestMapping注解 介绍 Spring Boot是一个流行的Java框架&#xff0c;它提供了许多方便的注解和工具&#xff0c;使得Web应用程序的开发变得更加容易。其中&#xff0c;RequestMapping注解是Spring Boot中最常用的注解之一&#xff0c;它可以帮助开发者定义…

django旅游推荐系统-计算机毕设 附源码82884

django旅游推荐系统 摘 要 随着社会的快速发展和人们生活水平的不断提高&#xff0c;旅游已逐渐成为人们生活的重要组成部分&#xff0c;用户能够获取旅游信息的渠道也随信息技术的广泛应用而增加。大量未经过滤的信息在展示给用户的同时&#xff0c;也淹没了用户真正感兴趣的信…

10个图像处理的Python库

在这篇文章中&#xff0c;我们将整理计算机视觉项目中常用的Python库&#xff0c;如果你想进入计算机视觉领域&#xff0c;可以先了解下本文介绍的库&#xff0c;这会对你的工作很有帮助。 1、PIL/Pillow Pillow是一个通用且用户友好的Python库&#xff0c;提供了丰富的函数集…

【MOOC 测验】第5章 链路层

1、局域网的协议结构一般不包括&#xff08; &#xff09; A. 数据链路层B. 网络层C. 物理层D. 介质访问控制层 逻辑链路控制子层、介质访问控制子层、物理层 2、下列关于二维奇偶校验的说法&#xff0c;正确的是&#xff08; &#xff09; A. 可以检测和纠正双比特差错B…

OV Image Sensor PLL设置

本文讨论OV的Image Sensor PLL的配置。 1.PLL的组成和功能 如图为OS08A10的框图&#xff0c;由图可知&#xff0c;Image Sensor其实是一个模数混合的电路&#xff0c;PLL提供了诸如ADC,gain control,MIPI,I2C等电路所用的时钟。 既然 Image Sensor的PLL是Image Senor非常重要…

详解Vue组件系统

Vue渲染的两大基础方式 new 一个Vue的实例 这个我们一般会使用在挂载根节点这一初始化操作上&#xff1a; new Vue({el: #app }) 复制 注册组件并使用 通过Vue.component&#xff08;&#xff09;去注册一个组件&#xff0c;你就可以全局地使用它了&#xff0c;具体体现在…

什么是信号槽机制,如何实现,有什么用?(Qt面试题)

1. 什么是信号槽机制&#xff1f; 信号槽机制&#xff08;Signal-Slot mechanism&#xff09;是一种在软件开发中常用的设计模式&#xff0c;用于实现对象间的通信和事件处理。该机制最初由Qt框架引入并广泛应用&#xff0c;后来也被其他编程框架和库所采用。 信号槽机制通过定…

这样做,轻松拿捏阻焊桥!

PCB表面的一层漆&#xff0c;称为阻焊油墨&#xff0c;也就是PCB线路板阻焊油墨。阻焊油墨是PCB线路板中非常常见、也是主要使用的油墨&#xff0c;一般90%都是绿色&#xff0c;但也有杂色油墨&#xff1a;红色、蓝色、黑色、白色、黄色等。 阻焊油墨的作用就是绝缘&#xff0…

postman持续集成-Jenkins手动构建

Jenkins启动 在jenkins.war文件所在的目录输入cmd打开终端输入: java -jar jenkins.war启动服务,启动后终端的窗口不要关闭 在浏览器地址栏输入:localhost:8080 准备工作 打开已完成并测试无误的postman项目脚本,再次执行测试 导出测试用例集和测试环境两个文件,注意全部…

【换根DP】CF1324F

Maximum White Subtree - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) 题意&#xff1a; 思路&#xff1a; 先去树形DP求出DP值&#xff0c;这很好求 设dp[u]为以u为根的子树中白-黑的最大值 初始化就是&#xff1a;如果u本身是黑&#xff0c;那dp[u]-1&#xff0c;否则dp…

K8s(Kubernetes)学习(三):pod概念及相关操作

1 什么是 Pod 摘取官网: https://kubernetes.io/zh-cn/docs/concepts/workloads/pods/#working-with-pods 1.1 简介 Pod 是可以在 Kubernetes 中创建和管理的、最小的可部署的计算单元。Pod&#xff08;就像在鲸鱼荚或者豌豆荚中&#xff09;是一组&#xff08;一个或多个&…

【Java面试题】Java基础——面向对象

文章目录 重载和重写的区别★★★Java的三大特性请说明一下Super关键字的作用&#xff1f;static关键字的作用&#xff1f;final关键字的作用&#xff1f;super关键字和this关键字的作用&#xff1f;面向对象的三大特性★★★成员变量和局部变量的区别&#xff1f;Java能实现多…