springboot

简介

​ Spring Boot 是 Spring 家族中的一个全新的框架,它用来简化 Spring 应用程序的创建和开发过程,也可以说 Spring Boot 能简化我们之前采用 SpringMVC + Spring + MyBatis 框架进行开发的过程。

​ 在以往我们采用 SpringMVC + Spring + MyBatis 框架进行开发的时候,搭建和整合三大框架,我们需要做很多工作,比如配置 web.xml,配置 Spring,配置 MyBatis,并将它们整合在一起等,而 Spring Boot 框架对此开发过程进行了革命性的颠覆,完全抛弃了繁琐的 xml 配置过程,采用大量的默认配置简化我们的开发过程。所以采用 Spring Boot 可以非常容易和快速地创建基于 Spring 框架的应用程序,它让编码变简单了,配置变简单了,部署变简单了,监控变简单了。正因为 Spring Boot 它化繁为简,让开发变得极其简单和快速,所以在业界备受关注。

1.特性

➢ 能够快速创建基于 Spring 的应用程序

➢ 能够直接使用 java main 方法启动内嵌的 Tomcat 服务器运行 Spring Boot 程序,不需要部署 war 包文件

➢ 提供约定的 starter POM 来简化 Maven 配置,让 Maven 的配置变得简单

➢ 自动化配置,根据项目的 Maven 依赖配置,Spring boot 自动配置 Spring、Spring mvc等

➢ 提供了程序的健康检查等功能

➢ 基本可以完全不使用 XML 配置文件,采用注解配置

2.四大核心

2.1自动配置

2.2起步依赖

2.3Actuator

健康检测,检测程序运行情况。

2.4命令行界面

入门案例:

1.多环境下核心配置文件的使用,工作中开发的环境有哪些:开发环境,测试环境,准生产环境,生产环境

web.IndexController

@Controller
public class IndexController {@RequestMapping(value = "/say")public @ResponseBody String say(){return "Hello World!";}
}

第一步:建立响应的四个配置文件

第二步:在主核心配置文件里进行配置

#springboot主核心配置文件
#激活使用的配置文件
spring.profiles.active=dev

2.将自定义配置映射到对象

① @Value("${school.name}")

② @ConfigurationProperties(prefix = “school”)

<!--解决使用@ConfigurationProperties 注解出现警告问题-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional>
</dependency>

3.Springboot集成jsp

导入依赖

 <!--引入Springboot内嵌Tomcat对jsp的解析依赖,不添加解析不了jsp--><!--仅仅只是展示jsp页面,只添加一下一个依赖--><dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId></dependency>

导入插件

 <!--springboot项目默认推荐使用的前端引擎是thymeleaf现在我们要使用springboot集成jsp,手动指定jsp最后编译的路径而且springboot集成jsp编译jsp的路径是springboot规定好的位置META-INF/resources--><resources><resource><!--源文件夹--><directory>src/main/webapp</directory><!--指定编译到META-INF/resources--><targetPath>META-INF/resources</targetPath><includes><include>*.*</include></includes></resource></resources>

在application.properties配置视图解析器

#配置视图解析器
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

在IndexController中写程序

@Controller
public class IndexController {@RequestMapping(value = "/say")public ModelAndView say(){ModelAndView mv = new ModelAndView();mv.addObject("message","Hello,SpringBoot");mv.setViewName("say");return mv;}@RequestMapping(value = "/index")public String index(Model model){model.addAttribute("message","HelloWorld");return "say";}
}

在webapp下写say.jsp,并声明webapp为web资源

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>

springboot框架Web开发

springboot集成MyBatis

①添加mybatis依赖,MySQL驱动

        <!--mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!--mybatis整合springboot框架的起步依赖--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.0</version></dependency>

②使用mybatis提供的逆向工程生成实体bean,映射文件,DAO接口

建表


drop table if exists t_student;
create table t_student
(id                   int(10)                        not null auto_increment,name                 varchar(20)                    null,age                  int(10)                        null,constraint PK_T_STUDENT primary key clustered (id)
);insert into t_student(name,age) values("zhangsan",25);
insert into t_student(name,age) values("lisi",28);
insert into t_student(name,age) values("wangwu",23);
insert into t_student(name,age) values("Tom",21);
insert into t_student(name,age) values("Jck",55);
insert into t_student(name,age) values("Lucy",27);
insert into t_student(name,age) values("zhaoliu",75);

③修改GeneratorMapper.xml 配置(根目录下建立)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration><!-- 指定连接数据库的 JDBC 驱动包所在位置,指定到你本机的完整路径 --><classPathEntry location="D:\importantjava\mysql-connector-java-8.0.25.jar"/><!-- 配置 table 表信息内容体,targetRuntime 指定采用 MyBatis3 的版本 --><context id="tables" targetRuntime="MyBatis3"><!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 --><commentGenerator><property name="suppressAllComments" value="true" /></commentGenerator><!-- 配置数据库连接信息 --><jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3306/springboot"userId="root"password="123456"></jdbcConnection><!-- 生成 model 类,targetPackage 指定 model 类的包名, targetProject 指定生成的 model 放在 eclipse 的哪个工程下面--><javaModelGenerator targetPackage="com.allspark.springboot.model"targetProject="src/main/java"><property name="enableSubPackages" value="false" /><property name="trimStrings" value="false" /></javaModelGenerator><!-- 生成 MyBatis 的 Mapper.xml 文件,targetPackage 指定 mapper.xml 文件的包名, targetProject 指定生成的 mapper.xml 放在 eclipse 的哪个工程下面 --><sqlMapGenerator targetPackage="com.allspark.springboot.mapper"targetProject="src/main/java"><property name="enableSubPackages" value="false" /></sqlMapGenerator><!-- 生成 MyBatis 的 Mapper 接口类文件,targetPackage 指定 Mapper 接口类的包名, targetProject 指定生成的 Mapper 接口放在 eclipse 的哪个工程下面 --><javaClientGenerator type="XMLMAPPER"targetPackage="com.allspark.springboot.mapper" targetProject="src/main/java"><property name="enableSubPackages" value="false" /></javaClientGenerator><!-- 数据库表名及对应的 Java 模型类名 --><table tableName="t_student" domainObjectName="Student"enableCountByExample="false"enableUpdateByExample="false"enableDeleteByExample="false"enableSelectByExample="false"selectByExampleQueryId="false"/></context>
</generatorConfiguration>

④在 pom.xml文件中添加 mysql反向工程依赖

<!--mybatis 代码自动生成插件--><plugin><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId><version>1.3.6</version><configuration><!--配置文件的位置--><configurationFile>GeneratorMapper.xml</configurationFile><verbose>true</verbose><overwrite>true</overwrite></configuration></plugin>

⑤手动指定文件夹为resources

<!--手动指定文件夹为resources--><resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource></resources>

或者在resources下建立mapper目录将StudentMapper.xml放进去,再在application.properties中添加配置

#指定MyBatis映射文件的路径
mybatis.mapper-locations=classpath:mapper/*.xml

⑥StudentController

@Controller
public class StudentController {@Autowiredprivate StudentService studentService;@RequestMapping(value = "/student")public @ResponseBody Object student(Integer id){Student student=studentService.queryStudentById(id);return student;}
}

⑦service

public interface StudentService {/*** 根据学生id查询学生* @param id* @return*/Student queryStudentById(Integer id);
}
@Service
public class StudentServiceImpl implements StudentService {@Autowiredprivate StudentMapper studentMapper;@Overridepublic Student queryStudentById(Integer id) {return studentMapper.selectByPrimaryKey(id);}
}

⑧启动类上加注解@MapperScan

@SpringBootApplication  //开启spring的注解
@MapperScan(basePackages = "com.allspark.springboot.mapper") //开启扫描mapper接口的包以及子目录
public class SpringbootMybatis3014Application {public static void main(String[] args) {SpringApplication.run(SpringbootMybatis3014Application.class, args);}}

⑨核心配置文件指定四个要素

#设置连接数据库的配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456

小结:

SpringBoot集成MyBatis,最主要的是两个注解,@Mapper,@MapperScan

@Mapper:需要在每一个Mapper接口类上添加,作用扫描dao接口

@MapperScan:是在SpringBoot启动入口类上添加的,它是扫描所有的包

关于Mapper映射文件存放的位置的写法有以下两种:

1.将Mapper接口和Mapper映射文件存放到src/main/java同一目录下,还需要在pom文件中手动指定资源文件夹路径resources

2.将Mapper接口和Mapper映射文件分开存放

​ Mapper接口类存放到src/main/java同一目录下

​ Mapper映射文件存放到resources(类路径)

​ 在springboot核心配置文件中指定mapper映射文件存放的位置

SpringBoot项目下使用事务

​ 事务是一个完整的功能,也叫做是一个完整的业务

​ 事务只跟什么SQL语句有关系?事务只跟DML语句有关系:增删改

​ DML,DQL,DDL,TCL,DCL

在方法上加@Transactional

@Service
public class StudentServiceImpl implements StudentService {@Autowiredprivate StudentMapper studentMapper;@Transactional@Overridepublic int updateStudentById(Student student) {int i = studentMapper.updateByPrimaryKeySelective(student);int a = 10/0;return i;}
}

springmvc常用注解

//@Controller
@RestController //相当于控制层类上加@Controller+方法上加+ResponseBody,// 意味着当前控制层所有方法返回的对象都是json对象
public class StudentController {@RequestMapping(value = "/student")//@ResponseBodypublic  Object student(){Student student = new Student();student.setId(1001);student.setName("zhangsan");return student;}//该方法请求方式支持GET和POST请求@RequestMapping(value = "/queryStudentById",method = {RequestMethod.GET,RequestMethod.POST})public Object queryStudentById(Integer id){Student student = new Student();student.setId(id);return student;}//该方法请求方式支持GET和POST请求//@RequestMapping(value = "/queryStudentById2",method = RequestMethod.GET)@GetMapping(value = "/queryStudentById2")//相当于上一句话,只接收GET请求,如果请求方式不对会报405错误//该注解通常在查询数据的时候使用public Object queryStudentById2(Integer id){return "Only Get Method";}//@RequestMapping(value = "/insert",method = RequestMethod.POST)@PostMapping(value = "/insert") //相当于上一句话//该注解通常在新增数据的时候使用 -> 新增public Object insert(){return "Insert success";}//@RequestMapping(value = "/delete",method = RequestMethod.DELETE)@DeleteMapping(value = "/delete")//相当于上一句话//该注解通常在删除数据的时候使用 -> 删除public Object delete(){return "delete Student";}//@RequestMapping(value = "/update",method = RequestMethod.PUT)@PutMapping(value = "/update") //相当于上一句话//该注解通常在修改数据的时候使用 -> 更新public Object update(){return "update student info";}
}

使用RESTful

REST(英文:Representational State Transfer,简称 REST)

一种互联网软件架构设计的风格,但它并不是标准,它只是提出了一组客户端和服务器交互时的架构理念和设计原则,基于这种理念和原则设计的接口可以更简洁,更有层次,REST这个词,是 Roy Thomas Fielding 在他 2000 年的博士论文中提出的。

任何的技术都可以实现这种理念,如果一个架构符合 REST 原则,就称它为 RESTFul 架构

比如我们要访问一个 http 接口:http://localhost:8080/boot/order?id=1021&status=1

采用 RESTFul 风格则 http 地址为:http://localhost:8080/boot/order/1021/1

@RestController
public class StudentController {@RequestMapping(value = "/student")public Object student(Integer id,Integer age){Student student = new Student();student.setId(id);student.setAge(age);return student;}//@RequestMapping(value = "/student/detail/{id}/{age}")@GetMapping(value = "/student/detail/{id}/{age}")public Object student1(@PathVariable("id") Integer id,@PathVariable("age") Integer age){Map<String,Object> retMap = new HashMap<>();retMap.put("id",id);retMap.put("age",age);return retMap;}//@RequestMapping(value = "/student/detail/{id}/{status}")@DeleteMapping(value = "/student/detail/{id}/{status}")public Object student2(@PathVariable("id") Integer id,@PathVariable("status") Integer status){Map<String,Object> retMap = new HashMap<>();retMap.put("id",id);retMap.put("status",status);return retMap;}//以上代码student1和student2会出现请求路径冲突的问题//通常在RESTful风格中方法的请求方式会按增删改查的请求方式来区分//修改请求路径//RESTful请求风格要求路径中使用的单词都是名词,最好不要出现动词@DeleteMapping(value = "/student/{id}/detail/{status}")public Object student3(@PathVariable("id") Integer id,@PathVariable("city") Integer city){Map<String,Object> retMap = new HashMap<>();retMap.put("id",id);retMap.put("city",city);return retMap;}@PostMapping(value = "/student/{id}")public String addStudent(@PathVariable("id") Integer id){return "add student ID:"+id;}@PutMapping(value = "/student/{id}")public String updateStudent(@PathVariable("id") Integer id){return "update student ID:"+id;}}

springboot创建非web工程

第一种方式(了解)

直接获取ConfigurableApplicationContext

@SpringBootApplication
public class Springboot026Java1Application {public static void main(String[] args) {/*** Springboot程序启动后,返回值是ConfigurableApplicationContext,它也是Spring容器* 它起始相当于原来Spring容器中启动容器ClasspathXmlApplicationContext*///获取springboot容器ConfigurableApplicationContext applicationContext=SpringApplication.run(Springboot026Java1Application.class, args);//从spring容器中获取指定bean对象StudentService studentService = (StudentService) applicationContext.getBean("studentServiceImpl");//调用业务方法String sayHello = studentService.sayHello();System.out.println(sayHello);}}

第二种方式(了解)

实现CommandLineRunner,重写run方法

@SpringBootApplication
public class Springboot027Java2Application implements CommandLineRunner {@Autowiredprivate StudentService studentService;public static void main(String[] args) {//SpringBoot启动程序,会初始化Spring容器SpringApplication.run(Springboot027Java2Application.class, args);}//重写CommandLineRunner类中的run方法@Overridepublic void run(String... args) throws Exception {//调用业务方法String sayHello = studentService.sayHello("World");System.out.println(sayHello);}
}

关闭springboot工程的启动Logo(了解)

@SpringBootApplication
public class Springboot028CloseLogoApplication {public static void main(String[] args) {//获取入口SpringBoot类SpringApplication springApplication = new SpringApplication(Springboot028CloseLogoApplication.class);//设置它的属性springApplication.setBannerMode(Banner.Mode.OFF);springApplication.run(args);}
}

修改启动Logo(了解)

在 src/main/resources 放入 banner.txt 文件,该文件名字不能随意,文件中的内容就是要输出

的 logo ;可以利用网站生成图标: https://www.bootschool.net/ascii 或者http://patorjk.com/software/taag/,

将生成好的图标文字粘贴到 banner.txt 文件中,然后将关闭 logo 输出的语句注释,启动看效果

修改后 LOGO

        _ _                      _    | | |                    | |   __ _| | |___ _ __   __ _ _ __| | __/ _` | | / __| '_ \ / _` | '__| |/ /| (_| | | \__ \ |_) | (_| | |  |   < \__,_|_|_|___/ .__/ \__,_|_|  |_|\_\| |                    |_|

springboot使用拦截器

​ a.定义一个拦截器,实现HandlerInterceptor接口

​ UserInterceptor

public class UserInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("进入拦截器--------------------");//编写业务拦截的规则//从session中获取用户的信息User user=(User) request.getSession().getAttribute("user");//判断用户是否登录if (null==user){//未登录response.sendRedirect(request.getContextPath()+"/user/error");}return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}
}

​ b.创建一个配置类(即在SpringMvc配置文件中使用mvc:interceptors标签)

@Configuration //定义此类为配置类(即相当于之前的xml配置文件)
public class InterceptorConfig implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {//要拦截user下的所有访问请求,必须用户登录后才可访问,但是这样拦截的路径中有一些是不需要用户登录也可访问的String [] addPathPatterns={"/user/**"};//要排除的路径,排除的路径说明用户不需要登录也可访问String [] excludePathPatterns={"/user/out","/user/error","/user/login"};//mvc:interceptor bean class=""registry.addInterceptor(new UserInterceptor()).addPathPatterns(addPathPatterns).excludePathPatterns(excludePathPatterns);}
}

User

public class User {private Integer id;private String username;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}
}

UserController

@Controller
@RequestMapping(value = "/user")
public class UserController {//用户登录的请求,需要排除@RequestMapping(value = "/login")public @ResponseBody Object login(HttpServletRequest request){//将用户的信息存放到session中User user = new User();user.setId(1001);user.setUsername("zhangsan");request.getSession().setAttribute("user",user);return "login SUCCESS";}//该请求需要用户登录后才可访问@RequestMapping(value = "/center")public @ResponseBody Object center(){return "See Center Message";}//该请求不登录也可访问@RequestMapping(value = "/out")public @ResponseBody Object out(){return "Out see anytime";}//如果用户未登录访问了需要登录才可访问的情况,之后会跳转至该请求路径//该请求路径不需要登录也可访问@RequestMapping(value = "/error")public @ResponseBody Object error(){return "error";}}

SpringBoot框架下使用Servlet(了解)

-创建一个Servlet,它要继承HttpServlet

-在web.xml配置文件中使用servlet servlet-mapping

a.第一种方式:注解方式

@WebSevlet @ServletCompanscan

servlet.MyServlet

@WebServlet(urlPatterns = "/myservlet")
public class MyServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.getWriter().println("My SpringBoot Servlet-1");resp.getWriter().flush();resp.getWriter().close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doPost(req, resp);}
}
@SpringBootApplication  //开启spring配置
@ServletComponentScan(basePackages = "com.allspark.springboot.servlet")
public class Springboot031Servlet1Application {public static void main(String[] args) {SpringApplication.run(Springboot031Servlet1Application.class, args);}}

b.第二种方式:通过配置类注册主键

config.ServletConfig

@Configuration //该注解将此类定义为配置类(相当于一个xml文件)
public class ServletConfig {//@Bean是一个方法级别上的注解,主要用在配置类里//相当于一个//<beans>//    <bean id="" class="">//<beans>@Beanpublic ServletRegistrationBean servletRegistrationBean(){ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new MyServlet(),"/myservlet");return servletRegistrationBean;}
}

servlet.MyServlet

public class MyServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.getWriter().println("My SpringBoot Servlet-2");resp.getWriter().flush();resp.getWriter().close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doPost(req, resp);}
}

Spring框架下使用过滤器Filter(了解)

a.第一种方式:注解方式

@SpringBootApplication
@ServletComponentScan(basePackages = "com.allspark.springboot.filter")
public class Springboot033Filter1Application {public static void main(String[] args) {SpringApplication.run(Springboot033Filter1Application.class, args);}}
@WebFilter(urlPatterns = "/myfilter")
public class MyFilter implements Filter {@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {System.out.println("-------------您已进入过滤器----------------");filterChain.doFilter(servletRequest,servletResponse);}
}

b.第二种方式:注册主键

config.FilterConfig

@Configuration //定义此类为配置类
public class FilterConfig {@Beanpublic FilterRegistrationBean myFilterRegistrationBean(){//注册过滤器FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyFilter());//添加过滤路径filterRegistrationBean.addUrlPatterns("/user/*");return filterRegistrationBean;}
}

filter.MyFilter

public class MyFilter implements Filter {@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {System.out.println("----------------您已进入过滤器-222--------------------");filterChain.doFilter(servletRequest,servletResponse);}
}

web.UserController

@Controller
public class UserController {@RequestMapping(value = "/user/detail")public @ResponseBody String userDetail(){return "/user/detail";}@RequestMapping(value = "/center")public @ResponseBody String center(){return "center";}
}

Springboot框架下设置字符编码

a.第一种实现方式:使用CharacterEncodingFilter

comfig.SystemConfig

@Configuration //将此类定义为配置类
public class SystemConfig {@Beanpublic FilterRegistrationBean characterEncodingFilterRegistrationBean() {//创建字符编码过滤器CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();//设置强制使用指定字符编码characterEncodingFilter.setForceEncoding(true);//设置指定字符编码characterEncodingFilter.setEncoding("utf-8");FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();//设置字符编码过滤器filterRegistrationBean.setFilter(characterEncodingFilter);//设置字符编码过滤器路径filterRegistrationBean.addUrlPatterns("/*");return filterRegistrationBean;}
}

servlet.MyServlet

@WebServlet(urlPatterns = "/myservlet")
public class MyServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.getWriter().println("世界您好,Hello World!");//统一设置浏览器编码格式resp.setContentType("text/html;character=utf-8");resp.getWriter().flush();resp.getWriter().close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doGet(req, resp);}
}
@SpringBootApplication
@ServletComponentScan(basePackages = "com.allspark.springboot.servlet")
public class Springboot035CharacterEncoding1Application {public static void main(String[] args) {SpringApplication.run(Springboot035CharacterEncoding1Application.class, args);}}

application.properties

#关闭springboot的http字符编码支持
#只有关闭该选项后,spring字符编码过滤器生效
server.servlet.encoding.enabled=false

b.第二种方式:springboot字符编码设置(强力推荐)

servlet.MyServlet

@WebServlet(urlPatterns = "/myservlet")
public class MyServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.getWriter().println("世界您好,Hello World!");resp.setContentType("text/html;character=utf-8");resp.getWriter().flush();resp.getWriter().close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req,resp);}}

@ServletComponentScan(basePackages = “com.allspark.springboot.servlet”)

@SpringBootApplication
@ServletComponentScan(basePackages = "com.allspark.springboot.servlet")
public class Springboot036CharacterEncoding2Application {public static void main(String[] args) {SpringApplication.run(Springboot036CharacterEncoding2Application.class, args);}}

application.properties

#设置请求响应字符编码
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true
server.servlet.encoding.charset=utf-8

springboot打war包

部署到tomact中,之前在application.properties设置的上下文根和端口号就失效了,以本地Tomcat为准

springboot打jar包

端口号和上下文根就是springboot核心配置文件中设置的值

springboot集成logback日志

SpringBoot 集成 Thymeleaf 模板

简介

Thymeleaf 是一个流行的模板引擎,该模板引擎采用 Java 语言开发模板引擎是一个技术名词,是跨领域跨平台的概念,在 Java 语言体系下有模板引擎,在 C#、PHP 语言体系下也有模板引擎,甚至在 JavaScript 中也会用到模板引擎技术,Java 生态下的模板引擎有 Thymeleaf 、Freemaker、Velocity、Beetl(国产) 等。

Thymeleaf 对网络环境不存在严格的要求,既能用于 Web 环境下,也能用于非 Web 环境下。在非 Web 环境下,他能直接显示模板上的静态数据;在 Web 环境下,它能像 Jsp 一样从后台接收数据并替换掉模板上的静态数据。它是基于 HTML 的,以 HTML 标签为载体,Thymeleaf 要寄托在 HTML 标签下实现。

SpringBoot 集成了 Thymeleaf 模板技术,并且 Spring Boot 官方也推荐使用 Thymeleaf 来替代 JSP 技术,Thymeleaf 是另外的一种模板技术,它本身并不属于 Spring Boot,Spring Boot只是很好地集成这种模板技术,作为前端页面的数据展示,在过去的 Java Web 开发中,我们往往会选择使用 Jsp 去完成页面的动态渲染,但是 jsp 需要翻译编译运行,效率低

Thymeleaf 的官方网站:http://www.thymeleaf.org

Thymeleaf 官方手册:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

例子1:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<!--thymeleaf模板引擎的页面必须得通过中央调度器
-->
<h2 th:text="${data}">展示要显示的内容</h2>
</body>
</html>

例子2:Thymeleaf 关闭页面缓存

#设置thymeleaf模板引擎的缓存,设置为false关闭,默认为true开启
spring.thymeleaf.cache = false#设置thymeleaf模板引擎的前/后缀,(可选项)
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

再改update resources

thymeleaf表达式

标准变量表达式和选择变量表达式

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<h1>标准变量表达式:${}(推荐)</h1>
用户编号:<span th:text="${user.id}"></span><br>
用户姓名:<span th:text="${user.username}"></span><br>
用户年龄:<span th:text="${user.age }"></span><br><h1>选择变量表达式(星号表达式):*{}(不推荐)</h1>
<!--*{}必须使用th:object属性绑定这个对象在div子标签中使用*来代替绑定的对象${}
-->
<div th:object="${user}">用户编号:<span th:text="*{id}"></span><br>用户姓名:<span th:text="*{username}"></span><br>用户年龄:<span th:text="*{age}"></span><br>
</div><h1>标签变量表达式与选择变量表达式混合使用(不推荐)</h1>
用户编号:<span th:text="*{user.id}"></span><br>
用户姓名:<span th:text="*{user.username}"></span><br>
用户年龄:<span th:text="*{user.age}"></span><br>
</body>
</html>

路径表达式

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<h1>URL路径表达式:@{.... }</h1>
<h2>a标签中的绝对路径(没有参数)</h2>
<a href="http://www.baidu.com">传统写法:跳转至百度</a><br>
<a th:href="@{http://www.bjpowernode.com}">路径表达式:跳转至动力节点</a><br>
<a th:href="@{http://localhost:8080/user/detail}">跳转至:/user/detail</a><br>
<a href="http://localhost:8080/user/detail">传统写法跳转至:/user/detail</a><br><h2>URL路径表达式,相对路径[没有参数](实际开发中推荐使用的)</h2>
<a th:href="@{/user/detail}">跳转至:/user/detail</a><h2>绝对路径(带参数)(不推荐)</h2>
<a href="http://localhost:8080/test?username='zhangsan'">绝对路径,带参数:/test,并带参数username</a><br>
<a th:href="@{http://localhost:8080/test?username=zhangsan}">路径表达式写法,带参数/test,并带参数username</a><br><h2>相对路径(带参数)</h2>
<a th:href="@{/test?username=lisi}">相对路径,带参数</a><h2>相对路径(带参数:后台获取的参数值)</h2>
<a th:href="@{'/test?username='+${id}}">相对路径:获取后台参数值</a><h2>相对路径(带多个参数:后台获取的参数值)</h2>
<a th:href="@{'/test1?id='+${id}+'&username='+${username}+'&age='+${age}}">相对路径(带多个参数:后台获取的参数值)</a><br>
<a th:href="@{/test1(id=${id},username=${username},age=${age})}">强烈推荐使用:@{}相对路径(带多个参数:后台获取的参数值)</a><br>
<a th:href="@{'/test2/'+${id}}">请求路径为RESTful风格</a><br>
<a th:href="@{'/test3/'+${id}+'/'+${username}}">请求路径为RESTful风格</a>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<script type="text/javascript" th:src="@{/js/jquery-2.0.0.min.js}"></script>
<script>$(function (){alert("-----");alert($("#username").val());});</script>
<input type="text" id="username" value="999">
<img th:src="@{/img/R-C.jpg}">
</body>
</html>

thymeleaf常见属性

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<form method="get" action="http://localhost:8080/test1">用户编号:<input type="text" name="id"><br>用户姓名:<input type="text" name="username"><br>用户年龄:<input type="text" name="age"><br><input type="submit" value="submit">
</form><form th:method="post" th:action="@{/test1}">用户编号:<input type="text"th:id="id" th:name="id"><br>用户姓名:<input type="text" th:id="username" th:name="username"><br>用户年龄:<input type="text" th:id="age" th:name="age"><br><input type="submit" value="submit"><script>function test(){alert("----");}</script><button th:onclick="test()">submit111</button><button onclick="test()">submit222</button>
</form>
</body>
</html>

th:each

循环遍历list集合
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>循环遍历list集合</title>
</head>
<body>
<!--user 当前循环的对象变量名称(随意)userStat 当前循环对象状态的变量(可选默认就是对象变量名称+Stat)${userList} 当前循环的集合
--><div th:each="user,userStat:${userList}"><span th:text="${userStat.index}"></span><span th:text="${userStat.count}"></span><span th:text="${user.id}"></span><span th:text="${user.nick}"></span><span th:text="${user.phone}"></span><span th:text="${user.address}"></span>
</div>
</body>
</html>
循环遍历Map集合
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>循环遍历Map集合</title>
</head>
<body>
<div th:each="userMap,userMapStat:${userMaps}"><span th:text="${userMapStat.count}"></span><span th:text="${userMapStat.index}"></span><span th:text="${userMap.key}"></span><span th:text="${userMap.value}"></span><span th:text="${userMap.value.id}"></span><span th:text="${userMap.value.nick}"></span><span th:text="${userMap.value.phone}"></span><span th:text="${userMap.value.address}"></span>
</div>
</body>
</html>
循环遍历数组
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>循环遍历Array数组</title>
</head>
<body>
<h1>循环遍历Array数组(使用方法同list一样)</h1>
<div th:each="user,userStat:${userArray}"><span th:text="${userStat.index}"></span><span th:text="${userStat.count}"></span><span th:text="${user.id}"></span><span th:text="${user.nick}"></span><span th:text="${user.phone}"></span><span th:text="${user.address}"></span>
</div>
</body>
</html>
遍历复杂集合
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>循环遍历复杂的集合</title>
</head>
<body>
<h2>循环遍历复杂集合:list->Map->list->User</h2>
<div th:each="myListMap:${myList}"><div th:each="myListMapObj:${myListMap}">Map集合的key:<span th:text="${myListMapObj.key}"></span><div th:each="myListMapObjList:${myListMapObj.value}"><span th:text="${myListMapObjList.id}"></span><span th:text="${myListMapObjList.nick}"></span><span th:text="${myListMapObjList.phone}"></span><span th:text="${myListMapObjList.address}"></span></div></div>
</div>
</body>
</html>

条件判断

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>条件判断</title>
</head>
<body>
<h1>th:if 用法:如果满足条件显示(执行),否则相反</h1>
<div th:if="${sex eq 1}"></div>
<div th:if="${sex eq 0}"></div><h1>th:unless 用法:与th:if相反,即条件判断取反</h1>
<div th:unless="${sex ne 1}"></div><h1>th:switch/th:case用法</h1>
<div th:switch="${productType}"><span th:case="0">产品0</span><span th:case="1">产品1</span><span th:case="*">无此产品</span>
</div>
</body>
</html>

内敛表达式

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>内敛表达式</title>
</head>
<body>
<div th:text="${data}">xxx</div>
<h3 th:text="${data}">xxx</h3><h1>内敛文本:th:inline="text"</h1>
<div th:inline="text">数据:[[${data}]]
</div><h1>内敛脚本 th:inline="javascript"</h1>
<script type="text/javascript" th:inline="javascript">function showData() {alert([[${data}]]);}</script>
<button th:onclick="showData()">展示数据</button>
</body>
</html>

字面量

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>字面量</title>
</head>
<body>
<h1>文本字面量,用单引号'....'的字符串就是字面量</h1>
<a th:href="@{'/user/detail?sex='+${sex}}">查看性别</a>
<span th:text="Hello"></span><h1>数字字面量</h1>
今年是<span th:text="2020">1949</span><br/>
20年后是<span th:text="2020+20">1969</span><br/><h2>boolean字面量</h2>
<div th:if="${flag}">执行成功
</div>
<div th:if="${!flag}">不成功
</div><h1>null字面量</h1>
<span th:text="${user.id}"></span>
<div th:unless="${userDetail eq null}">对象已创建,地址不为空
</div>
<div th:if="${userDetail.id eq null}"></div></body>
</html>

字符串拼接

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>字符串拼接</title>
</head>
<body>
<span th:text="''+${totalRows}+''+${totalPage}+'页,当前第'+${currentPage}+'页,首页 上一页 下一页 尾页'"></span><h1>使用更优雅的方式来拼接字符串:|要拼接的字符串内容|</h1>
<span th:text="|共${totalRows}条${totalPage}页,当前第${currentPage}页,首页 上一页 下一页 尾页|">共120条12页,当前第1页,首页 上一页 下一页 尾页</span>
</body>
</html>

运算符

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>运算符</title>
</head>
<body>
<!--三元运算:表达式?”正确结果”:”错误结果”算术运算:+ , - , * , / , %关系比较::> , < , >= , <= ( gt , lt , ge , le )相等判断:== , != ( eq , ne )
-->
<h1>三元运算符</h1>
<span th:text="${sex eq 1 ? '':''}"></span><br/>
<span th:text="${sex == 1 ? '':''}"></span><br/>
20*8=<span th:text="20 * 8"></span><br/>
20/8=<span th:text="20 / 8"></span><br/>
20+8=<span th:text="20 + 8"></span><br/>
20-8=<span th:text="20 - 8"></span><br/>
<div th:if="5 > 2">5>2 是真的</div>
<div th:unless="5 gt 2">5 gt 2 是真的</div>
1>=1<span th:if="1 ge 1"></span>
1<=1<span th:if="1 le 1"></span>
</body>
</html>

基本表达式对象

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<h1>从session中获取值</h1>
<span th:text="${#session.getAttribute('data')}"></span><br>
<span th:text="${#httpSession.getAttribute('data')}"></span><br>
<span th:text="${session.data}"></span><br>
<script type="text/javascript" th:inline="javascript">//http://localhost:8080/springboot/user/detail//获取协议名称var scheme = [[${#request.getScheme()}]];//获取服务器名称var serverName = [[${#request.getServerName()}]];//获取服务器端口号var serverPort = [[${#request.getServerPort}]];//获取上下文根var contextPath = [[${#request.getContextPath()}]];var allPath = scheme+"://"+serverName+":"+serverPort+contextPath;var requestURL = [[${#httpServletRequest.requestURL}]];var queryString = [[${#httpServletRequest.queryString}]];alert(requestURL);alert(queryString);</script>
</body>
</html>

功能表达式对象

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<div th:text="time"></div>
<div th:text="${#dates.format(time,'yyyy-MM-dd HH:mm:ss')}"></div>
<div th:text="${data}"></div>
<div th:text="${#strings.substring(data,0,10)}"></div>
<div th:text="${#lists}"></div>
</body>
</html>

自学之SpringBoot相关推荐

  1. 自学笔记-SpringBoot集成ElasticSearch

    目录 一.ElasticSearch介绍: 二.ElasticSearch安装: 三.Kibana的安装 四.配置ik分词器 五.Springboot集成ElasticSearch Ⅰ.依赖 Ⅱ.配置 ...

  2. 毕业设计:基于Springboot + Vue仿网易云音乐网站(一)开源

    项目背景 最近自学了springboot.vue.redis等技术,为了巩固,决定自己做个小网站玩玩,把学到的东西都使用一下,因为自己比较喜欢听音乐,去年一年网易云就听了1800个小时,然后也喜欢周杰 ...

  3. 百度实习面经2022-4-24(第一次面试,暂时只面了一场,感觉人无了)

    我的学习进度 我走的是JavaEE企业版的开发,目前大三在读,路线也是先学的 c语言.java.HTML+CSS3.Jquery.python等 之后专注于 java 走后端开发路线学了MySQL.J ...

  4. 自学SpringBoot,超详细笔记

    1.SpringBoot 回顾下什么是Spring? Spring是一个开源框架,2003年兴起的一个轻量级的java开发框架,是为了解决企业级应用开发的复杂性而创建的,简化开发 Spring是如何简 ...

  5. 自学SpringBoot之国际化配置相关的坑

    前两天在b站上自学SpringBoot的国际化配置时,浏览器总是报乱码的错,类似??login.tip_zh_CN??, 由于b站上基本都是使用Ideal,我用的是sts2.2.5版本,难免遇到不同, ...

  6. springboot毕设项目法律自学网的设计与实现 878x4(java+VUE+Mybatis+Maven+Mysql)

    springboot毕设项目法律自学网的设计与实现 878x4(java+VUE+Mybatis+Maven+Mysql) 项目运行 环境配置: Jdk1.8 + Tomcat8.5 + Mysql ...

  7. 自学Springboot(一)

    注:所用IDLE为Intellij 一丶创建一个Springboot项目 二丶项目目录 三丶 创建一个测试controller(SampleController.java) 代码如下 package ...

  8. Flyway自学之路-04(springboot结合Flyway)

    1.新建项目 2.添加mysql数据库依赖 <dependency><groupId>org.springframework.boot</groupId><a ...

  9. 自学Java day41 图书管理系统-springboot快速开发 从jvav到架构师

    前端:html + css + jvavscript + vue + ajax + axios + element ui 后端:jvav + springboot + mybatisplus + my ...

最新文章

  1. matlab元件阻感负载,单相桥式全控整流电路阻感负载课程设计matlab
  2. 一天学完spark的Scala基础语法教程十、类和对象(idea版本)
  3. net中一些所封装的类
  4. Python day7之mysql
  5. linux ntp时间立即同步命令_记一次生产环境部署NTP服务及配置时间同步
  6. linux添加超级管理员用户,修改,删除用户
  7. python求最大值代码的方式_python使用分治法实现求解最大值的方法
  8. MOSEK Fusion Model
  9. 电影海王真的好看吗|我爬取了9000条影评,得出的结论是
  10. Qt phonon 多媒体框架
  11. rst 文件打开方式
  12. XSSFWorkbook下载excel表格
  13. Python for 循环遍历字符串
  14. WorkPlus SE | 全国第1个永久免费的即时通讯软件!
  15. 新手如何选择外汇交易平台?
  16. OSPF与BGP联动
  17. 常见浏览器清理缓存方法
  18. echarts横向倒叙柱状图
  19. 批处理设置windows防火墙协议规则
  20. 如果有天,全世界的人都变成程序员......

热门文章

  1. MediaPlay 缓存
  2. 在Thinkpad中设置电池管理阈值
  3. 因为我们在对待他冷漠的表面下
  4. iPad pro快捷键
  5. vue项目构建和部署_零部署:使用Vue和VuePress构建文档系统
  6. maya中英文对照_maya菜单中英文对照(1)_maya教程
  7. 玩转这6个平台,用Python接单告别死工资,三个月挣了去年一年的收入!
  8. truncate 与 delete 区别
  9. 如何有效预防CC攻击?
  10. 【操作系统】如何在linux系统下运行C程序