SpringBoot
一、快速入门
1.1 创建项目
1.左上文件==新建==项目==左侧选择Maven Archetype==输入项目名HelloWorld,位置~\IdeaProjects
2.选择maven-archetype-webapp==点开高级设置==鼠标往下拉==组ID输入com.tys和版本号1.0==点击创建
3.对着src文件==右键新建==目录==全选==回车
1.2 引入依赖
//pom.xml 复制进去,刷新Maven
<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.0modelVersion>
<groupId>com.tysgroupId>
<artifactId>HelloWorldartifactId>
<version>1.0version>
<packaging>jarpackaging>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
properties>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.3.4.RELEASEversion>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-configuration-processorartifactId>
<optional>trueoptional>
dependency>
dependencies>
project>
1.3 编写业务
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 创建主程序
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);
}
}
二、底层注解
2.1 @Configuration
1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
2、配置类本身也是组件
3、proxyBeanMethods:代理bean的方法,有两种
Full模式(proxyBeanMethods = true)(默认值,每个@Bean方法被调用多少次返回的组件都是单实例的)
Lite模式(proxyBeanMethods = false)(每个@Bean方法被调用多少次返回的组件都是新创建的)
@Configuration(proxyBeanMethods = false)
public class MyConfig {
@Bean
public User user01(){
User zhangsan = new User("zhangsan", 18);
zhangsan.setPet(tomcatPet());
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
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(name = "tom")
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
<?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>
=======================================================================================
@ImportResource("classpath:beans.xml")
public class MyConfig {
...
}
2.5 @ConfigurationProperties
mycar.brand=BYD
mycar.price=100000
=======================================================================================
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
Car的实体类
}
三、web开发
3.1 静态资源
spring:
mvc:
static-path-pattern: /static/**
resources:
static-locations: [classpath:/static/]
=======================================================================================
spring:
resources:
static-locations: [classpath:/static/]
=======================================================================================
spring:
resources:
static-locations: [classpath:/static/]
3.2 Restful风格
spring:
mvc:
hiddenmethod:
filter:
enabled: true
<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>
@GetMapping("/user")
public String getUser(){
return "GET-张三";
}
@PostMapping("/user")
public String saveUser(){
return "POST-张三";
}
@PutMapping("/user")
public String putUser(){
return "PUT-张三";
}
@DeleteMapping("/user")
public String deleteUser(){
return "DELETE-张三";
}
3.3 获取request域中的值
@Controller
public class RequestController {
@GetMapping("/goto")
public String goToPage(HttpServletRequest request){
request.setAttribute("msg","成功了...");
request.setAttribute("code",200);
return "forward:/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 自定义类型转换器
@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 拦截器
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);
}
}
@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="@{/upload}" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputEmail1">邮箱