Springboot是一个快速开发框架,可以迅速搭建出一套基于Spring框架体系的应用,是SpringCloud的基础。 Springboot开启了各种自动装配,简化代码开发,不需要编写各种配置文件,只需要引入相关的依赖,就可迅速搭建一个应用。
特点 1、不需要web.xml 2、不需要springmvc.xml 3、内嵌tomcat 4、不需要配置JSON解析,支持REST架构 5、个性化配置简单
如何使用 1、创建maven工程,导入相关依赖。
<parent> <artifactId>spring-boot-starter-parent</artifactId> <groupId>org.springframework.boot</groupId> <version>2.3.1.RELEASE</version> </parent> <dependencies> <!-- web启动jar包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- lombok依赖 若爆红请更新maven--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.6</version> <scope>provided</scope> </dependency> </dependencies>如果导入依赖maven出现红线,请点一下更新maven。
2、创建Student实体类
package com.southwind.entity; import lombok.Data; @Data public class Student { private long id; private String name; private int age; }3、StudentRepository
-------------------接口------------------------- package com.southwind.repository; import com.southwind.entity.Student; import java.util.Collection; import java.util.List; public interface StudentRepository { public Collection<Student> findAll(); public Student findById(long id); public void saveOrUpdate(Student student); public void deleteById(long id); }4、StudentRepositoryImpl
-----------------------------------实现接口的类 package com.southwind.repository.impl; import com.southwind.entity.Student; import com.southwind.repository.StudentRepository; import org.springframework.stereotype.Repository; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; @Repository public class StudentRepositoryImpl implements StudentRepository { private static Map<Long,Student> studentMap; static { studentMap = new HashMap<>(); studentMap.put(1L,new Student(1L,"张三",21)); studentMap.put(2L,new Student(2L,"李四",22)); studentMap.put(3L,new Student(3L,"王五",22)); } @Override public Collection<Student> findAll() { return studentMap.values(); } @Override public Student findById(long id) { return studentMap.get(id); } @Override public void saveOrUpdate(Student student) { studentMap.put(student.getId(),student); } @Override public void deleteById(long id) { studentMap.remove(id); } }5、StudentHandller
package com.southwind.controller; import com.southwind.entity.Student; import com.southwind.repository.StudentRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Collection; @RestController @RequestMapping("/student")//映射请求 public class StudentHandler { @Autowired private StudentRepository studentRepository; @GetMapping("/findAll") public Collection<Student> findAll(){ return studentRepository.findAll(); } @GetMapping("/findById/{id}") public Student findById(@PathVariable("id") long id){ return studentRepository.findById(id); } @PostMapping("/save") public void save(@RequestBody Student student){ studentRepository.saveOrUpdate(student); } @PutMapping("/update") public void update(@RequestBody Student student){ studentRepository.saveOrUpdate(student); } @DeleteMapping("/deleteById/{id}") public void deleteById(@PathVariable("id") long id){ studentRepository.deleteById(id); } }6、application.yml 配置文件(放在resource内)
server: port: 90907、Application启动类 @SpringbootApplication表示当前类是Springboot的入口,Application类的存放位置必须是其他相关业务类存放位置的父级(级别要高)
新建空maven工程
pom.xml 添加依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.7.RELEASE</version> </parent> <dependencies> <!-- web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 整合JSP --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <!-- JSTL --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.6</version> <scope>provided</scope> </dependency> </dependencies> 创建配置文件 application.yml server: port: 8080 spring: mvc: view: # 设置前缀后缀 prefix: / suffix: .jsp 创建 Handler package com.southwind.controller; import com.southwind.entity.Student; import com.southwind.repository.StudentRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/hello") public class HelloHandler { @Autowired private StudentRepository studentRepository; @GetMapping("/index") public ModelAndView index(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("index"); modelAndView.addObject("list",studentRepository.findAll()); return modelAndView; } @GetMapping("/deleteById/{id}") public String deleteById(@PathVariable("id") long id){ studentRepository.deleteById(id); return "redirect:/hello/index"; } @PostMapping("/save") public String save(Student student){ studentRepository.saveOrUpdate(student); return "redirect:/hello/index"; } @PostMapping("/update") public String update(Student student){ studentRepository.saveOrUpdate(student); return "redirect:/hello/index"; } @GetMapping("/findById/{id}") public ModelAndView findById(@PathVariable("id") long id){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("update"); modelAndView.addObject("student",studentRepository.findById(id)); return modelAndView; } } JSP <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page isELIgnored="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <h1>学生信息</h1> <table> <tr> <th>学生编号</th> <th>学生姓名</th> <th>学生年龄</th> <th>操作</th> </tr> <c:forEach items="${list}" var="student"> <tr> <td>${student.id}</td> <td>${student.name}</td> <td>${student.age}</td> <td> <a href="/hello/findById/${student.id}">修改</a> <a href="/hello/deleteById/${student.id}">删除</a> </td> </tr> </c:forEach> </table> <a href="/save.jsp">添加学生</a> </body> </html> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="/hello/save" method="post"> ID:<input type="text" name="id"/><br/> name:<input type="text" name="name"/><br/> age:<input type="text" name="age"/><br/> <input type="submit" value="提交"/> </form> </body> </html> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="/hello/update" method="post"> ID:<input type="text" name="id" value="${student.id}" readonly/><br/> name:<input type="text" name="name" value="${student.name}"/><br/> age:<input type="text" name="age" value="${student.age}"/><br/> <input type="submit" value="提交"/> </form> </body> </html>Spring Boot 可以结合 Thymeleaf 模版来整合 HTML,使用原生的 HTML 作为视图。
Thymeleaf 模版是面向 Web 和独立环境的 Java 模版引擎,能够处理 HTML、XML、JavaScript、CSS 等。
<p th:text="${message}"></p> pom.xml <!-- 继承父包 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.7.RELEASE</version> </parent> <dependencies> <!-- web启动jar --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.6</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> appliction.yml server: port: 8080 spring: thymeleaf: prefix: classpath:/templates/ suffix: .html mode: HTML5 encoding: UTF-8 Handler package com.southwind.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/index") public class IndexHandler { @GetMapping("/index") public String index(){ System.out.println("index..."); return "index"; } } HTML <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Hello World</h1> </body> </html>如果希望客户端可以直接访问 HTML 资源,将这些资源放置在 static 路径下即可,否则必须通过 Handler 的后台映射才可以访问静态资源。
导入 Thymeleaf 标签 <html lang="en" xmlns:th="http://www.thymeleaf.org">
赋值、拼接 @GetMapping("/index2") public String index2(Map<String,String> map){ map.put("name","张三"); return "index"; } <p th:text="${name}"></p> <p th:text="'学生姓名是'+${name}+2"></p> <p th:text="|学生姓名是,${name}|"></p> 条件判断:if/unlessth:if 表示条件成立时显示内容,th:unless 表示条件不成立时显示内容
@GetMapping("/if") public String index3(Map<String,Boolean> map){ map.put("flag",true); return "index"; } <p th:if="${flag == true}" th:text="if判断成立"></p> <p th:unless="${flag != true}" th:text="unless判断成立"></p> 循环 @GetMapping("/index") public String index(Model model){ System.out.println("index..."); List<Student> list = new ArrayList<>(); list.add(new Student(1L,"张三",22)); list.add(new Student(2L,"李四",23)); list.add(new Student(3L,"王五",24)); model.addAttribute("list",list); return "index"; } <table> <tr> <th>index</th> <th>count</th> <th>学生ID</th> <th>学生姓名</th> <th>学生年龄</th> </tr> <tr th:each="student,stat:${list}" th:style="'background-color:'+@{${stat.odd}?'#F2F2F2'}"> <td th:text="${stat.index}"></td> <td th:text="${stat.count}"></td> <td th:text="${student.id}"></td> <td th:text="${student.name}"></td> <td th:text="${student.age}"></td> </tr> </table>stat 是状态变量,属性:
index 集合中元素的index(从0开始)
count 集合中元素的count(从1开始)
size 集合的大小
current 当前迭代变量
even/odd 当前迭代是否为偶数/奇数(从0开始计算)
first 当前迭代的元素是否是第一个
last 当前迭代的元素是否是最后一个
URL
Thymeleaf 对于 URL 的处理是通过 @{...} 进行处理,结合 th:href 、th:src
<h1>Hello World</h1> <a th:href="@{http://www.baidu.com}">跳转</a> <a th:href="@{http://localhost:9090/index/url/{na}(na=${name})}">跳转2</a> <img th:src="${src}"> <div th:style="'background:url('+ @{${src}} +');'"> <br/> <br/> <br/> </div> 三元运算 @GetMapping("/eq") public String eq(Model model){ model.addAttribute("age",30); return "test"; } <input th:value="${age gt 30?'中年':'青年'}"/>gt great than 大于
ge great equal 大于等于
eq equal 等于
lt less than 小于
le less equal 小于等于
ne not equal 不等于
switch
@GetMapping("/switch") public String switchTest(Model model){ model.addAttribute("gender","女"); return "test"; } <div th:switch="${gender}"> <p th:case="女">女</p> <p th:case="男">男</p> <p th:case="*">未知</p> </div> 基本对象 #ctx :上下文对象#vars:上下文变量#locale:区域对象#request:HttpServletRequest 对象#response:HttpServletResponse 对象#session:HttpSession 对象#servletContext:ServletContext 对象 @GetMapping("/object") public String object(HttpServletRequest request){ request.setAttribute("request","request对象"); request.getSession().setAttribute("session","session对象"); return "test"; } <p th:text="${#request.getAttribute('request')}"></p> <p th:text="${#session.getAttribute('session')}"></p> <p th:text="${#locale.country}"></p> 内嵌对象工具类,可以对从后端传来的数据进行进一步处理
可以直接通过 # 访问。
1、dates:java.util.Date 的功能方法
2、calendars:java.util.Calendar 的功能方法
3、numbers:格式化数字
4、strings:java.lang.String 的功能方法
5、objects:Object 的功能方法
6、bools:对布尔求值的方法
7、arrays:操作数组的功能方法
8、lists:操作集合的功能方法
9、sets:操作集合的功能方法
10、maps:操作集合的功能方法
@GetMapping("/util") public String util(Model model){ model.addAttribute("name","zhangsan"); model.addAttribute("users",new ArrayList<>()); model.addAttribute("count",22); model.addAttribute("date",new Date()); return "test"; } <!-- 格式化时间 --> <p th:text="${#dates.format(date,'yyyy-MM-dd HH:mm:sss')}"></p> <!-- 创建当前时间,精确到天 --> <p th:text="${#dates.createToday()}"></p> <!-- 创建当前时间,精确到秒 --> <p th:text="${#dates.createNow()}"></p> <!-- 判断是否为空 --> <p th:text="${#strings.isEmpty(name)}"></p> <!-- 判断List是否为空 --> <p th:text="${#lists.isEmpty(users)}"></p> <!-- 输出字符串长度 --> <p th:text="${#strings.length(name)}"></p> <!-- 拼接字符串 --> <p th:text="${#strings.concat(name,name,name)}"></p> <!-- 创建自定义字符串 --> <p th:text="${#strings.randomAlphanumeric(count)}"></p>https://blog.csdn.net/PANDORA_A/article/details/107349787
SpringSecurity是一个安全框架,其核心功能包括认证,授权和攻击防护
创建空的maven工程 1、pom.xml添加依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-parent</artifactId> <version>2.3.1.RELEASE</version> </parent> <dependencies> <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>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> </dependencies>权限管理demo:有两个html资源,index和admin。定义两个角色ADMIN和USER。ADMIN权限高,可以访问index和admin两个html文件,而USER只能访问index.html。
2、创建html login.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form th:action="@{/login}" method="post"> 用户名:<input type="text" name="username"><br/> 密码:<input type="text" name="password"><br/> <input type="submit" value="登陆"> </form> </body> </html>index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>hello world</h1> <form action="/logout" method="post"> <input type="submit" value="退出"> </form> </body> </html>admin.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>后台管理系统</h1> <form action="/logout" method="post"> <input type="submit" value="退出" > </form> </body> </html>3、创建handler
package com.southwind.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @Controller public class HelloHandler { @GetMapping("/index") public String index(){ return "index"; } @GetMapping("/admin") public String admin(){ return "admin"; } @GetMapping("/login") public String login(){ return "login"; } }4、创建application.yml 设置自定义密码
spring: thymeleaf: prefix: classpath:/templates/ suffix: .html security: user: name: admin password: 12345、创建启动类application
package com.southwind; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }6、创建SecurityConfig类
package com.southwind.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; // 声明为配置类 @Configuration //让websecurity生效 @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()) //设置用户名-密码-添加角色(USER) .withUser("user").password(new MyPasswordEncoder().encode("1234")).roles("USER") .and() //设置第二个用户名-密码-设置两个角色(权限更高) .withUser("admin").password(new MyPasswordEncoder().encode("0000")).roles("USER","ADMIN"); } @Override protected 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(); } }7、在config包(SecurityConfig所在包)下创建MyPasswordEncoder类
package com.southwind.config; import org.springframework.security.crypto.password.PasswordEncoder; public class MyPasswordEncoder implements PasswordEncoder { @Override public String encode(CharSequence charSequence) { return charSequence.toString(); } @Override public boolean matches(CharSequence charSequence, String s) { return s.equals(charSequence.toString()); } }