SpringBoot(页面值,mybatis,PageHelper,静态资源的引用)
目录结构:
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>com.cxb</groupId>
<artifactId>SpringBoot-Thymeleaf</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringBoot-Thymeleaf</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!-- mybatis的分页插件 -->
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
spring:
thymeleaf:
#缓冲的配置
cache: false
check-template: true
check-template-location: true
#开启MVC thymeleaf 视图解析
enabled: true
encoding: utf-8
mode: HTML5
prefix: classpath:/templates/
suffix: .html
#配置数据源
datasource:
url: jdbc:mysql://127.0.0.1:3306/sp?useUnicode=true&characterEncoding=utf8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
#指定mybatis映射文件的地址
mybatis:
#配置文件的路径
#config-location: classpath:mybatis-config.xml
mapper-locations: classpath:mapper/*.xml
# mybatis自动扫描包中的实体类,自动定义别名,别名是类名(首字母大写或小写都可以,一般用小写)
type-aliases-package: com.cxb.model
#pagehelper分页插件配置
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: countSql
package com.cxb.model;
public class User {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package com.cxb.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.cxb.model.User;
@Mapper
public interface UserDao {
@Select("select * from user where id = #{id}")
User findUserById(@Param("id") int id);
@Update("update user set name=#{name}, age=#{age} where id=#{id}")
int updateById(@Param("name") String name,@Param("age") int age,@Param("id") int id);
@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
int saveUser(@Param("name") String name,@Param("age") int age);
//下面的两个方法都是xml中配置的
User findUserByAge(int age);
List<User> findListByName(String name);
List<User> findAllUser();
int saveUserByParm(Map<String,Object> map);
int updateUserById(Map<String,Object> map);
void deleteUserById(int id);
}
package com.cxb.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cxb.dao.UserDao;
import com.cxb.model.User;
@Service
public class UserService {
@Autowired
private UserDao userDao;
public User findUserById(int id) {
return userDao.findUserById(id);
}
/**
* 通过年纪查找单个对象
* @param age
* @return
*/
public User findUserByAge(int age) {
return userDao.findUserByAge(age);
}
/**
* 通过名字查找集合对象
* @param name
* @return
*/
public List<User> findListByName(String name){
return userDao.findListByName(name);
}
/**
* 查询所有的user
* @return
*/
public List<User> findAllUser(){
return userDao.findAllUser();
}
/**
* 新增用户
* @param name
* @param age
* @return
*/
public int saveUserByParm(Map<String,Object> map) {
return userDao.saveUserByParm(map);
}
/**
* 根据id修改该用户信息
* @param name
* @param age
* @return
*/
public int updateUserById(Map<String,Object> map) {
return userDao.updateUserById(map);
}
/**
* 根据id删除用户
* @param id
*/
public void deleteUserById(int id) {
userDao.deleteUserById(id);
}
public int updateById(String name, int age, int id) {
return userDao.updateById(name, age, id);
}
public int saveUser(String name, int age) {
return userDao.saveUser(name, age);
}
}
package com.cxb.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cxb.model.User;
import com.cxb.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
//页面跳转不能使用 @RestController 而是使用@Controller
@Controller
@RequestMapping("/home")
public class HomeController {
@Autowired
private UserService userService;
@RequestMapping(value="/index", method=RequestMethod.GET)
//加了@ResponseBody 就是返回字符串了
public String index(ModelMap map) {
//返回值给页面
map.addAttribute("name", "小石潭记");
return "index";
}
@RequestMapping(value="/userById", method=RequestMethod.GET)
//加了@ResponseBody 就是返回字符串了
public String userById(HttpServletRequest request,ModelMap map) {
String id = request.getParameter("id");
//根据id查询user
User user = userService.findUserById(Integer.parseInt(id));
//返回集合对象给页面
map.addAttribute("user", user);
return "user";
}
@RequestMapping(value="/userByAge", method=RequestMethod.GET)
//加了@ResponseBody 就是返回字符串了
public String userByAge(HttpServletRequest request,ModelMap map) {
String age = request.getParameter("age");
//根据年纪查询user
User user = userService.findUserByAge(Integer.parseInt(age));
//返回集合对象给页面
map.addAttribute("user", user);
return "user";
}
//http://localhost:8080/home/listByName?name=赵云
@RequestMapping(value="/listByName", method=RequestMethod.GET)
//加了@ResponseBody 就是返回字符串了
public String listByName(HttpServletRequest request,ModelMap map) {
String name = request.getParameter("name");
List<User> list = userService.findListByName(name);
//返回集合对象给页面
map.addAttribute("list", list);
return "list";
}
//http://localhost:8080/home/list
@RequestMapping(value="/list", method=RequestMethod.GET)
public String list(ModelMap map) {
//模拟集合
List<User> list = userService.findAllUser();
//返回集合对象给页面
map.addAttribute("list", list);
PageInfo<User> pageInfo=new PageInfo<>(list);
System.out.println(pageInfo);
return "list";
}
@SuppressWarnings("rawtypes")
@RequestMapping(value="/listPage", method=RequestMethod.GET,produces = "application/json; charset=utf-8")
@ResponseBody
public PageInfo listPage() {
/**
* int pageNum, 当前页
* int pageSize, 每页的条数
*/
PageHelper.startPage(2,5);
//模拟集合
List<User> list = userService.findAllUser();
//返回集合对象给页面
PageInfo<User> pageInfo=new PageInfo<>(list);
return pageInfo;
}
@RequestMapping(value="/saveUser", method=RequestMethod.POST)
@ResponseBody
public String saveUser(HttpServletRequest request) {
String name = request.getParameter("name");
String age = request.getParameter("age");
//注解式的保存对象
userService.saveUser(name, Integer.parseInt(age));
Map<String,Object> map =new HashMap<>();
map.put("name", name);
map.put("age", age);
int saveUser = userService.saveUserByParm(map);
return "save success "+saveUser+" record ";
}
@RequestMapping(value="/updateUserById", method=RequestMethod.GET)
@ResponseBody
public String updateUserById(HttpServletRequest request) {
String id = request.getParameter("id");
String name = request.getParameter("name");
String age = request.getParameter("age");
//注解式的修改
// int update = userService.updateById(name, Integer.parseInt(age), Integer.parseInt(id));
Map<String,Object> map=new HashMap<>();
map.put("name", name);
map.put("age", Integer.parseInt(age));
map.put("id", Integer.parseInt(id));
int update = userService.updateUserById(map);
return "update success "+update+" record ";
}
@RequestMapping(value="/deleteUserById", method=RequestMethod.GET)
@ResponseBody
public String deleteUserById(HttpServletRequest request) {
String id = request.getParameter("id");
userService.deleteUserById(Integer.parseInt(id));
return "delete success record";
}
/**
* @return
*/
@RequestMapping(value="/error", method=RequestMethod.GET)
@ResponseBody
public String error() {
return "sorry error";
}
}
package com.cxb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
@SpringBootApplication
//没有连接数据库的时候报错 需要加上这一句
//@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class SpringBootThymeleafApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootThymeleafApplication.class, args);
}
/**
* 这里是为了使用阿里的fastjson 方式一
* @return
*/
@Bean
public HttpMessageConverters fastJsonConverters() {
FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
FastJsonConfig fastConfig=new FastJsonConfig();
fastConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastConverter.setFastJsonConfig(fastConfig);
HttpMessageConverter<?> converter=fastConverter;
return new HttpMessageConverters(converter);
}
}
package com.cxb;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringBootThymeleafApplication.class);
}
}
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.cxb.dao.UserDao">
<!--根据名字查询单个对象-->
<select id="findUserByAge" parameterType="Integer" resultType="User">
select * from user where age = #{age}
</select>
<!--这是返回的集合的属性-->
<resultMap id="userBaseMap" type="User">
<id column="id" property="id" />
<result column="name" property="name" />
<result column="age" property="age" />
</resultMap>
<!--根据名字查询集合对象-->
<select id="findListByName" resultMap="userBaseMap" parameterType="java.lang.String" >
select * from user where name = #{name}
</select>
<!--根据名字查询集合对象-->
<select id="findAllUser" resultMap="userBaseMap">
select * from user
</select>
<!--插入一个对象-->
<insert id="saveUserByParm" parameterType="HashMap" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user(name, age) VALUES(#{name}, #{age})
</insert>
<!--修改对象 -->
<update id="updateUserById" parameterType="HashMap">
update user set name=#{name}, age=#{age} where id=#{id}
</update>
<!--根据id删除对象 -->
<delete id="deleteUserById" parameterType="Integer">
delete from user where id =#{id}
</delete>
</mapper>
style.css
.login-title{
font-size: 30px;
color: red;
}
home.js
/*alert("1");*/
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index thymeleaf</title>
<link rel="stylesheet" href="/css/style.css"/>
<script src="/js/home.js"></script>
</head>
<body>
<h1>HELLO INDEX THYMELEAF</h1>
你好,<h2 th:text="${name}"></h2>
<p class="login-title">哈哈 NBA</p>
</body>
</html>
list.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index thymeleaf</title>
<link rel="stylesheet" href="/css/style.css"/>
<script src="/js/home.js"></script>
</head>
<body>
<h1>循环显示集合</h1>
<!-- <a href="user.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a> -->
<table border="1">
<tr>
<th>ID</th>
<th>名字</th>
<th>年纪</th>
<th>操作</th>
</tr>
<tr th:each="user : ${list}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
<td>
<!--带参数跳转页面 -->
<a href="user.html" th:href="@{/home/userById(id=${user.id})}">查看详情</a>
</td>
</tr>
</table>
<hr>
<a th:href="@{http://www.baidu.com}">绝对路径(百度)</a>
</body>
</html>
user.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index thymeleaf</title>
<link rel="stylesheet" href="/css/style.css"/>
<script src="/js/home.js"></script>
</head>
<body>
<h1>显示单个对象的属性值</h1>
ID:<input type="text" name="id" value="James Carrot" th:value="${user.id}" />
NAME:<input type="text" name="name" value="James Carrot" th:value="${user.name}" />
AGE:<input type="text" name="age" value="James Carrot" th:value="${user.age}" />
</body>
</html>
http://localhost:8080/home/listPage
http://localhost:8080/home/list