SpringBoot
约定大约配置
(Maven、Spring、SpringMVC、SpringBoot)
1、微服务
1.什么是微服务
微服务是一种架构风格,他要求我们在开发一个应用的时候,这个应用必须 构建成一系列小服务的组合;
2、HelloWorld
导入Web依赖
这样就可以直接使用springboot自带的tomcat了
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
写一个Controller文件
controller包必须跟*Application.class在同一级别下
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "Hello World";
}
}
启动服务器
运行*Application的主方法
可以在application.properties文件中设置端口号
#更改端口号
server.port=8081
测试
进入网页就可以
3、实现原理(自动装配,run方法)
不全,网上搜吧 -。-
自动配置:
pom.xml
-
spring-boot-dependencies :核心依赖,在父工程中
引入SpringBoot的依赖的时候不需要指定版本号
启动器
-
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency>
-
启动器:说白了就是SpringBoot的启动场景
-
spring-boot-starter-web,他就会帮助我们自动导入web环境所有的依赖
-
springboot会将所有的功能场景,都变成一个个启动器
主程序
//标注这个类是一个springboot的应用
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
//利用反射,启动springboot
SpringApplication.run(DemoApplication.class, args);
}
}
SpringBootApplication
-
@SpringBootConfiguration:springboot的配置
@Configuration:spring配置类
@Component:说明这也是一个spring的组件
-
@EnableAutoConfiguration:自动配置
@AutoConfigurationPackage:自动配置包
@Import(AutoConfigurationPackages.Registrar.class):导入选择器
@Import(AutoConfigurationImportSelector.class):自动配置,导入选择
List configurations = getCandidateConfigurations(annotationMetadata, attributes);获取所有的配置
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
getBeanClassLoader());
Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
+ "are using a custom packaging, make sure that file is correct.");
return configurations;
}
结论:SpringBoot的所有自动配置都是在启动的时候扫描并加载:spring.factories所有的自动配置类都在这里
,但不一定生效,倒入了start,就有了对应的启动器,自动装配就会生效。
4、Yaml配置文件的使用
@Component
public class Dog {
private String name;
private int age;
//下面还有构造方法和get set
}
@Component
//指向yaml中创建的person对象
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private int age;
private boolean happy;
private Date birthday;
private Map<String,Object> maps;
private List<String> lists;
private Dog dog;
}
person:
#随机生成一个uuid
name: dong${random.uuid}
#随机生成一个整数
age: ${random.int}
happy: true
birthday: 2020/7/12
maps: {k1: v1,k2: v2}
hello: Happy
lists:
- code
- music
- girl
dog:
#如果person.hello存在就直接显示,不存在使用hello
name: ${person.hello:hello}_旺财
age: 3
拓展
//指定properties文件
@PropertySource(value = "classpath:dong.properties")
public class Person {
//从文件中取出值
@Value("${name}")
private String name;
JSR303校验
导入maven依赖
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.13.Final</version>
</dependency>
使用注解进行校验
@Validated
public class Person {
@Email(message = "邮箱格式错误")
private String name;
}
JSR的注解
@Null //被注释的元素必须为null
@NotNull //被注释的元素必须部位null
@AssertTrue //被注释的元素必须为true
@AssertFalse //被注释的元素必须为false
@Min(value) //被注释的必须是数字,必须大于等于最小值
@Max(value) //被注释的必须是数字,必须大于等于最大值
@DecimalMin(value) //被注释的必须是数字,必须大于等于最小值
@DecimalMax(value) //被注释的必须是数字,必须大于等于最大值
@Size(max,min) //被注释的元素大小必须在指定范围内
@Digits(integer,fraction) //被注释的必须是数字,其值必须在指定范围内
@Past //被注释的元素必须是一个过去的日期
@Future //被注释的元素必须是一个将来的日期
@Pattern(value) //被注释的元素必须必须符合指定的正则表达式
同时配置多套环境
server:
port: 8081
spring:
profiles:
active: dev
---
server:
port: 8082
spring:
profiles: dev
---
server:
port: 8083
spring:
profiles: test
5、Web开发
静态资源可以存放的目录:
- webjars
- public,static,/**,resources
自定义配置文件
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index.html").setViewName("index");
registry.addViewController("/").setViewName("index");
registry.addViewController("/main.html").setViewName("dashboard");
}
}
6、Thymeleaf
在网页导入依赖
<html xmlns:th=http://www.thymeleaf.org>
语法
<div th:text="${msg}"></div> <!--不会转义-->
<div th:utext="${msg}"></div> <!--会转义-->
<hr>
<h3 th:each="user:${list}" th:text="${user}"></h3> <!--遍历-->
<hr>
<h3 th:each="user:${list}">
[[${user}]]
</h3>
7、国际化
-
配置i8n文件
-
自定义一个组件
public class MyLocalResolver implements LocaleResolver { @Override public Locale resolveLocale(HttpServletRequest request) { String language = request.getParameter("l"); Locale locale = Locale.getDefault(); if (!StringUtils.isEmpty(language)){ String[] s = language.split("_"); locale = new Locale(s[0], s[1]); } return locale; } @Override public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) { } }
-
把组件注入到@Bean中
@Bean public LocaleResolver localeResolver(){ return new MyLocalResolver(); }
-
前端请求
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a> <a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
数据显示
<!--#{}:进行数据显示--> <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
8、配置拦截器
实现HandlerInterceptor接口自定义拦截器
public class LoginHandler implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//登陆成功之后,应该有用户的session
Object loginUser = request.getSession().getAttribute("loginUser");
if (loginUser==null){
request.setAttribute("msg","没有权限请先登录");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}
return true;
}
}
将拦截器配置到Configuration
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandler())
.addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/user/login");
}
9、配置Druid数据源
1、导入Druid依赖和log4j的依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2、通过application.yaml文件配置Druid
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
#以下开始配置Druid
type: com.alibaba.druid.pool.DruidDataSource
maxPoolPreparedStatementPerConnectionSize: 20
filters: stat,wall,log4j
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
3、通过配置类,配置监控页面
@Configuration
//相当于web.xml文件
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
//后台监控功能
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
HashMap<String, String> initParameters = new HashMap<>();
initParameters.put("loginUsername","root");
initParameters.put("loginPassword","123456");
bean.setInitParameters(initParameters);
return bean;
}
}
4、使用配置好的用户名和密码,登录配置的路径“/druid/**”
10、整合Mybatis
1、导入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
2、创建包
正常创建mapper、pojo和controller包
但是我把mapper的xml文件放到resource下新建的mybatis下的mapper文件夹中
3、配置别名和扫描xml文件
在application.yaml中配置
mybatis:
type-aliases-package: com.dong.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
4、写pojo类,和以前一样
5、写mapper接口
@Mapper
@Repository
public interface UserMapper {
List<User> queryUserList();
User queryUserById(@Param("id") Integer id);
int updateUser(User user);
}
6、写mapper.xml和以前一样
11、SpringSecurity(安全)
几个类:
- WebSecurityConfigurerAdapter:自定义Security策略
- AuthenticationManagerBuilder:自定义认证策略
- @EnableWebSecurity:开启WebSecurity模式
SpringSecurity的两个主要目标是“认证”和“授权”(访问控制)
“认证”:Authentication
“授权”:Authorization
1、导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2、编写配置类
@EnableWebSecurity
public class SerurityConfig extends WebSecurityConfigurerAdapter {
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人都可以访问,功能也只有对应有权限的人才能访问
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限到登录页
//loginPage指定登录的页面
//loginProcessingUrl指定登录提交的表单
//usernameParameter指定前端用户名文本框的name属性
//passwordParameter指定前端密码框的name属性
http.formLogin().loginPage("/tologin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");
//注销,成功跳转首页
http.logout().logoutSuccessUrl("/");
//开启记住我功能,默认保存两周
//rememberMeParameter指定记住我复选框的name属性
http.rememberMe().rememberMeParameter("remember");
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("dongdong").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
3、根据不同的等级显示不同的页面
<!--导入命名空间xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
-->
<html xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<!--
sec:authorize="!isAuthenticated()"
判断是否登录
-->
<div sec:authorize="!isAuthenticated()">
<a class="item" th:href="@{/toLogin}" >
<i class="address card icon"></i> 登录
</a>
</div>
<div sec:authorize="isAuthenticated()">
<a class="item">
<!--sec:authentication="name"显示用户名-->
用户名:<span sec:authentication="name"></span>
</a></div>
<!--sec:authorize="hasRole('vip1')"判断权限是否是vip1-->
<div class="column" sec:authorize="hasRole('vip1')">
12、Shiro
1、导入依赖
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.5.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/jcl-over-slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>2.0.0-alpha1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>2.0.0-alpha1</version>
</dependency>
2、配置文件
log4j.properties
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
shrio.ini
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5
QuickStart.class
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Simple Quickstart application showing how to use Shiro's API.
*
* @since 0.9 RC2
*/
public class QuickStart {
private static final transient Logger log = LoggerFactory.getLogger(QuickStart.class);
public static void main(String[] args) {
// The easiest way to create a Shiro SecurityManager with configured
// realms, users, roles and permissions is to use the simple INI config.
// We'll do that by using a factory that can ingest a .ini file and
// return a SecurityManager instance:
// Use the shiro.ini file at the root of the classpath
// (file: and url: prefixes load from files and urls respectively):
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
// for this simple example quickstart, make the SecurityManager
// accessible as a JVM singleton. Most applications wouldn't do this
// and instead rely on their container configuration or web.xml for
// webapps. That is outside the scope of this simple quickstart, so
// we'll just do the bare minimum so you can continue to get a feel
// for things.
SecurityUtils.setSecurityManager(securityManager);
// Now that a simple Shiro environment is set up, let's see what you can do:
// get the currently executing user:
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
// let's login the current user so we can check against roles and permissions:
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true);
try {
currentUser.login(token);
} catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// ... catch more exceptions here (maybe custom ones specific to your application?
catch (AuthenticationException ae) {
//unexpected condition? error?
}
}
//say who they are:
//print their identifying principal (in this case, a username):
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//test a role:
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
//test a typed permission (not instance-level)
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//a (very powerful) Instance Level permission:
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
//all done - log out!
currentUser.logout();
System.exit(0);
}
}
Subject currentUser = SecurityUtils.getSubject(); //创建subject
Session session = currentUser.getSession(); //通过subject得到session
currentUser.login(token); //登录
currentUser.isAuthenticated() //是否被认证
currentUser.getPrincipal() //得到认证
currentUser.hasRole("schwartz") //是否有这个角色
currentUser.isPermitted("lightsaber:wield") //获得权限
currentUser.logout(); //注销
13、Springboot整合Shiro
1、整合Mybatis
2、导入shiro-spring依赖
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.5.3</version>
</dependency>
3、两个工具类
ShrioConfig.class
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.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShrioConfig {
//第三步:ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//设置安全管理器
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
//添加内置过滤器
/*
* anon:无需认证就可访问
* authc:必须认证才能访问
* user:必须拥有记住我功能才能访问
* perms:拥有某个资源的权限才能访问
* role:拥有某个角色权限才能访问
* */
Map<String, String> filterMap = new LinkedHashMap<>();
filterMap.put("/user/add","perms[wen]");
filterMap.put("/user/update","perms[sunxing]");
filterMap.put("/user/*","authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
//拦截后跳转登录页面
shiroFilterFactoryBean.setLoginUrl("/tologin");
//未授权请求
shiroFilterFactoryBean.setUnauthorizedUrl("/noauth");
return shiroFilterFactoryBean;
}
//第二步:DefaultWebSecurityManager
@Bean(name = "defaultWebSecurityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
//关联Realm
defaultWebSecurityManager.setRealm(userRealm);
return defaultWebSecurityManager;
}
//第一步:创建realm对象,需要自定义
@Bean(name = "userRealm")
public UserRealm userRealm() {
return new UserRealm();
}
;
}
UserRealm.class
import com.example.pojo.User;
import com.example.service.UserService;
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 {
@Autowired
private UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=》授权");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermission("user:add");
//拿到当前对象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User) subject.getPrincipal();
info.addStringPermission(currentUser.getUserCode());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=》认证");
//用户名,密码
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
User user = userService.queryByName(userToken.getUsername());
if (user==null){
return null;
}
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
session.setAttribute("loginUser",user);
return new SimpleAuthenticationInfo(user,user.getUserPassword(),"");
}
}
Controller中的登录模块
@RequestMapping("/login")
public String login(String username,String password,Model model){
//获取当前用户
Subject subject = SecurityUtils.getSubject();
//封装用户登录数据
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);
return "index";
} catch (UnknownAccountException e) {
//用户名不存在
model.addAttribute("msg","用户名不存在");
return "login";
}catch (IncorrectCredentialsException e){
model.addAttribute("msg","密码错误");
return "login";
}
}
14、Thymeleaf整合Shiro
1、导入依赖
<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
2、在ShrioConfig.class中配置
//整合Shiro和Thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
3、前端使用
<div shiro:hasPermission="wen">
<a th:href="@{/user/add}">add</a>
</div>
<div shiro:hasPermission="sunxing">
<a th:href="@{/user/update}">update</a>
</div>
<div th:if="${session.loginUser==null}">
<a th:href="@{/tologin}">登录</a>
</div>
//用户名不存在
model.addAttribute("msg","用户名不存在");
return "login";
}catch (IncorrectCredentialsException e){
model.addAttribute("msg","密码错误");
return "login";
}
}
14、Thymeleaf整合Shiro
1、导入依赖
<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
2、在ShrioConfig.class中配置
//整合Shiro和Thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
3、前端使用
<div shiro:hasPermission="wen">
<a th:href="@{/user/add}">add</a>
</div>
<div shiro:hasPermission="sunxing">
<a th:href="@{/user/update}">update</a>
</div>
<div th:if="${session.loginUser==null}">
<a th:href="@{/tologin}">登录</a>
</div>