Thymeleaf的对象

Thymeleaf是直接支持访问Servlet web的原生资源,HttpServletRequest HttpServletResponse HttpSession ServletContext.

#request:获取HttpServletRequest对象
#response:获取HttpServletResponse 对象
#session:获取HttpSession 对象
#servletContext:获取ServletContext对象


1.Handler

@GetMapping("/servlet")
public String servlet(HttpServletRequest request){
    request.setAttribute("valye","request");
    request.getSession().setAttribute("valye","request");
    request.getServletContext().setAttribute("valye","request");
    return "test";
}


<!--request-->
        <p th:text="${#request.getAttribute('value')}"></p>
        <p th:text="${#session.getAttribute('value')}"></p>
        <p th:text="${#servletContext.getAttribute('value')}"></p>
        <p th:text="${#reponse}"></p>

Thymeleaf支持直接访问session,相对于

${#servletContext.getAttribute('value')}也可以简化为${value}


Thymeleaf的内置对象

  • dates;日期格式化
  • calendars:日期操作
  • numbers:数字格式化
  • Strings:字符格式化
  • bools:boolean
  • arrays:数组内置对象
  • lists:list集合内置对象
  • sets:set集合内置对象
  • maps;map集合内置对象

    @GetMapping("/uniltity")
    public ModelAndView uniltity(){
        ModelAndView modelAndView =new ModelAndView();
        modelAndView.setViewName("test");
        modelAndView.addObject("date",new Date());
        Calendar calendar =Calendar.getInstance();
        calendar.set(2020,1,1);
        modelAndView.addObject("calendar",calendar);
        modelAndView.addObject("number",0.06);
        modelAndView.addObject("string","Springboot");
        modelAndView.addObject("boolean",true);
        modelAndView.addObject("array",Arrays.asList("张三","李四","王五"));
        List<User> users = Arrays.asList(new User("张三",1),new User("李四",2),new User("王五",3));
        modelAndView.addObject("list",users);
        Set<User> set =new HashSet<>();
        set.add(new User("张三",1));
        set.add(new User("李四",2));
        modelAndView.addObject("set",set);
        Map<Integer,User> map=new HashMap<>();
        map.put(1,new User("张三",1));
        map.put(2,new User("李四",2));
        modelAndView.addObject("map",map);
        return modelAndView;
    }
date:格式化<span th:text="${#dates.format(date,'yyy-mm-dd')}"></span><br>
当前时间:<span th:text="${#dates.cteateToday()}"></span><br>
Calendar格式化:<span th:text="${#calendars.format(calendar,'yyyy-mm-dd')}"></span><br>
number百分比格式化:<span th:text="${#numbers.formatPercent(number,2,2)}"></span><br>
name是否为空:<span th:text="${#strings.isTmpty(string)}"></span><br>
name的长度:<span th:text="${#strings.length(string)}"></span><br>
name的拼接:<span th:text="${#strings.concat('Good',string)}"></span><br>
boolen是否为true:<span th:text="${#bools.isTrue(boolean)}"></span><br>
arrys的长度:<span th:text="${#arrays.length(array)}"></span><br>
array是否包含张三:<span th:text="${#arrays.contains(array,'张三')}"></span><br>
list是否为空:<span th:text="${#list.isEmpty(list)}"></span><br>
list的长度:<span th:text="${#list.size(list)}"></span><br>
Set是否为空:<span th:text="${#sets.isEmpty(set)}"></span><br>
Set的长度:<span th:text="${#sets.size(set)}"></span><br>
Map是否为空:<span th:text="${#maps.isEmpty(map)}"></span><br>
Map是的长度:<span th:text="${#maps.size(map)}"></span><br>

Spring boot 整合JDBC Template

JDBC Template是spring自带的一个JDBC的模版组件,底层实现了对JDBC的封装,用法和Mybatis类似,需要开发者定义SQL语句,JDBC Template帮助我们完成数据库的连接,SQL的执行,结果集的封装

不足之处灵活性不如Mybatis,因为Mybatis是直接卸载XML王文建中,更有利于扩展和维护,JDBC Template是以硬编码的形式将SQL直接写在java代码中,不利于扩展和维护

1.pom.xml

<?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>org.example</groupId>
    <artifactId>soringbootdo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <artifactId>spring-boot-starter-web</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.2.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-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

2.实体类:

package com.southwind.entity;

import lombok.Data;

@Data
public class User {
    private Integer id;
    private  String name;
    private  Integer money;
}

3.Repository

接口:

package com.southwind.Repository;

import com.southwind.entity.User;

import java.util.List;

public interface UserRepository {
    public List<User> findAll();
    public  User finById(Integer id);
    public int save (User user);
    public  int update(User user);
    public  int delete(Integer id);
}
package com.southwind.Repository.impl;

import com.southwind.Repository.UserRepository;
import com.southwind.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;


import java.util.List;
@Repository
public class UserRepositoryImpl implements UserRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public List<User> findAll() {
        return jdbcTemplate.query(
                "select * from people",
                new BeanPropertyRowMapper<>(User.class)
        );
    }

    public User finById(Integer id) {

        return jdbcTemplate.queryForObject(
                "select * from people where id=?",
                new Object[]{id},
                new BeanPropertyRowMapper<>(User.class)
        );
    }

    public int save(User user) {

        return jdbcTemplate.update(
                "insert into people(id,name,money) values (?,?,?)",
                user.getId(),
                user.getName(),
                user.getMoney()

        );
    }

    public int update(User user) {

        return jdbcTemplate.update(
                "update people set name=?,money=? where  id=?",
                user.getName(),
                user.getMoney(),
                user.getId()
        );
    }

    public int delete(Integer id) {

        return jdbcTemplate.update(
                "delete from people where id=?",
                id

        );
    }
}

4.Handeler

package com.southwind.Controller;

import com.southwind.Repository.UserRepository;
import com.southwind.Repository.impl.UserRepositoryImpl;
import com.southwind.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserHandler {
    @Autowired
    private UserRepositoryImpl userRepository;
    @GetMapping("/findall")
    @ResponseBody
    public List<User> findall(){
        return userRepository.findAll();
    }

    @GetMapping("/findbyid/{id}")
    @ResponseBody
    public User findbyid(@PathVariable("id")Integer id) {
        return userRepository.finById(id);
    }

    @PostMapping("/save")
    @ResponseBody
    public int save(@RequestBody User user){
        return userRepository.save(user);
    }
    @PutMapping("/update")
    @ResponseBody
    public int update(@RequestBody User user){
        return userRepository.update(user);
    }
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public int delete(@PathVariable Integer id){
        return userRepository.delete(id);
    }
}

方法

query:

public <T> List<T> query(String sql, RowMapper<T> rowMapper) throws DataAccessException {
    return (List)result(this.query((String)sql, (ResultSetExtractor)(new RowMapperResultSetExtractor(rowMapper))));
}

RowMapper是一个接口,作用是分析结果集,将JDBC查询的ResultSet对象转化成对应的POJO

queryForObjiect(String sql,Object[] args, RowMapper rowMapper)

该方法查询一条数据,并将结果封装成一个POJO

update

public int update(String sql, @Nullable Object... args) throws DataAccessException {
    return this.update(sql, this.newArgPreparedStatementSetter(args));
}

增加、修改、删除都可以用这个方法

posted on 2022-06-23 23:02  Steam残酷  阅读(250)  评论(0)    收藏  举报