ShiroConfig配置
package com.joel.shiro; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.LinkedHashMap; import java.util.Map; @Configuration public class ShiroConfig { //创建ShiroFilterFactoryBean @Bean public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); //设置安全管理器 shiroFilterFactoryBean.setSecurityManager(securityManager); //添加shiro内置过滤器 //常用过滤器 // anon无需认证可以访问 // authc 必须认证才能访问 // user 如果使用remeberMe的功能可以直接访问 // perms:该资源必须得到资源授权才能访问 // role:该资源必须得到角色权限才能访问 Map<String, String> filterMap = new LinkedHashMap<>(); // filterMap.put("/add", "authc"); // filterMap.put("/update", "authc"); filterMap.put("/testThymeleaf","anon"); filterMap.put("/login","anon"); // 授权过滤器 // 授权过滤器一定要放在所有拦截的后面 filterMap.put("/add","perms[user:add]"); filterMap.put("/update","perms[user:update]"); //设置未授权提示的页面 shiroFilterFactoryBean.setUnauthorizedUrl("/unAuth"); // 修改跳转的页面 shiroFilterFactoryBean.setLoginUrl("/tologin"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap); shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth"); return shiroFilterFactoryBean; } @Bean(name = "securityManager") //创建DefaultWebSecurityManager public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // 关联realm securityManager.setRealm(userRealm); return securityManager; } //创建Realm @Bean(name = "userRealm") public UserRealm getRealm() { return new UserRealm(); } }
Realm的编写
package com.joel.shiro; import com.joel.springboot.model.Student; import com.joel.springboot.service.StudentService; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; public class UserRealm extends AuthorizingRealm { //执行授权逻辑 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("执行授权逻辑"); //给资源进行授权 SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(); //添加资源的授权字符串 //info.addStringPermission("user:add"); //到数据库查询当前登陆用户的授权 Subject subject= SecurityUtils.getSubject(); Student student=(Student)subject.getPrincipal(); Student dbStudent =studentService.findById(student.getId()); info.addStringPermission(dbStudent.getPerms()); System.out.println("执行授权逻辑完成"); return info; } @Autowired private StudentService studentService; //执行认证逻辑 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arga) throws AuthenticationException { System.out.println("执行认证逻辑"); //假设数据库的用户名和密码 System.out.println("认证成功"); //1.判断用户名 UsernamePasswordToken token=(UsernamePasswordToken)arga; System.out.println("认证成功"); Student student=studentService.findByStudentname(token.getUsername()); System.out.println("认证成功"); if(!token.getUsername().equals(student.getName())){ //用户名不存在 return null;//shiro底层会抛出一个UnKnowAccountException } //2判断密码.第二个参数一定是密码 return new SimpleAuthenticationInfo(student,student.getPassword(),""); } }
controller控制类
package com.joel.Controller; import com.joel.springboot.service.StudentService; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; 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 public class UserController { @GetMapping("add") public String add(Model model) { System.out.println("11"); model.addAttribute("msg", "11111"); return "add"; } @RequestMapping("/update") public String update() { System.out.println("22"); return "update"; } @RequestMapping("/testThymeleaf") public String testThymeleaf(Model model) { model.addAttribute("msg", "hello"); return "test"; } @GetMapping("/tologin") public String getlogin(Model model) { model.addAttribute("msg", "hello"); System.out.println("11"); return "login"; } @RequestMapping("/noAuth") public String noAuth(){ return "/noAuth"; } @Autowired private StudentService studentService; //登陆逻辑处理 @RequestMapping ("/login") public String login(String name,String password,Model model) { //使用shiro编写认证操作 //获取subject Subject subject = SecurityUtils.getSubject(); //封装用户数据 System.out.println("111"); UsernamePasswordToken token = new UsernamePasswordToken(name, password); System.out.println("111"); // 执行登陆方法 try { subject.login(token); //登陆成功 //跳转到testhtml页面 return "redirect:/testThymeleaf"; } catch (UnknownAccountException e) { model.addAttribute("msg", "用户不存在"); return "login"; } catch (IncorrectCredentialsException e) { model.addAttribute("msg", "密码错误"); return "login"; } } }
Mapper文件
package com.joel.springboot.mapper; import com.joel.springboot.model.Student; import org.apache.ibatis.annotations.Mapper; public interface StudentMapper { int deleteByPrimaryKey(Integer id); int insert(Student record); int insertSelective(Student record); Student selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Student record); int updateByPrimaryKey(Student record); public Student findByStudentname(String name); public Student findById(Integer id ); }
<?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.joel.springboot.mapper.StudentMapper"> <resultMap id="BaseResultMap" type="com.joel.springboot.model.Student"> <id column="id" jdbcType="INTEGER" property="id" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="age" jdbcType="INTEGER" property="age" /> <result column="password" jdbcType="VARCHAR" property="password" /> <result column="perms" jdbcType="VARCHAR" property="perms" /> </resultMap> <sql id="Base_Column_List"> id, name, age, password,perms </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from student where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from student where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.joel.springboot.model.Student"> insert into student (id, name, age, password) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{password,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.joel.springboot.model.Student"> insert into student <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="name != null"> name, </if> <if test="age != null"> age, </if> <if test="password != null"> password, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=INTEGER}, </if> <if test="name != null"> #{name,jdbcType=VARCHAR}, </if> <if test="age != null"> #{age,jdbcType=INTEGER}, </if> <if test="password != null"> #{password,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.joel.springboot.model.Student"> update student <set> <if test="name != null"> name = #{name,jdbcType=VARCHAR}, </if> <if test="age != null"> age = #{age,jdbcType=INTEGER}, </if> <if test="password != null"> password = #{password,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.joel.springboot.model.Student"> update student set name = #{name,jdbcType=VARCHAR}, age = #{age,jdbcType=INTEGER}, password = #{password,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> <select id="findByStudentname" parameterType="String" resultType="com.joel.springboot.model.Student"> select * from student where name =#{value } </select> <select id="findById" parameterType="int" resultType="com.joel.springboot.model.Student"> select * from student where id=#{value } </select> </mapper>
application.properties文件配置
spring.resources.static-locations=classpath:/templates/ spring.thymeleaf.cache=false spring.thymeleaf.mode=LEGACYHTML5 spring.thymeleaf.suffix=.html spring.thymeleaf.encoding=UTF-8 mybatis.mapper-locations=classpath:com.joel.mapper/*.xml spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/springdb?userUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
GeneratorConfig.xml插件自动生成mapper可不写
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.7.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <java.version>1.8</java.version> <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version> <project.build.sorceEncoding>UTF-8</project.build.sorceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> </properties> <groupId>com.joel.shiro</groupId> <artifactId>01-demo-shiro</artifactId> <version>1.0.0</version> <name>01-demo-shiro</name> <description>Project for Spring Boot</description> <dependencies> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.11.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf</artifactId> <version>3.0.9.RELEASE</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.0</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.6</version> <configuration> <!--配置文件的位置 --> <configurationFile>GeneratorConfig.xml</configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> </resource> <resource> <directory>src/main/webapp</directory> <targetPath>META-INF/resources</targetPath> <includes> <include>**/*.*</include> </includes> </resource> </resources> </build> </project>
其他的也不多做累述了,说的够多了。未来的自己你要是这还看不懂,你可以别学了。嘻嘻