SpringBoot
一、快速入门
1.1 创建项目
1.左上文件==新建==项目==左侧选择Maven Archetype==输入项目名HelloWorld,位置~\IdeaProjects 2.选择maven-archetype-webapp==点击高级设置==鼠标往下拉==组ID输入com.tys和版本号1.0==点击创建 3.对着src文件==右键新建==目录==全选==回车
1.2 引入依赖
//pom.xml 复制,刷新Maven <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tys</groupId> <artifactId>HelloWorld</artifactId> <version>1.0</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.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-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>
1.3 编写业务
//对着src/main/java==右键新建==软件包==com.tys.boot.controller
//对着com.tys.boot.controller==右键新建==Java类==HelloController
package com.tys.boot.controller;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
@Controller
@ResponseBody
public class HelloController {
@RequestMapping("/hello")
public String handle01(){
return "Hello, Spring Boot 2!";
}
}
1.4 创建主程序
//对着src/main/java==右键新建==Java类==com.tys.boot.MainApplication
package com.tys.boot;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
//点击第7行的小箭头,控制台出现多少秒,打开浏览器
//访问:localhost:8080/hello 看见网页出现 Hello, Spring Boot 2! 代表成功
二、底层注解
2.1 @Configuration
1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
2、配置类本身也是组件
3、proxyBeanMethods:代理bean的方法,有两种
Full模式(proxyBeanMethods = true)(默认值,每个@Bean方法被调用多少次返回的组件都是单实例的)
Lite模式(proxyBeanMethods = false)(每个@Bean方法被调用多少次返回的组件都是新创建的)
//告诉SpringBoot这是一个配置类 == 配置文件
@Configuration(proxyBeanMethods = false)
public class MyConfig {
//给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型
@Bean
public User user01(){
User zhangsan = new User("zhangsan", 18);
zhangsan.setPet(tomcatPet()); //user组件依赖了Pet组件
return zhangsan;
}
@Bean("tom")
public Pet tomcatPet(){
return new Pet("tomcat");
}
}
2.2 @Import
//给容器中自动创建出这两个类型的组件,默认组件的名字就是全限定名
@Import({
User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false)
public class MyConfig {
}
2.3 @Conditional
//@Conditional是条件装配:满足指定的条件,则进行组件注入
//以@ConditionalOnMissingBean进行举例说明
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(name = "tom")//没有tom名字的Bean时,MyConfig类的Bean才能生效。
public class MyConfig {
@Bean
public User user01(){
User zhangsan = new User("zhangsan", 18);
zhangsan.setPet(tomcatPet());
return zhangsan;
}
@Bean("tom22")
public Pet tomcatPet(){
return new Pet("tomcat");
}
}
2.4 @ImportResource
//beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans ...">
<bean id="haha" class="com.lun.boot.bean.User">
<property name="name" value="zhangsan"></property>
<property name="age" value="18"></property>
</bean>
<bean id="hehe" class="com.lun.boot.bean.Pet">
<property name="name" value="tomcat"></property>
</bean>
</beans>
======================================================================================= //比如公司使用bean.xml文件生成配置bean,而非注解@bean
//使用@ImportResource导入配置文件
@ImportResource("classpath:beans.xml")
public class MyConfig {
...
}
2.5 @ConfigurationProperties
//配置文件application.properties
mycar.brand=BYD
mycar.price=100000
======================================================================================= //配置绑定 如何使用Java读取到properties文件中的内容,并且把它封装到JavaBean中
//只有在容器中的组件,才会拥有SpringBoot提供的强大功能,所以需要@Component
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
Car的实体类
}
三、web开发
3.1 静态资源
# 对着/src/main/resources==右键新建==目录==static 在这放一张图片01.png
# 对着/src/main/resources==右键新建==文件==application.yaml
# /*表示拦截当前目录,/**表示拦截所有文件包括子文件夹里的
# 前两行表示访问路径是以static开头,localhost:8080/static/xx.png
# 后两行表示告诉spring,静态资源在项目的static文件夹下
spring:
mvc:
static-path-pattern: /static/**
resources:
static-locations: [classpath:/static/]
# 浏览器访问:localhost:8080/static/01.png
=======================================================================================
# 欢迎页
# 在/src/main/resources/static路径下,新建index.html,也可以在controller层指定
spring:
# mvc:
# static-path-pattern: /static/** 有了url前缀,会导致欢迎页功能失效
resources:
static-locations: [classpath:/static/]
#访问:localhost:8080 会自动打开index.html
=======================================================================================
# Favicon图标
# 在/src/main/resources/static路径下,放入favicon.ico
spring:
# mvc:
# static-path-pattern: /static/** 有了url前缀,会导致小图标功能失效
resources:
static-locations: [classpath:/static/]
#访问:localhost:8080
3.2 Restful风格
spring:
mvc:
hiddenmethod:
filter:
enabled: true #开启网页表单的Restful功能
<form action="/user" method="get">
<input value="GET提交" type="submit" />
</form>
<form action="/user" method="post">
<input value="POST提交" type="submit" />
</form>
<form action="/user" method="post">
<input name="_method" type="hidden" value="DELETE"/>
<input value="DELETE 提交" type="submit"/>
</form>
<form action="/user" method="post">
<input name="_method" type="hidden" value="PUT" />
<input value="PUT提交"type="submit" />
<form>
//springboot出了新注解,其实两种注解方式功能实现一样的
@GetMapping("/user")
//@RequestMapping(value = "/user",method = RequestMethod.GET)
public String getUser(){
return "GET-张三";
}
@PostMapping("/user")
//@RequestMapping(value = "/user",method = RequestMethod.POST)
public String saveUser(){
return "POST-张三";
}
@PutMapping("/user")
//@RequestMapping(value = "/user",method = RequestMethod.PUT)
public String putUser(){
return "PUT-张三";
}
@DeleteMapping("/user")
//@RequestMapping(value = "/user",method = RequestMethod.DELETE)
public String deleteUser(){
return "DELETE-张三";
}
3.3 获取request域中的值
//此注解@RequestAttribute,获取request域中的值
@Controller
public class RequestController {
@GetMapping("/goto")
public String goToPage(HttpServletRequest request){
request.setAttribute("msg","成功了...");
request.setAttribute("code",200);
return "forward:/success"; //转发到success页面
}
@ResponseBody
@GetMapping("/success")
public Map success(@RequestAttribute(value = "msg",required = false) String msg,
@RequestAttribute(value = "code",required = false) Integer code){
Map<String,Object> map = new HashMap<String,Object>();
map.put("msg",msg);
map.put("code",code);
return map;
}
}
3.4 自定义类型转换器
//Pet实体类,以前传name="啊猫" age=3
//现在直接逗号分割,直接传"啊猫,3"
@Bean
public WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new Converter<String, Pet>() {
@Override
public Pet convert(String source) {
if(!StringUtils.isEmpty(source)){
Pet pet = new Pet();
String[] split = source.split(",");
pet.setName(split[0]);
pet.setAge(Integer.parseInt(split[1]));
return pet;
}
return null;
}
});
}
};
}
3.5 拦截器
//编写一个拦截器实现登录检查,没有账号登录,直接输入网址,进不了后台管理页面
//对着src/main/java==右键新建==软件包==com.tys.boot.interceptor
//对着com.tys.boot.interceptor==右键新建==Java类==LoginInterceptor
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURI = request.getRequestURI();
HttpSession session = request.getSession();
Object loginUser = session.getAttribute("loginUser");
if(loginUser != null){
return true;
}
request.setAttribute("msg","请先登录");
request.getRequestDispatcher("/").forward(request,response);
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("postHandle执行{}",modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("afterCompletion执行异常{}",ex);
}
}
//拦截器注册到容器中并且指定拦截规则
//对着src/main/java==右键新建==软件包==com.tys.boot.config
//对着com.tys.boot.config==右键新建==Java类==AdminWebConfig
@Configuration
public class AdminWebConfig implements WebMvcConfigurer{
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())//拦截器注册到容器中
.addPathPatterns("/**") //所有请求都被拦截包括静态资源
.excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**",
"/js/**","/aa/**"); //放行的请求
3.6 文件上传
//页面代码/static/form/form_layouts.html <form role="form" th:action