SpringBoot快速入门

1.开端介绍

1.两种核心配置文件同时存在(properties的优先级高于yml)

[图片上传失败...(image-64f292-1649323574184)]

2.多环境下核心配置文件

[图片上传失败...(image-74a4eb-1649323574184)]

[图片上传失败...(image-ed1bc1-1649323574184)]

[图片上传失败...(image-8632ca-1649323574184)]

3.获取自定义配置

[图片上传失败...(image-478bb0-1649323574184)]

[图片上传失败...(image-3b77ba-1649323574184)]

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

[图片上传失败...(image-2bad1-1649323574184)]

[图片上传失败...(image-55236c-1649323574184)]

[图片上传失败...(image-f7cc3a-1649323574184)]

[图片上传失败...(image-ddecbc-1649323574184)]

5.springboot集成jsp

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

<bulid>
<!--
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>
</bulid>

[图片上传失败...(image-554766-1649323574184)]

[图片上传失败...(image-566f27-1649323574184)]

[图片上传失败...(image-86c4b-1649323574184)]

[图片上传失败...(image-b22041-1649323574184)]

2. springboot框架web开发

1.集成mybatis 所需的依赖

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

2.Mybatis创建逆向工程 (步骤)

<!--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>

[图片上传失败...(image-d341b2-1649323574184)]

GeneratorMapper.xml:
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEgeneratorConfiguration
PUBLIC"-//mybatis.org//DTDMyBatisGeneratorConfiguration1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>

<!--指定连接数据库的JDBC驱动包所在位置,指定到你本机的完整路径-->
<classPathEntrylocation="D:\222\abo\mysql-connector-java-5.1.37.jar"/>

<!--配置table表信息内容体,targetRuntime指定采用MyBatis3的版本-->
<contextid="tables"targetRuntime="MyBatis3">
<!--抑制生成注释,由于生成的注释都是英文的,可以不让它生成-->
<commentGenerator>
<propertyname="suppressAllComments"value="true"/>
</commentGenerator>

<!--connectionURL="jdbc:mysql://192.168.80.129:3306/springboot"-->
<!--配置数据库连接信息-->
<jdbcConnectiondriverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm1"
userId="root"
password="123456">
</jdbcConnection>
<!--生成model类,targetPackage指定model类的包名,targetProject指定
生成的model放在eclipse的哪个工程下面-->
<javaModelGeneratortargetPackage="com.jihu.model"
targetProject="src/main/java">
<propertyname="enableSubPackages"value="false"/>
<propertyname="trimStrings"value="false"/>
</javaModelGenerator>

<!--生成MyBatis的Mapper.xml文件,targetPackage指定mapper.xml文件的
包名,targetProject指定生成的mapper.xml放在eclipse的哪个工程下面-->
<sqlMapGeneratortargetPackage="com.jihu.mapper"
targetProject="src/main/java">
<propertyname="enableSubPackages"value="false"/>
</sqlMapGenerator>

<!--生成MyBatis的Mapper接口类文件,targetPackage指定Mapper接口类的包
名,targetProject指定生成的Mapper接口放在eclipse的哪个工程下面-->
<javaClientGeneratortype="XMLMAPPER"
targetPackage="com.jihu.mapper"targetProject="src/main/java">
<propertyname="enableSubPackages"value="false"/>
</javaClientGenerator>

<!--数据库表名及对应的Java模型类名-->
<tabletableName="user"domainObjectName="User"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>

application.properties:(指定了mybatis映射文件路径)
#设置连接数库的配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssm1?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456

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

开启扫描mapper的两种办法

第一种

[图片上传失败...(image-94222c-1649323574183)]

第二种

[图片上传失败...(image-14acd2-1649323574183)]

UserController
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/user")
    public Object user(Integer id){
        User user = userService.queryUserById(id);
        return user;
    }
}

UserService
public interface UserService {

    //根据学生id查询详情
    User queryUserById(Integer id) ;

}

UserServiceImpl
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User queryUserById(Integer id) {

        return userMapper.selectByPrimaryKey(id);
    }
}

UserMapper
package com.jihu.mapper;

import com.jihu.model.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper //扫描DAO接口道spring容器
public interface UserMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jihu.mapper.UserMapper">

  <resultMap id="BaseResultMap" type="com.jihu.model.User">
   <!-- id 标签只能修改主键字段-->
    <!-- result 除了主键以外的字段-->
    <!--
        column 数据库中的字段名称
        property 映射对象的属性名称
        jdbcType 列中数据库中字段的类型(可以省略不写)
    -->
    <!--
        resultMap 作用:
         1.当数据库中字段名称与实体类对象的属性名不一致时,可以进行转换
         2.当前查询的结果没有对象一个表的时候,可以自定义一个结果集
    -->
    <!--
           数据库表字段名称      实体对象属性名称
              user_name          userName
              product_type      productType
    -->
    <!--
          如果数据库中字段名称由多个单词构成,通过mybatis逆向工程生成的对象属性名称 会按照驼峰命名法规则生成属性名称
          其中:数据库中字段名称由多个单词构成的时候必须使用 _ 下划线分隔
    -->

    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="username" jdbcType="VARCHAR" property="username" />
    <result column="password" jdbcType="VARCHAR" property="password" />
  </resultMap>
  <!-- sql语句片段, 将公共的部分抽取出来  -->
  <sql id="Base_Column_List">
    id, username, password
  </sql>

  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from user
    where id = #{id,jdbcType=INTEGER}
  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from user
    where id = #{id,jdbcType=INTEGER}
  </delete>

  <insert id="insert" parameterType="com.jihu.model.User">
    insert into user (id, username, password
      )
    values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
      )
  </insert>

  <!--
    trim: 拼接用的
    suffixOverrides:去除多余的逗号
  -->
  <insert id="insertSelective" parameterType="com.jihu.model.User">
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="username != null">
        username,
      </if>
      <if test="password != null">
        password,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="username != null">
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        #{password,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>

  <update id="updateByPrimaryKeySelective" parameterType="com.jihu.model.User">
    update user
    <set>
      <if test="username != null">
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        password = #{password,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>

  <update id="updateByPrimaryKey" parameterType="com.jihu.model.User">
    update user
    set username = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>

</mapper>

User
@Data
public class User {
    private Integer id;

    private String username;

    private String password;
}    

3.springboot支持事务

springboot项目下使用事务:

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

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

DML,DQL,DDL,TCL,DCL

[图片上传失败...(image-5fb187-1649323574183)]

[图片上传失败...(image-d11352-1649323574182)]

4.使用 RESTful

[图片上传失败...(image-92d864-1649323574182)]

5.拦截器(重要)

springboot使用拦截器步骤:

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

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

[图片上传失败...(image-5e21fe-1649323574182)]

InterceptorConfig

package com.jihu.config;
import com.jihu.interceptor.UserInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration  //定义此类为配置文件(即相当于之前的xml配置文件)
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //要拦截user下的所有访问请求,必须用户登录后才能访问,
        //但是这样拦截的路径中有一些是不需要用户登录也可访问的
        String[] addPathPattererns = {
                "/user/**"
        };
        //要排除的路径,排除的路径说明不需要用户登录也可以访问
        String[] excludePathPatterns={
                "/user/out","/user/error","/user/login"
        };

        registry.addInterceptor(new UserInterceptor()).addPathPatterns(addPathPattererns).excludePathPatterns(excludePathPatterns);
    }
}

UserInterceptor

public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入拦截器----------------");
        //编写业务拦截的规则
        //从session中获取用户的信息
        User user = (User) request.getSession().getAttribute("user");

        //判断用户是否登录
        if (user == null){
            //未登录
            response.sendRedirect(request.getContextPath() + "/user/error");
            return  false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

UserController

package com.jihu.web;
import com.jihu.model.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    //用户登录请求
    @RequestMapping("/login")
    public Object login(HttpServletRequest request){
        //将用户信息存放到session
        User user = new User();
        user.setId(1002);
        user.setUsername("zhangsan");
        request.getSession().setAttribute("user",user);
        return "Login Success";
    }

    //该请求需要用户登录之后才可以访问
    @RequestMapping("/center")
    public Object center(){
        return "See Center Message";
    }

    //该请求不登录也可以访问
    @RequestMapping("/out")
    public Object out(){
        return "out";
    }

    //如果用户未登录访问了需要登录才可访问的请求,之后会跳转至该请求路径
    @RequestMapping("/error")
    public Object error(){
        return "error";
    }

}

User

@Data
public class User {

    private Integer id;
    private String username;
}    

6.使用 filter(过滤器)

案例1:使用注解方式

案例2:使用注册组件方式

案例1;

MyFilter

package com.jihu.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(urlPatterns = "/myfilter")
public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest,
        ServletResponse servletResponse, FilterChain filterChain) 
         throws IOException, ServletException {
        System.out.println("------------您已进入过滤器-------------");

        filterChain.doFilter(servletRequest,servletResponse);
    }
}

Application

@SpringBootApplication
@ServletComponentScan(basePackages = "com.jihu.filter")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

案例2:

[图片上传失败...(image-2b90bd-1649323574182)]

@Configuration  //定义此类为配置类
public class FilterConfig {

    @Bean
    public FilterRegistrationBean myFilterRegistrationBean(){

        //注册过滤器
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyFilter());
        //添加过滤路径
        filterRegistrationBean.addUrlPatterns("/user/*");

        return filterRegistrationBean;

    }

}

MyFilter

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

        filterChain.doFilter(servletRequest,servletResponse);
    }
}

UserController

@RestController
public class UserController {

    @RequestMapping("/user/detail")
    public  String userDetail(){
        return "/user/detail";
    }

    @RequestMapping("/center")
    public  String center(){
        return "center";
    }

}

7.设置字符编码

springboot 框架下设置字符编码

第一种实现方式: 使用CharacterEncodingFilter

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

第一种方式:

application.properties

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

MyServlet

package com.jihu.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.getWriter().println("i love 中国");
        //统一设置浏览器编码格式
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().flush();
        resp.getWriter().close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

Application

@SpringBootApplication
@ServletComponentScan(basePackages = "com.jihu.servlet")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

第二种方式:

application.properties

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

SystemConfig

package com.jihu.config;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;

@Configuration
public class SystemConfig {

    @Bean
    public FilterRegistrationBean characterEncodingFilterRegistrationBean(){

        //创建字符编码过滤器
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        //设置强制使用指定字符编码
        characterEncodingFilter.setForceEncoding(true);
        //设置指定字符编码
        characterEncodingFilter.setEncoding("UTF-8");

        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();

        //设置字符编码过滤器
        filterRegistrationBean.setFilter(characterEncodingFilter);
        //设置字符编码过滤器路径
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }

}

MyServlet

package com.jihu.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.getWriter().println("i love 中国");
        //统一设置浏览器编码格式
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().flush();
        resp.getWriter().close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

Application

@SpringBootApplication
@ServletComponentScan(basePackages = "com.jihu.servlet")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

8.logback日志

resources/logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- 日志级别从低到高分为 TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果
设置为 WARN,则低于 WARN 的信息都不会输出 -->
<!-- scan:当此属性设置为 true 时,配置文件如果发生改变,将会被重新加载,默认值为
true -->
<!-- scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认
单位是毫秒。当 scan 为 true 时,此属性生效。默认的时间间隔为 1 分钟。 -->
<!-- debug:当此属性设置为 true 时,将打印出 logback 内部日志信息,实时查看 logback
运行状态。默认值为 false。通常不打印 -->
<configuration scan="true" scanPeriod="10 seconds">
    <!--输出到控制台-->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <!--此日志 appender 是为开发使用,只配置最底级别,控制台输出的日志级别是大
        于或等于此级别的日志信息-->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>debug</level>
        </filter>
        <encoder>
            <Pattern>%date [%-5p] [%thread] %logger{60} [%file : %line] %msg%n
            </Pattern>
            <!-- 设置字符集 -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!--<File>/home/log/stdout.log</File>-->
        <File>D:/log/stdout.log</File>
        <encoder>
            <pattern>%date [%-5p] %thread %logger{60} [%file : %line] %msg%n</pattern>
        </encoder>
        <rollingPolicy
                class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- 添加.gz 历史日志会启用压缩 大大缩小日志文件所占空间 -->
            <!--<fileNamePattern>/home/log/stdout.log.%d{yyyy-MM-dd}.log</fileNam ePattern>-->
            <fileNamePattern>D:/log/stdout.log.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>30</maxHistory><!-- 保留 30 天日志 -->
        </rollingPolicy>
    </appender>

    <!--单个定义-->
    <logger name="com.bjpowernode.springboot.mapper" level="DEBUG"/>

    <!--如果root标签指定的日志级别那么以根日志级别为准,如果没有则已当前追加器日志级别为准-->
    <!--全部定义-->
    <root level="INFO">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </root>
</configuration>

3.thymeleaf

使用 thymeleaf 时必须加上命名空间

<html lang="en" xmlns:th="http://www.thymeleaf/org">

1.thymeleaf概述

[图片上传失败...(image-631c3b-1649323574180)]

[图片上传失败...(image-3bc5f0-1649323574180)]

2.springboot集成thymeleaf

application.properties

#设置thymeleaf模板引擎的缓存,设置为false(关闭), 默认为true(开启)
spring.thymeleaf.cache=false

#设置thymeleaf模板引擎的前缀/后缀(可选项)
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html	

[图片上传失败...(image-d135cf-1649323574180)]

IndexController

package com.jihu.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class IndexController {

    @RequestMapping("/message")
    public ModelAndView message(){
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg","你好 China!");
        mv.setViewName("message");
        return mv;
    }

    @RequestMapping("/index")
    public String index(Model model){
        model.addAttribute("data","SpringBoot 引擎设置");
        return "index";
    }

}

message.html

<!DOCTYPE html>
<!--
    xmlns:th="http://www.thymeleaf.org"
    xmlns ->命名空间
    命名空间后面的地址是一个约束文件,约束你使用thymeleaf表达式的一个规则文件,
    就好比我们之前在xml文件中的一些dtd文件
-->

<!--
    为什么使用了th 前缀就可以获取后台数据?
     那是因为项目中添加了thymeleaf的核心依赖,它的核心依赖会去解析thymeleaf自己定义的这些
     标签名称,通过thymeleaf自己的java核心代码来获取我们的后台数据
-->

<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--  thymeleaf模板引擎的页面必须的通过中央调度器  -->
<h1 th:text="${msg}" >xxx </h1>
<h1 th:text="${msg}" >xxx </h1>
<h1 th:text="${msg}" > </h1>

<h1>Thymeleaf</h1>
<h1>Thymeleaf</h1>

</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1 th:text="${data}">3</h1>

</body>
</html>

3.thymeleaf表达式–4种路径表达式

application.properties

#设置thymeleaf模板引擎的缓存,设置为false(关闭), 默认为true(开启)
spring.thymeleaf.cache=false

#设置thymeleaf模板引擎的前缀/后缀(可选项)
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html	

[图片上传失败...(image-ce8b9d-1649323574179)]

UserController

package com.jihu.web;

import com.jihu.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    @RequestMapping("/user/detail")
    public String user(Model model){

        User user = new User();
        user.setId(1001);
        user.setUsername("lisi");
        user.setAge(24);
        model.addAttribute("user",user);
        return "userDetail";
    }

    @RequestMapping("/url")
    public String url(Model model){
        model.addAttribute("id",1005);
        model.addAttribute("username","zhangsan");
        model.addAttribute("age",28);
        return "url";
    }

    @RequestMapping("/test")
    public @ResponseBody String test(String username){
        return "请求路径/test,参数是:"+username;
    }

    @RequestMapping("/test1")
    public @ResponseBody String test1(Integer id,String username,Integer age){
        return "请求路径/test1,参数id:"+id+",username:"+username+",age:"+age;
    }

    @RequestMapping("/test2/{id}")
    public @ResponseBody String test2(@PathVariable("id") Integer id){
        return "ID="+id;
    }
    @RequestMapping("/test3/{id}/{username}")
    public @ResponseBody String test3(@PathVariable("id") Integer id,
                                      @PathVariable("username") String username  ){
        return "ID="+id+"-----username="+username;
    }

    @RequestMapping("/url2")
    public  String url2(){
        return "url2";
    }

    @RequestMapping("/property")
    public  String property(){
        return "property";
    }
}

User

@Data
public class User {

    private Integer id;
    private String username;
    private Integer age;
}    

property.html

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>常见属性</title>
</head>
<body>

<form action="http://localhost:8080/test1" method="get">
    用户编号;<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:action="@{/test1}" method="get">
    用户编号;<input type="text" name="id"  /><br>
    用户姓名;<input type="text" name="username"  /><br>
    用户年龄;<input type="text" name="age"  /><br>
    <input type="submit" value="提交submit"  />
</form>

<script type="text/javascript">
    function test() {

            alert("------");
    }
</script>

<button th:onclick="test()">submit11</button>
<button onclick="test()">submit22</button>
</body>
</html>

url.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.bjpowernode1.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>

<h2>URL路径表达式,相对路径【没有参数】(实际开发中推荐使用)</h2>
<a th:href="@{/user/detail}">跳转到:/user/detail</a>

<h2>相对路径(带参数)</h2>
<a th:href="@{/test?username=lisi}" >相对路径,带参数</a><br>

<h2>相对路径(带参数,后台获取的参数值)</h2>
<!--/test?username=1005-->
<a th:href="@{'/test?username='+${id}}">相对路径,带参数,后台获取的参数值</a><br>

<h2>相对路径(带多个参数,后台获取的参数值)</h2>
<!-- /test1?id=1005&username=zhangsan&age=28  -->
<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>
<!--/test3/1005/zhangsan-->
<a th:href="@{'/test3/'+${id}+'/'+${username}}"> 请求路径为RESTful风格</a>

</body>
</html>

url2.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf/org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" th:src="@{/js/jquery-3.4.1.js}"></script>
    <script type="text/javascript">
        $(function () {
          //  alert("----");
            alert($("#username").val());
        });

    </script>
</head>
<body>
<input  type="text" value="999" id="username" />
<img th:src="@{/img/1.jpg}">
</body>
</html>

userDetail.html

<!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/>

<!--
    *{}必须使用th:object属性来绑定这个对象
    在div子标签中使用*来代替绑定的对象${user}
-->
<h1> 选择变量表达式(星号表达式) ;*{}  ->(不推荐) </h1>
<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>

3.循环遍历数组

[图片上传失败...(image-bceab1-1649323574178)]

UserController

package com.jihu.controller;

import com.jihu.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @RequestMapping("/each/list")
    public  String eachList(Model model){
        List<User> userList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setId(100+i);
            user.setNick("尹"+1);
            user.setPhone("1234561421"+i);
            user.setAddress("北京大兴"+i);
            userList.add(user);
        }
        model.addAttribute("userList",userList);
        return "eachList";
    }

    @RequestMapping("/each/Map")
    public  String eachMap(Model model){
        Map<Integer,Object> userMap = new HashMap<>();
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setId(100+i);
            user.setNick("尹"+1);
            user.setPhone("1234561421"+i);
            user.setAddress("北京大兴"+i);
           userMap.put(i,user);
        }
        model.addAttribute("userMap",userMap);
        return "eachMap";
    }

    @RequestMapping("/each/array")
    public  String eacharray(Model model){
       User[] userarray= new User[10];
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setId(100+i);
            user.setNick("尹"+1);
            user.setPhone("1234561421"+i);
            user.setAddress("北京大兴"+i);
           userarray[i]=user;
        }
        model.addAttribute("userarray",userarray);
        return "eachArray";
    }
}

User

@Data
public class User {

    private Integer id;
    private String nick;
    private String  phone;
    private String address;
}    

循环遍历Array数组(eachArray.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="userarray:${userarray}">
    <span  th:text="${userarrayStat.index}"></span>
    <span  th:text="${userarrayStat.count}"></span>
    <span th:text="${userarray.id}"></span>
    <span th:text="${userarray.nick}"></span>
    <span th:text="${userarray.phone}"></span>
    <span th:text="${userarray.address}"></span>

</div>
</body>
</html>

循环遍历list集合(eachList.html)
<!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>
<br>
<div th:each="user:${userList}">
    <span th:text="${userStat.count}"></span>
</div>

</body>
</html>

循环遍历Map集合(eachMap.html)
<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>循环遍历Map集合</title>
</head>
<body>

<!--
    Map集合结构
    key   value
    0      user
    1      user
    2      user
    ..     ...
-->
<div th:each="userMap:${userMap}">
    <span th:text="${userMapStat.index}"></span>
    <span th:text="${userMapStat.count}"></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>

4.条件判断 (th:if)

[图片上传失败...(image-bb426d-1649323574177)]

UserController

@Controller
public class UserController {

    @RequestMapping("/condition")
    public String condition(Model model){
        model.addAttribute("sex",1);
        model.addAttribute("flag",true);
        model.addAttribute("productType",0);
        return  "condition";
    }
}

condition.html

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>条件判断</title>
</head>
<body>
<h2> th:if 用法:如果满足条件显示(执行),否则相反 </h2>
<div th:if="${sex eq 1}">
    男
</div>
<div th:if="${sex eq 0}">
    女
</div>

<h2>th:unless  用法:与th:if用法想法,即条件判断取反</h2>
<div th:unless="${sex ne 1}">
    女
</div>

<h2> th:switch/th:case用法</h2>
<div th:switch="${productType}">
    <span th:case="0">产品0</span>
    <span th:case="1">产品1</span>
    <span th:case="*">无此产品</span>
</div>
</body>
</html>

5.内敛表达式 (th:inline)

UserController

@Controller
public class UserController {

    @RequestMapping("/inline")
    public String inline(Model model){
        model.addAttribute("data","springboot  111");
        return "inline-test";
    }
}

inline-test.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="${data}"></div>

<h2>内敛文本: th:inline="text"</h2>
<div th:inline="text">
    [[${data}]]
</div>
数据outside:  [[${data}]]

<h2>  内敛脚本 th:inline="javascript"  </h2>
<script type="text/javascript" th:inline="javascript">
    function showData() {
        alert([[${data}]]);
    }
</script>
<button type="button" onclick="showData()">展示数据</button>
</body>
</html>

7.字面量

[图片上传失败...(image-198d2f-1649323574176)]

[图片上传失败...(image-9bc193-1649323574176)]

[图片上传失败...(image-4b2798-1649323574176)]

[图片上传失败...(image-2cc394-1649323574176)]

8.字符串拼接

[图片上传失败...(image-9e7d4d-1649323574176)]

[图片上传失败...(image-aef29-1649323574176)]

[图片上传失败...(image-fdcdad-1649323574176)]

9.数学运算

[图片上传失败...(image-1128a1-1649323574175)]

[图片上传失败...(image-a3eaf2-1649323574175)]

[图片上传失败...(image-c5b160-1649323574175)]

[图片上传失败...(image-5611d6-1649323574175)]

10.基本表达式对象

UserController

@Controller
public class UserController {
    @RequestMapping("/index")
    public String index(HttpServletRequest request, Model model,Integer id){
        model.addAttribute("username","lisi");
        request.getSession().setAttribute("data","sessionData");
        return "index";
    }
}

index.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/inedx
    //获取协议名称
    var scheme = [[${#request.getScheme()}]];
    //获取服务器端口号
    var serverName = [[${#request.getServerName()}]];
    //获取服务器端口号
    var serverPort = [[${#request.getServerPort}]];
    //获取上下文根
    var contextPath = [[${#request.getContextPath()}]];  //现在上下文根为空

    var allPath = scheme+"://"+serverName+":"+serverPort+contextPath;
    alert(allPath);

    var requestURL = [[${#httpServletRequest.requestURL}]]; //http://localhost:8080/index
    var queryString = [[${#httpServletRequest.queryString}]];  //null   获取的参数  //id=101

    alert(requestURL);
    alert(queryString);
</script>
</body>
</html>

11.功能表达式对象(了解)

[图片上传失败...(image-3f9e2b-1649323574174)]

[图片上传失败...(image-e2bf77-1649323574174)]

[图片上传失败...(image-99da71-1649323574174)]

[图片上传失败...(image-fffca7-1649323574174)]

在此我向大家推荐一个架构学习交流圈。交流学习伪鑫:539413949(里面有大量的面试题及答案)里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化、分布式架构等这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值