网站建设虚线的代码,wordpress报表模板下载,wordpress制作xml,制作网站单页很早之前写过Thymeleaf的文章#xff0c;所以重新温习一下#xff0c;非前后端分离#xff0c;仅仅只是学习
官网#xff1a; https://www.thymeleaf.org/ SpringBoot可以快速生成Spring应用#xff0c;简化配置#xff0c;自动装配#xff0c;开箱即用。 JavaConfigur… 很早之前写过Thymeleaf的文章所以重新温习一下非前后端分离仅仅只是学习
官网 https://www.thymeleaf.org/ SpringBoot可以快速生成Spring应用简化配置自动装配开箱即用。 JavaConfiguration java类来代替XML的配置。对常用的第三方库提供了配置方案可以很容易的与Spring进行整合快速进行企业级开发。 优势不需要配置任何XML文件、内嵌tomcat、默认支持JSON不需要进行转换、支持RESTful。
使用时启动类必须覆盖所有与业务相关的类即启动类所在的包必须是业务类所在包的同包或者⽗包如果没有覆盖业务类就不会⾃动装配到IoC容器中。
YAML是不同于Properties的另外⼀种⽂件格式同样可以⽤来写配置⽂件Spring Boot默认⽀持YAML格式 YAML的优点在于编写简单结构清晰利⽤缩紧的形式来表示层级关系。 相⽐于PropertiesYAML可以进⼀步简化配置⽂件的编写更加⽅便。属性名和属性值之间必须⾄少⼀个空格。
如果Properties和YAML两种类型的⽂件同时存在Properties的优先级更⾼。
配置⽂件除了可以放置在resources路径下之外还有3个地⽅可以放置优先级顺序如下所示 1、根路径下的config中的配置⽂件 2、根路径下的配置⽂件 3、resources路径下的config中的配置⽂件 4、resources路径下的配置⽂件
可以直接在Handler中读取YAML⽂件中的数据⽐如在业务⽅法中向客户端返回当前服务的端⼝信息。
Value(${server.port})
private String port;JSP动态网页技术底层为Servlet可在html代码中编写Java代码
JSP底层原理它是一种中间层组件开发者可以在这个组件中将java代码与html代码整合由JSP引擎将组件转为Servlet再把混合代码翻译为Servlet的响应语句输出给客户端。
环境搭建
1、创建基于Maven的Web项⽬pom.xml !-- Spring项目转为SpringBoot--
parentartifactIdspring-boot-starter-parent/artifactIdgroupIdorg.springframework.boot/groupIdversion2.3.4.RELEASE/version
/parentdependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependency!-- 引入Spring Boot 内嵌的Tomcat对jsp的解析包--dependencygroupIdorg.apache.tomcat.embed/groupIdartifactIdtomcat-embed-jasper/artifactIdversion9.0.33/version !--报错 version7.0.59/version--scopeprovided/scope/dependency!-- servlet 依赖的jar包start--dependencygroupIdjavax.servlet/groupIdartifactIdservlet-api/artifactIdversion2.3/versionscopeprovided/scope/dependency!-- jsp 依赖的jar包start--dependencygroupIdjavax.servlet.jsp/groupIdartifactIdjavax.servlet.jsp-api/artifactIdversion2.3.1/version/dependency!-- jstl标签 依赖的jar包start--dependencygroupIdjavax.servlet/groupIdartifactIdjstl/artifactId/dependency/dependencies
2、创建Handler
Controller
RequestMapping(/hello)
public class HelloHandler {GetMapping(/index)public ModelAndView index(){ModelAndView modelAndView new ModelAndView(index);modelAndView.addObject(msg,hello springboot jsp);return modelAndView;}
}3、JSP
% page languagejava contentTypetext/html; charsetUTF-8 pageEncodingUTF-8 %
% page isELIgnoredfalse %
html
headtitleTitle/title
/head
bodyh2${msg}/h2
/body
/html
4、application.yml(配置视图解析器)
server:port: 8080
#springmvc视图解析器
spring:mvc:view:prefix: /suffix: .jsp5、编写启动类Application.java
SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}6、更新web.xml防止加载其他xml片段的时候包报错
?xml version1.0 encodingUTF-8?
web-app xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlnshttp://java.sun.com/xml/ns/javaeexsi:schemaLocationhttp://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsdversion3.0display-nameArchetype Created Web Application/display-name
/web-app
实际运用crud
1、pom.xml导入jstl依赖
报错 NoSuchMethodError: org.apache.tomcat.JarScanner.scan只需要在Dependencies下找到自己引入的tomcat,比如我自己引入的是7.0.59,展开后下面9.0.33是springboot自带的,将版本改为9.0.33就可以了,问题解决!
2、实体类Userid和name
3、Handler中创建业务⽅法返回User对象
Controller
RequestMapping(/user)
public class UserHandler {Autowiredprivate UserService userService;GetMapping(/findAll)public ModelAndView findAll(){
// User user1 new User(1, jack);
// User user2 new User(2, jack2);
// List userList Arrays.asList(user1, user2);ModelAndView modelAndView new ModelAndView(findAll);modelAndView.addObject(userList,userService.findAll());return modelAndView;}PostMapping(/save)public String save(User user){ //写一个save页面formuserService.save(user);return redirect:/user/findAll;}GetMapping(/deleteById/{id})public String deleteById(PathVariable(id) Integer id){userService.deleteById(id);return redirect:/user/findAll;}GetMapping(/findById/{id})public ModelAndView findById(PathVariable(id) Integer id){ModelAndView modelAndView new ModelAndView(update);modelAndView.addObject(user,userService.findById(id));return modelAndView;}PostMapping(/update)public String update(User user){//写一个update页面form,但先要根据id查询数据在修改userService.update(user);return redirect:/user/findAll;}
}4、Repository
public interface UserService {public Collection findAll();public User findById(Integer id);public void save(User user);public void deleteById(Integer id);public void update(User user);
}5、Service
Repository
public class UserRepositoryImpl implements UserRepository {public static Map map;static {map new HashMap();map.put(1,new User(1,jack1));map.put(2,new User(2,jack2));map.put(3,new User(3,jack3));}Overridepublic Collection findAll() {return map.values();}Overridepublic User findById(Integer id) {return map.get(id);}Overridepublic void save(User user) {map.put(user.getId(),user);}Overridepublic void deleteById(Integer id) {map.remove(id);}Overridepublic void update(User user) {map.put(user.getId(),user);}
}6、JSP
findAll.jsp
% page languagejava contentTypetext/html; charsetUTF-8 pageEncodingUTF-8 %
% page isELIgnoredfalse %
% taglib prefixc urihttp://java.sun.com/jsp/jstl/core %
html
bodytabletrth编号/thth姓名/thth操作/th/trc:forEach items${userList} varuserstrtd${users.id}/tdtd${users.name}/tdtda href/user/deleteById/${users.id}删除/aa href/user/findById/${users.id}修改/a/td/tr/c:forEach/table
/body
/html
save.jsp
form action/user/save methodpostinput typetext nameid /input typetext namename /input typesubmit value保存 /
/form
update.jsp
form action/user/update methodpostinput typetext nameid value${user.id} readonly /input typetext namename value${user.name} /input typesubmit value修改 /
/form
Thymeleaf是⽬前较为流⾏的视图层技术Spring Boot官⽅推荐使⽤Thymeleaf。 它可以实现前后端分离的交互方式即视图与业务数据分开响应还可以直接将服务端返回的数据生成为HTML文件同时也可以处理XML、JavaScript、CSS等格式。
Thymeleaf最大的特点是既可以直接在浏览器打开静态方法也可以结合服务端将业务数据填充到html后动态生成的页面动态方法
1 使用
1、创建Maven⼯程不需要创建Web⼯程pom.xml
spring-boot-starter-parentorg.springframework.boot2.3.4.RELEASEorg.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-thymeleaf
2、application.yml
classpath一般用来指代src/main/resources下的资源路径其本质其实是指项目打包后target的classes下的路径
spring:thymeleaf:prefix: classpath:/templates/ #模板路径suffix: .html #模板后缀servlet:content-type: text/html #设置content-typeencoding: utf-8 #编码格式mode: HTML5 #校验h5格式cache: false #关闭缓存在开发过程中可以立即看到修改后的结果3、创建Handler
Controller
RequestMapping(/hello)
public class HelloHandler {GetMapping(/index)public ModelAndView index(){ModelAndView modelAndView new ModelAndView(index);modelAndView.addObject(name,小明);return modelAndView;}
}4、启动类
SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class,args);}
}5、templates目录下编写HTML
!DOCTYPE html
html langen
!--引入标签--
html xmlns:thhttp://www.thymeleaf.org
headmeta charsetUTF-8titleTitle/title
/head
body!--name的值会覆盖hello--p th:text${name}hello/p
/body
/html
2 注意
如果需要加载后台返回的业务数据则需要在HTML⻚⾯中使⽤Thymeleaf模版标签来完成。
1、需要引⼊模版标签 html xmlns:thhttp://www.thymeleaf.org/html 2、通过特定的标签完成操作 p th:text${name}hello/p
Thymeleaf模版标签不同于JSTLThymeleaf模版标签是直接嵌⼊到HTML原⽣标签内部。
3 Thymeleaf常⽤标签【重点】
th:text用于文本的显示将业务数据的值填充到html标签中。
th:if用于条件判断对业务数据的值进行判断。成立则显示内容。
p th:if${score90}优秀/p
p th:if${score90}不优秀/p
th:unless也⽤作条件判断逻辑与th:if恰好相反如果条件不成⽴则显示否则不显示。
th:switch th:case两个结合起来使⽤⽤作多条件等值判断
div th:switch${id}p th:case1a/pp th:case2b/pp th:case3c/p
/div
th:action⽤来指定请求的URL相当于form表单中的action属性、【重点】
如果action的值直接写在HTML中则需要使⽤{}
form th:action{/hello/login} methodpost
input typesubmit//form
如果是从后台传来的数据则使⽤${}。
GetMapping(/redirect/{url})
public Stringredirect(PathVariable(url) String url, Model model){model.addAttribute(url,/hello/login);return url;
}form th:action${url} methodpost
input typesubmit//form
th:each⽤来 遍历集合(类似foreach)
tabletr th:eachuser:${userList}td th:text${user.id}/tdtd th:text${user.name}/td/tr
/table
th:value⽤来给标签赋值
input typetext th:value${idValue}/
th:src⽤来引⼊静态资源相当于HTML原⽣标签img、script的src属性。
img th:src${src}/
如果src的值直接写在HTML中: img th:src{/1.png}
th:href⽤作设置超链接的href
ListUser list Arrays.asList(new User(1,jack),new User(2,tom));
ModelAndView modelAndView new ModelAndView(index);
modelAndView.addObject(list,list);
modelAndView.addObject(userName,tom);
selectoption th:eachuser:${list}th:value${user.id}th:text${user.name}th:selected${user.name userName}/option
/select
结合th:each来使⽤⾸先 遍历list集合 动态创建option元素根据每次遍历出的user.name与业务数据中的userName是否相等来决定是否要选择。
th:attr给HTML标签的任意属性赋值
input th:attrvalue${attr}/
等价于
input th:value${attr}/
4 Thymeleaf对象
Thymeleaf支持访问Servlet Web的原生资源HttpServletRequest、HttpServletResponse、HttpSession、ServletContext。
request获取HttpServletRequest对象response获取HttpServletResponse对象session获取HttpSession对象*servletContext获取ServletContext对象
GetMapping(/servlet)
public String servlet(HttpServletRequest request){request.setAttribute(value,request);request.getSession().setAttribute(value,session);request.getServletContext().setAttribute(value,servletContext);return servletTest;
}p th:text${#request.getAttribute(value)}/p
p th:text${#session.getAttribute(value)}/p
p th:text${#servletContext.getAttribute(value)}/p
p th:text${#response}/p
[注意]Thymeleaf⽀持直接访问session ${#request.getAttribute(name)}也可以简化 ${name}
5 Thymeleaf内置对象
dates⽇期格式化、calendars⽇期操作、numbers数字格式化、 strings字符串格式化、boolsboolean、arrays数组内置对象、 listsList集合内置对象、setsSet集合内置对象、mapsMap集合内置对象
index.html:
date格式化span th:text${#dates.format(date,yyyy-MM-dd)}/spanbr/
当前时间span th:text${#dates.createNow()}/spanbr/
当前日期span th:text${#dates.createToday()}/spanbr/
Calendar格式化span th:text${#calendars.format(calendar,yyyy-MM-dd)}/spanbr/number百分比格式化(小数点左右保留两位0.06--06.00%)
span th:text${#numbers.formatPercent(number,2,2)}/spanbr/
boolean是否为truespan th:text${#bools.isTrue(boolean)}/spanbr/String类型的name是否为空span th:text${#strings.isEmpty(string)}/spanbr/
name的长度span th:text${#strings.length(string)}/spanbr/
String类型的name拼接span th:text${#strings.concat(yu ,string)}/spanbr/
String类型的name拼接span th:text${#strings.concat(string, yu)}/spanbr/arrays的⻓度span th:text${#arrays.length(array)}/spanbr/
arrays是否包含jackspan th:text${#arrays.contains(array,jack)}/spanbr/
List是否为空span th:text${#lists.isEmpty(list)}/spanbr/
List的⻓度span th:text${#lists.size(list)}/spanbr/Set是否为空span th:text${#sets.isEmpty(set)}/spanbr/
Set的⻓度span th:text${#sets.size(set)}/spanbr/
Map是否为空span th:text${#maps.isEmpty(map)}/spanbr/
Map⻓度span th:text${#maps.size(map)}/spanbr/
Handler:
GetMapping(/inner)
public ModelAndView inner(){ModelAndView modelAndView new ModelAndView(index);modelAndView.addObject(date,new Date()); //日期Calendar calendar Calendar.getInstance();calendar.set(2022,4,27);modelAndView.addObject(calendar,calendar);modelAndView.addObject(number,0.06);modelAndView.addObject(string,hello world);modelAndView.addObject(boolean,true);modelAndView.addObject(array,Arrays.asList(jack,tom));List list new ArrayList();list.add(new User(1,jack1));list.add(new User(2,tom1));modelAndView.addObject(list,list);Set set new HashSet();set.add(new User(1,jack2));set.add(new User(2,tom2));modelAndView.addObject(set,set);Map map new HashMap();map.put(1,new User(1,jack3));map.put(2,new User(2,tom3));modelAndView.addObject(map,map);return modelAndView;
}JdbcTemplate是Spring自带的JDBC模块组件底层对JDBC进行了封装。用法与mybatis一样需要自定义sql语句它实现了数据库的连接SQL语句的执行结果集的封装。
缺点灵活性比如mybatis因为mybatis的SQL语句定义在xml配置文件中更有利于维护和扩展。 而JdbcTemplate以硬编码的方式将SQL直接写在Java代码中不利于维护扩展。
1、pom.xml
org.springframework.bootspring-boot-starter-jdbcmysqlmysql-connector-java
2、创建实体类
3、创建UserRepository接口以及实现类
Repository
public class UserRepositoryImpl implements UserRepository {Autowiredprivate JdbcTemplate jdbcTemplate; //直接引入Overridepublic List findAll() {return jdbcTemplate.query(select * from user,new BeanPropertyRowMapper(User.class));}Overridepublic User findById(Integer id) {return jdbcTemplate.queryForObject(select * from user where id ?,new Object[]{id},new BeanPropertyRowMapper(User.class));}Overridepublic void save(User user) {jdbcTemplate.update(insert into user(username,password) values(?,?),user.getUsername(),user.getPassword());}Overridepublic void update(User user) {jdbcTemplate.update(update user set username?,password? where id? ,user.getUsername(),user.getPassword(),user.getId());}Overridepublic void delete(Integer id) {jdbcTemplate.update(delete from user where id?,id);}
}4、测试
SpringBootTest
class SpringbootApplicationTests {Autowiredprivate UserRepositoryImpl userRepository;Testvoid testJdbc() {List userList userRepository.findAll();System.out.println(userList);}
}query方法
1、 query(String sql, RowMappert rowMapper)/t
其中的RowMapper是一个接口作用是解析结果集将JDBC查询出来的ResultSet对象转化为POJO。
调用query方法时要指定类的结构 new BeanPropertyRowMapper(User.class)
FunctionalInterface
public interface RowMapper {NullableT mapRow(ResultSet rs, int rowNum) throws SQLException;
}2、 queryForObject(String sql, Nullable Object[] args, RowMappert rowMapper)/t
该⽅法⽤来 查询⼀条数据并将结果封装成⼀个POJO
update方法
增加、删除、修改的操作都可以调用个这个方法。
1、pom.xmlspring的web项目
org.springframework.bootspring-boot-starter-parent2.6.7org.springframework.bootspring-boot-starter-webmysqlmysql-connector-javaorg.mybatis.spring.bootmybatis-spring-boot-starter2.2.2
2、application.yml
#端口
server:port: 8080tomcat:uri-encoding: UTF-8
###############################
mybatis:mapper-locations: classpath:/mapping/*.xml # mapper.xml文件的路径type-aliases-package: com.yu.entity # 全限定名包名类名起别名
###############################
spring:datasource:url: jdbc:mysql://127.0.0.1:3306/school?useSSLfalsecharacterEncodingutf8serverTimezoneGMTdriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: 123453、实体类User
4、创建UserRepository接口
public interface UserRepository {public List findAll();public User findById(Integer id);public void save(User user);public void update(User user);public void delete(Integer id);
}5、/resources/mapping创建UserRepository.xml【关注点】
select * from userselect * from user where id#{id}insert into user(username,password) values(#{username},#{password})update user set username#{usernamw},password#{password} where id#{id}delete from user where id#{id}
6、创建Handler
RestController
RequestMapping(/user)
public class UserHandler {Autowiredprivate UserRepository userRepository;GetMapping(/findAll)public List findAll(){return userRepository.findAll();}GetMapping(/findById/{id})public User findById(PathVariable(id) Integer id){return userRepository.findById(id);}PostMapping(/save)public int save(RequestBody User user){return userRepository.save(user);}PutMapping(/update)public int update(RequestBody User user){return userRepository.update(user);}DeleteMapping(/delete/{id})public int delete(PathVariable(id) Integer id){return userRepository.delete(id);}
}7、创建启动类扫描mapper
SpringBootApplication
MapperScan(com.yu.repository) #扫描mapper
public class SpringbootApplication {public static void main(String[] args) {SpringApplication.run(SpringbootApplication.class, args);}
}总结 1、注意application配置文件中需要配置mybatis的mapper文件路径以及别名。 2、在resources的mapping文件夹下创建对应的Mapper.xml文件sql语句还有命名空间 3、启动类添加注解 MapperScan(“com.yu.repository”) 。作用是指定要变成实现类的接口所在的包然后包下面的所有接口在编译之后都会生成相应的实现类。
JPA和Spring Data JPA的关系
JPAjava persistence APIjava持久层规范。定义了一系列ORM接口它本身不能直接使用接口必须实现才能使用Hibernate框架就是一个实现了JPA规范的框架。
Spring Data JPA是Spring框架提供的对JPA规范的抽象通过约定的命名规范完成持久层接口的编写 在不需要实现接口的情况下就可以完成对数据库的操作。
简单理解通过Spring Data JPA只需要定义接口而不需要实现就能完成CRUD的操作。
Spring Data JPA本身并不是⼀个具体的实现它只是⼀个抽象层底层还是需要Hibernate这样的JPA来提供⽀持。 Hibernate 是一款全自动的 ORM 框架它能够自动生成的 SQL 语句并自动执行实现对数据库进行操作
Spring Data JPA和Spring JdbcTemplate的关系
Spring JdbcTemplate是Spring框架提供的⼀套操作数据库的模版 Spring Data JPA是JPA的抽象。
1、pom.xml
!-- Spring Boot 集成 Spring Data JPA --
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-jpa/artifactId
/dependency
2、application.yml
#端口
server:port: 8080tomcat:uri-encoding: UTF-8spring:datasource:url: jdbc:mysql://127.0.0.1:3306/school?useSSLfalsecharacterEncodingutf8serverTimezoneGMTdriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: 12345# 显示sql语句并格式化 jpa: show-sql: trueproperties:hibernate:format_sql: true
3、实体类。完成实体类与数据表的映射【重点】
import javax.persistence.*;
Data
Entity(name user)//将类与表名联系起来name为表名
public class User {IdGeneratedValue(strategy GenerationType.IDENTITY)private Integer id;Columnprivate String username;Columnprivate String password;
}注解分析
Entity将实体类与数据表进行映射其中name user指定表名Id将实体类中的成员变量与数据表的主键进行映射⼀般都是idGeneratedValue表示自动生成主键strategy为主键选择生成策略GenerationType.IDENTITY主键由数据库自动生成主要是自动增长型Column将实体类中的成员变量与数据表的普通字段进行映射
4、创建UserRepository
只需要继承JpaRepository不需要实现方法也不需要写SQL语句。
import org.springframework.data.jpa.repository.JpaRepository;public interface UserRepository extends JpaRepository {
} // 其中JpaRepository一个指实体类另一个是表的主键的类型5、创建Handler
RestController
RequestMapping(/user)
public class UserHandler {Autowiredprivate UserRepository userRepository;GetMapping(/findAll)public List findAll(){return userRepository.findAll();}GetMapping(/findById/{id})public User findById(PathVariable(id) Integer id){return userRepository.findById(id).get(); // Optional findById(ID id);防止空指针}PostMapping(/save)public void save(RequestBody User user){userRepository.save(user);}PutMapping(/update)public void update(RequestBody User user){userRepository.save(user);}DeleteMapping(/deleteById/{id})public void deleteById(PathVariable(id) Integer id){userRepository.deleteById(id);}
}6、【重点】在继承JpaRepsitory的基础上开发者也可以自定义方法。
public interface UserRepository extends JpaRepository {// 这个自定义的方法要特别注意// By后面的为字段名的首字母大写。不能写其他的例如findByName则报错public User findByUsername(String username);
}GetMapping(/findByUsername/{username})
public User findByUsername(PathVariable(username) String username){return userRepository.findByUsername(username);
}Spring Security利用Spring IoC/DI和AOP功能为系统提供了声明式安全访问控制功能减少了为系统安全而编写大量重复代码的工作。
整合Spring Security
1、创建spring的Maven⼯程pom.xml
spring-boot-starter-parent 这是Spring Boot的父级依赖这样当前的项目就是Spring Boot项目了。 spring-boot-starter-parent 是一个特殊的starter它用来提供相关的Maven默认依赖。使用它之后常用的包依赖可以省去version标签。
parentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion2.3.4.RELEASE/version
/parentdependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-security/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-thymeleaf/artifactId/dependency
/dependencies
2、Handler
Controller
public class SecurityHandler {GetMapping(/index)public String index(){return index;}
}3、前端thymeleaf的html
form methodpost action/logoutinput typesubmit value退出
/form
4、application.yml
spring:thymeleaf:prefix: classpath:/templates/suffix: .html5、Application
SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class,args);}
}
自定义用户密码(默认登录页面)
spring:thymeleaf:prefix: classpath:/templates/suffix: .htmlsecurity:user:name: adminpassword: 12345
权限管理
用户----角色----权限将权限交给角色再把角色赋予用户。
举例 定义两个资源index.html、admin.html 定义两个角色ADMIN可以访问index.html和admin.html、USER只能访问index.html
1、config包下面创建SecurityConfig类
Configuration // 配置类
EnableWebSecurity // 开启web安全验证
public class SecurityConfig extends WebSecurityConfigurerAdapter {/*** 角色和资源的关系* param http* throws Exception*/Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers(/admin).hasRole(ADMIN).antMatchers(/index).access(hasRole(ADMIN) or hasRole(USER)).anyRequest().authenticated().and().formLogin().loginPage(/login).permitAll().and().logout().permitAll().and().csrf().disable();}/*** 用户和角色的关系* param auth* throws Exception*/Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser(user).password(new MyPasswordEncoder().encode(000)).roles(USER).and().withUser(admin).password(new MyPasswordEncoder().encode(123)).roles(ADMIN,USER);}
}
2、自定义MyPassowrdEncoder
public class MyPasswordEncoder implements PasswordEncoder {Overridepublic String encode(CharSequence charSequence) {return charSequence.toString();}Overridepublic boolean matches(CharSequence charSequence, String s) {return s.equals(charSequence.toString());}
}
3、Handler
Controller
public class SecurityHandler {GetMapping(/index)public String index(){return index;}GetMapping(/admin)public String admin(){return admin; //转发到admin页面}GetMapping(/login)public String login(){return login;}
}
4、login.html
html xmlns:thhttp://www.thymeleaf.org
body!-- spring security的param.error --p th:if${param.error}用户名或密码错误/pform th:action{/login} methodpost!-- 这里的name必须是username --用户名input typetext nameusernamebr/密 码input typepassword namepasswordbr/input typesubmit value登录/form
/body
5、index.htmlUSER、ADMIN
bodyp欢迎回来/pform methodpost action/logoutinput typesubmit value退出/form
/body
6、admin.htmlADMIN
bodyp后台管理系统/pform methodpost action/logoutinput typesubmit value退出/form
/body