一、目录结构
二、代码
1、ConfigInfo
1 package cn.bijian.springboot.config; 2 3 import org.springframework.boot.context.properties.ConfigurationProperties; 4 import org.springframework.stereotype.Component; 5 6 @Component 7 @ConfigurationProperties(prefix = "school") 8 public class ConfigInfo { 9 private String name; 10 private String website; 11 12 public String getName() { 13 return name; 14 } 15 16 public void setName(String name) { 17 this.name = name; 18 } 19 20 public String getWebsite() { 21 return website; 22 } 23 24 public void setWebsite(String website) { 25 this.website = website; 26 } 27 }
2、InterceptorConfig
1 package cn.bijian.springboot.config; 2 3 import cn.bijian.springboot.Interceptor.CustomerInterceptor; 4 import org.springframework.context.annotation.Configuration; 5 import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 6 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 7 8 @Configuration 9 public class InterceptorConfig implements WebMvcConfigurer { 10 @Override 11 public void addInterceptors(InterceptorRegistry registry) { 12 //定义拦截的路径 13 String[] addPath = { 14 "/customer/**" 15 }; 16 //定义不需要拦截的路径 17 String[] excludePath = { 18 "/customer/error", 19 "/customer/verifyRealName" 20 }; 21 registry.addInterceptor(new CustomerInterceptor()).addPathPatterns(addPath).excludePathPatterns(excludePath); 22 } 23 }
3、ServletConfig
1 package cn.bijian.springboot.config; 2 3 import cn.bijian.springboot.servlet.MyServlet; 4 import org.springframework.boot.web.servlet.ServletRegistrationBean; 5 import org.springframework.context.annotation.Bean; 6 import org.springframework.context.annotation.Configuration; 7 8 /* 9 字符编码 10 */ 11 @Configuration 12 public class ServletConfig { 13 @Bean 14 public ServletRegistrationBean createServletRegistrationBean(){ 15 ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new MyServlet(), "/myServlet"); 16 return servletRegistrationBean; 17 } 18 }
4、CustomerInterceptor
1 package cn.bijian.springboot.Interceptor; 2 3 import org.springframework.web.servlet.HandlerInterceptor; 4 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 8 /* 9 拦截器 10 */ 11 public class CustomerInterceptor implements HandlerInterceptor { 12 @Override 13 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 14 System.out.println("---------------拦截规则--------------"); 15 Integer code = (Integer) request.getSession().getAttribute("code"); 16 if (code == null){ 17 response.sendRedirect(request.getContextPath()+"/customer/error"); 18 return false; 19 } 20 return true; 21 } 22 }
5、AccountMapper
1 package cn.bijian.springboot.mapper; 2 3 import cn.bijian.springboot.model.Account; 4 import org.apache.ibatis.annotations.Mapper; 5 6 //@Mapper 7 public interface AccountMapper { 8 int deleteByPrimaryKey(Integer id); 9 10 int insert(Account record); 11 12 int insertSelective(Account record); 13 14 Account selectByPrimaryKey(Integer id); 15 16 int updateByPrimaryKeySelective(Account record); 17 18 int updateByPrimaryKey(Account record); 19 20 Long selectCountAllAccount(); 21 }
6、Account
1 package cn.bijian.springboot.model; 2 3 public class Account { 4 private Integer id; 5 6 private String name; 7 8 private Double money; 9 10 public Integer getId() { 11 return id; 12 } 13 14 public void setId(Integer id) { 15 this.id = id; 16 } 17 18 public String getName() { 19 return name; 20 } 21 22 public void setName(String name) { 23 this.name = name; 24 } 25 26 public Double getMoney() { 27 return money; 28 } 29 30 public void setMoney(Double balance) { 31 this.money = balance; 32 } 33 34 @Override 35 public String toString() { 36 return "Account{" + 37 "id=" + id + 38 ", name='" + name + '\'' + 39 ", money=" + money + 40 '}'; 41 } 42 }
7、AccountService
1 package cn.bijian.springboot.service; 2 3 import cn.bijian.springboot.model.Account; 4 5 public interface AccountService { 6 Account findAccountById(Integer id); 7 8 int updateAccount(Account account); 9 10 Long countAllAccount(); 11 }
8、AccountServiceImpl
1 package cn.bijian.springboot.service.Impl; 2 3 import cn.bijian.springboot.mapper.AccountMapper; 4 import cn.bijian.springboot.model.Account; 5 import cn.bijian.springboot.service.AccountService; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.data.redis.core.RedisTemplate; 8 import org.springframework.data.redis.serializer.StringRedisSerializer; 9 import org.springframework.stereotype.Service; 10 import org.springframework.transaction.annotation.Transactional; 11 12 import java.util.concurrent.TimeUnit; 13 14 @Service("accountService") 15 public class AccountServiceImpl implements AccountService { 16 @Autowired 17 private AccountMapper accountMapper; 18 @Autowired 19 private RedisTemplate<Object,Object> redisTemplate; 20 21 @Override 22 public Account findAccountById(Integer id) { 23 return accountMapper.selectByPrimaryKey(id); 24 } 25 26 @Override 27 @Transactional 28 public int updateAccount(Account account) { 29 int res = accountMapper.updateByPrimaryKeySelective(account); 30 System.out.println("更新结果"+res); 31 // int i = 10/0; 32 return res; 33 } 34 35 @Override 36 public Long countAllAccount() { 37 //设置key的序列化方式 38 redisTemplate.setKeySerializer(new StringRedisSerializer()); 39 Long count = (Long) redisTemplate.opsForValue().get("countAllAccount"); 40 if (count == null){ 41 count = accountMapper.selectCountAllAccount(); 42 redisTemplate.opsForValue().set("countAllAccount",count,15, TimeUnit.SECONDS); 43 } 44 return count; 45 } 46 }
9、MyServlet
package cn.bijian.springboot.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().print("您好,世界!"); resp.setContentType("text/html;charset=utf-8"); resp.getWriter().flush(); resp.getWriter().close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
10、AccountController
1 package cn.bijian.springboot.web; 2 3 import cn.bijian.springboot.model.Account; 4 import cn.bijian.springboot.service.AccountService; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.ui.Model; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 import org.springframework.web.bind.annotation.ResponseBody; 10 import org.springframework.web.bind.annotation.RestController; 11 12 //@Controller 13 @RestController //@Controller与@ResponseBody的组合注解 14 @RequestMapping("/account") 15 public class AccountController { 16 @Autowired 17 private AccountService accountService; 18 /* 19 mybatis反向工程 20 */ 21 @RequestMapping("/testAccount") 22 public Object testAccount(Model model){ 23 Account account = accountService.findAccountById(1); 24 return account; 25 } 26 /* 27 事务管理 28 */ 29 @RequestMapping("/testUpdateAccount") 30 public @ResponseBody Object testUpdateAccount(){ 31 int res = 0; 32 try { 33 Account account = new Account(); 34 account.setId(1); 35 account.setName("aaaa"); 36 res = accountService.updateAccount(account); 37 } catch (Exception e) { 38 e.printStackTrace(); 39 return "fail"; 40 } 41 return res; 42 } 43 }
11、CustomerController
1 package cn.bijian.springboot.web; 2 3 import org.springframework.web.bind.annotation.RequestMapping; 4 import org.springframework.web.bind.annotation.RestController; 5 6 import javax.servlet.http.HttpServletRequest; 7 8 /* 9 拦截器 10 */ 11 @RestController 12 @RequestMapping("/customer") 13 public class CustomerController { 14 @RequestMapping("/account") 15 public Object queryAccount(){ 16 return "余额:100元"; 17 } 18 19 @RequestMapping("/verifyRealName") 20 public Object verifyRealName(HttpServletRequest request){ 21 request.getSession().setAttribute("code",1); 22 return "顾客实名验证成功!"; 23 } 24 25 @RequestMapping("/error") 26 public Object error(){ 27 return "顾客没有实名验证!"; 28 } 29 }
12、LogController
1 package cn.bijian.springboot.web; 2 3 import cn.bijian.springboot.model.Account; 4 import cn.bijian.springboot.service.AccountService; 5 import lombok.extern.slf4j.Slf4j; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 import org.springframework.web.bind.annotation.RestController; 9 10 @Slf4j 11 @RestController 12 @RequestMapping("/log") 13 public class LogController { 14 @Autowired 15 private AccountService accountService; 16 17 @RequestMapping("/findAccountById") 18 public Object findAccountById(){ 19 log.info("-----------查询开始----------------"); 20 Account account = accountService.findAccountById(1); 21 log.info("-----------查询结束----------------"); 22 23 return "findAccountById:"+account; 24 } 25 }
13、RedisController
1 package cn.bijian.springboot.web; 2 3 import cn.bijian.springboot.service.AccountService; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.RestController; 7 8 9 @RestController 10 @RequestMapping("/account") 11 public class RedisController { 12 @Autowired 13 private AccountService accountService; 14 15 @RequestMapping("/countAllAccount") 16 public Object countAllAccount(){ 17 Long count = accountService.countAllAccount(); 18 return "学生总人数:" + count; 19 } 20 }
14、RestfulController
1 package cn.bijian.springboot.web; 2 3 import cn.bijian.springboot.service.AccountService; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.web.bind.annotation.*; 6 7 import java.util.HashMap; 8 import java.util.Map; 9 10 @RestController 11 @RequestMapping("/account") 12 public class RestfulController { 13 @Autowired 14 private AccountService accountService; 15 16 @PostMapping("/addAccount/{name}/{money}") 17 public Object addAccount(@PathVariable("name") String name,@PathVariable("money") Double money){ 18 Map<String,Object> map = new HashMap<>(); 19 map.put("name",name); 20 map.put("money",money); 21 return map; 22 } 23 24 @DeleteMapping("/deleteAccount/{id}") 25 public Object deleteAccount(@PathVariable("id") Integer id){ 26 return "删除学生:"+id; 27 } 28 29 @PutMapping("/updateAccount/{id}") 30 public Object updateAccount(@PathVariable("id") Integer id){ 31 return "修改学生:"+id; 32 } 33 34 @GetMapping("/findAccount/{id}") 35 public Object findAccount(@PathVariable("id") Integer id){ 36 return "查询学生:"+id; 37 } 38 39 /* 40 请求冲突问题: 41 1、改路径 2、改请求方式 42 RESTful原则: 43 1、增post请求 删delete请求 改put请求 查get请求 44 2、请求路径不要出现动词 45 eg: /boot/order/1021/1 推荐 46 /boot/queryOrder/1021/1 不推荐 47 3、分页、排序等操作,不需要使用斜杠传参数 48 eg: /boot/orders?page=1&sort=desc 49 */ 50 }
15、ThymeleafController
1 package cn.bijian.springboot.web; 2 3 import cn.bijian.springboot.model.Account; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.ui.Model; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 8 import javax.servlet.http.HttpServletRequest; 9 import java.util.ArrayList; 10 import java.util.List; 11 12 @Controller 13 @RequestMapping("/thymeleaf") 14 public class ThymeleafController { 15 /* 16 Thymeleaf入门 17 */ 18 @RequestMapping("/index") 19 public String index(Model model){ 20 model.addAttribute("data","springboot集成Thymeleaf模板"); 21 return "index"; 22 } 23 24 /* 25 标准变量表达式 th:text="" 26 */ 27 @RequestMapping("/account") 28 public String account(Model model){ 29 Account account = new Account(); 30 account.setId(1); 31 account.setName("aaa"); 32 account.setMoney(100d); 33 model.addAttribute("account",account); 34 return "account"; 35 } 36 37 /* 38 URL表达式 @{...} 39 */ 40 @RequestMapping("/url") 41 public String url(Model model){ 42 Account account = new Account(); 43 account.setId(1); 44 account.setName("aaa"); 45 account.setMoney(100d); 46 model.addAttribute("account",account); 47 return "url"; 48 } 49 @RequestMapping("/info") 50 public String info(Integer id){ 51 System.out.println("账户编号:"+id); 52 return "success"; 53 } 54 55 /* 56 th:each属性 57 */ 58 @RequestMapping("/list") 59 public String list(Model model){ 60 List<Account> accounts = new ArrayList<>(); 61 for (int i = 0; i < 5; i++) { 62 Account account = new Account(); 63 account.setId(1); 64 account.setName("aaa"); 65 account.setMoney(100d); 66 accounts.add(account); 67 } 68 model.addAttribute("accounts",accounts); 69 return "list"; 70 } 71 72 /* 73 th:if、th:unless、th:switch、th:case属性 74 */ 75 @RequestMapping("/condition") 76 public String condition(Model model){ 77 Account account1 = null; 78 model.addAttribute("account1",account1); 79 80 Account account2 = new Account(); 81 account2.setId(12); 82 account2.setName("fff"); 83 account2.setMoney(120d); 84 model.addAttribute("account2",account2); 85 86 model.addAttribute("sex",1); 87 88 return "condition"; 89 } 90 }
16、UserController
1 package cn.bijian.springboot.web; 2 3 import cn.bijian.springboot.config.ConfigInfo; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.beans.factory.annotation.Value; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.ui.Model; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 import org.springframework.web.bind.annotation.ResponseBody; 10 11 @Controller 12 @RequestMapping("/user") 13 public class UserController { 14 /* 15 入门 16 */ 17 @RequestMapping("/say") 18 public @ResponseBody String say(){ 19 return "hello,springboot!"; 20 } 21 22 /* 23 自定义配置项(1) 24 */ 25 @Value("${school.name}") 26 private String schoolName; 27 @Value("${school.website}") 28 private String schoolWeb; 29 @RequestMapping("/testCustomize1") 30 public @ResponseBody String testCustomize1(){ 31 return schoolName+"->"+schoolWeb; 32 } 33 34 /* 35 自定义配置项(2) 36 */ 37 @Autowired 38 private ConfigInfo configInfo; 39 @RequestMapping("/testCustomize2") 40 public @ResponseBody String testCustomize2(){ 41 return configInfo.getName()+"->"+configInfo.getWebsite(); 42 } 43 44 /* 45 前端使用JSP页面 46 */ 47 @RequestMapping("/testJSP") 48 public String testJSP(Model model){ 49 model.addAttribute("data","前端使用JSP页面"); 50 return "index"; 51 } 52 /* 53 拦截器 54 */ 55 }
17、Application
1 package cn.bijian.springboot; 2 3 import org.mybatis.spring.annotation.MapperScan; 4 import org.springframework.boot.SpringApplication; 5 import org.springframework.boot.autoconfigure.SpringBootApplication; 6 import org.springframework.transaction.annotation.EnableTransactionManagement; 7 8 @SpringBootApplication 9 @MapperScan("cn.bijian.springboot.mapper") 10 @EnableTransactionManagement 11 public class Application { 12 public static void main(String[] args) { 13 SpringApplication.run(Application.class, args); 14 } 15 16 }
18、AccountMapper.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 3 <mapper namespace="cn.bijian.springboot.mapper.AccountMapper"> 4 <resultMap id="BaseResultMap" type="cn.bijian.springboot.model.Account"> 5 <id column="id" jdbcType="INTEGER" property="id" /> 6 <result column="NAME" jdbcType="VARCHAR" property="name" /> 7 <result column="money" jdbcType="DOUBLE" property="money" /> 8 </resultMap> 9 <sql id="Base_Column_List"> 10 id, NAME, money 11 </sql> 12 <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> 13 select 14 <include refid="Base_Column_List" /> 15 from account 16 where id = #{id,jdbcType=INTEGER} 17 </select> 18 <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> 19 delete from account 20 where id = #{id,jdbcType=INTEGER} 21 </delete> 22 <insert id="insert" parameterType="cn.bijian.springboot.model.Account"> 23 insert into account (id, NAME, money 24 ) 25 values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{money,jdbcType=DOUBLE} 26 ) 27 </insert> 28 <insert id="insertSelective" parameterType="cn.bijian.springboot.model.Account"> 29 insert into account 30 <trim prefix="(" suffix=")" suffixOverrides=","> 31 <if test="id != null"> 32 id, 33 </if> 34 <if test="name != null"> 35 NAME, 36 </if> 37 <if test="money != null"> 38 money, 39 </if> 40 </trim> 41 <trim prefix="values (" suffix=")" suffixOverrides=","> 42 <if test="id != null"> 43 #{id,jdbcType=INTEGER}, 44 </if> 45 <if test="name != null"> 46 #{name,jdbcType=VARCHAR}, 47 </if> 48 <if test="money != null"> 49 #{money,jdbcType=DOUBLE}, 50 </if> 51 </trim> 52 </insert> 53 <update id="updateByPrimaryKeySelective" parameterType="cn.bijian.springboot.model.Account"> 54 update account 55 <set> 56 <if test="name != null"> 57 NAME = #{name,jdbcType=VARCHAR}, 58 </if> 59 <if test="money != null"> 60 money = #{money,jdbcType=DOUBLE}, 61 </if> 62 </set> 63 where id = #{id,jdbcType=INTEGER} 64 </update> 65 <update id="updateByPrimaryKey" parameterType="cn.bijian.springboot.model.Account"> 66 update account 67 set NAME = #{name,jdbcType=VARCHAR}, 68 money = #{money,jdbcType=DOUBLE} 69 where id = #{id,jdbcType=INTEGER} 70 </update> 71 <select id="selectCountAllAccount" resultType="java.lang.Long"> 72 select 73 count(*) 74 from 75 account 76 </select> 77 </mapper>
19、account.html
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>account</title> 6 </head> 7 <body> 8 9 <span th:text="${account.id}"></span> 10 <span th:text="${account.name}"></span> 11 <span th:text="${account.money}"></span> 12 13 </body> 14 </html>
20、condition.html
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>condition</title> 6 </head> 7 <body> 8 <div th:if="${account1 eq null}"> 9 <input th:name="account" th:value="1"> 10 </div> 11 12 <div th:unless="${account2 eq null}"> 13 <input th:name="account" th:value="${account2.name}"> 14 </div> 15 16 <div th:switch="${sex}"> 17 <span th:case="1">性别男</span><br/> 18 <span th:case="0">性别女</span><br/> 19 <span th:case="*">保密</span> 20 </div> 21 </body> 22 </html>
21、index.html
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>index</title> 6 </head> 7 <body> 8 9 <span th:text="${data}"></span> 10 </body> 11 </html>
22、info.html
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>info</title> 6 </head> 7 <body> 8 9 </body> 10 </html>
23、list.html
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>list</title> 6 </head> 7 <body> 8 <div th:each="account,accountStat:${accounts}"> 9 <span th:text="${accountStat.index}"></span> 10 <span th:text="${account.id}"></span> 11 <span th:text="${account.name}"></span> 12 <span th:text="${account.money}"></span> 13 </div> 14 </body> 15 </html>
24、success.html
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>success</title> 6 </head> 7 <body> 8 <h2>success</h2> 9 </body> 10 </html>
25、url.html
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>url</title> 6 <!--自动添加上下文,避免404找不到--> 7 <script th:src="@{/jquery.min.js}"></script> 8 9 <a th:onclick="'show('+${account.id}+')'" th:style="'color:red;'">显示id</a> 10 <script type="text/javascript"> 11 function show(id) { 12 alert(id) 13 } 14 </script> 15 16 </head> 17 <body> 18 <a th:href="@{'http://localhost:8080/springboot/thymeleaf/info'}">绝对路径(无参数)</a> 19 <a th:href="@{'http://localhost:8080/springboot/thymeleaf/info?id='+${account.id}}">绝对路径(有参数)</a> 20 21 <a th:href="@{'/thymeleaf/info'}">相对路径(无参数)</a> 22 <a th:href="@{'/thymeleaf/info?id='+${account.id}}">相对路径(有参数)</a> 23 <a th:href="@{/thymeleaf/info(id=${account.id})}">相对路径2(有参数)</a> 24 25 <form th:action="@{'/thymeleaf/info?id='+${account.id}}" th:method="post"> 26 用户名:<input type="text" name="username"> 27 <button name="btn" type="submit">提交</button> 28 </form> 29 30 <span th:id="${account.id}" th:name="${account.name}" th:type="text">aaa</span> 31 32 <input th:value="${account.name}" type="hidden"> 33 34 <!--可以给没有定义的属性赋值--> 35 <span th:attr="zhangsan=${account.name}">attr</span> 36 37 <input th:text="${account.name}" th:value="${account.money}"> 38 39 </body> 40 </html>
26、application.properties
1 #激活开发环境 2 spring.profiles.active=dev 3 4 #激活测试环境 5 #spring.profiles.active=test 6 7 #激活生产环境 8 #spring.profiles.active=product
27、application-dev.properties
1 # 开发环境 2 server.port=8080 3 server.servlet.context-path=/springboot 4 #自定义配置项 5 school.name=aaa 6 school.website=http://www.baidu.com 7 #配置SpringMVC视图解析器,其中/表示目录为src/main/webapp 8 spring.mvc.view.prefix=/ 9 spring.mvc.view.suffix=.jsp 10 #配置数据库连接信息 11 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 12 spring.datasource.url=jdbc:mysql://localhost:3306/spring?serverTimezone=UTC 13 spring.datasource.username=root 14 spring.datasource.password=123456 15 #指定Mybatis映射文件的路径 16 mybatis.mapper-locations=classpath:mapper/*.xml 17 #配置redis连接信息 18 spring.redis.host=localhost 19 spring.redis.port=6379 20 #字符编码设置 21 server.servlet.encoding.enabled=true 22 server.servlet.encoding.force=true 23 server.servlet.encoding.charset=UTF-8 24 #日志文件配置 25 logging.config=classpath:logging-config.xml 26 #thymeleaf页面的缓存开关,默认true开启,建议开发阶段关闭,目的实时看到页面 27 spring.thymeleaf.cache=false 28 spring.thymeleaf.prefix=classpath:/templates/ 29 spring.thymeleaf.suffix=.html
28、application-product.properties
1 # 生产环境 2 server.port=9090 3 server.servlet.context-path=/springboot-product
29、application-test.properties
1 # 测试环境 2 server.port=8090 3 server.servlet.context-path=/springboot-test
30、logging-config.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!-- 日志级别从低到高分为 TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果 3 设置为 WARN,则低于 WARN 的信息都不会输出 --> 4 <!-- scan:当此属性设置为 true 时,配置文件如果发生改变,将会被重新加载,默认值为 5 true --> 6 <!-- scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认 7 单位是毫秒。当 scan 为 true 时,此属性生效。默认的时间间隔为 1 分钟。 --> 8 <!-- debug:当此属性设置为 true 时,将打印出 logback 内部日志信息,实时查看 logback 9 运行状态。默认值为 false。通常不打印 --> 10 <configuration scan="true" scanPeriod="10 seconds"> 11 <!--输出到控制台--> 12 <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> 13 <!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息--> 14 <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> 15 <level>debug</level> 16 </filter> 17 <encoder> 18 <Pattern>%date [%-5p] [%thread] %logger{60} [%file : %line] %msg%n</Pattern> 19 <!-- 设置字符集 --> 20 <charset>UTF-8</charset> 21 </encoder> 22 </appender> 23 24 <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> 25 <!--<File>/home/log/out.log</File>--> 26 <File>D:/IdeaProjects/springboot_review_1/log/out.log</File> 27 <encoder> 28 <pattern>%date [%-5p] %thread %logger{60} [%file : %line] %msg%n</pattern> 29 </encoder> 30 <rollingPolicy 31 class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> 32 <!-- 添加.gz 历史日志会启用压缩 大大缩小日志文件所占空间 --> 33 <!--<fileNamePattern>/home/log/out.log.%d{yyyy-MM-dd}.log</fileNam 34 ePattern>--> 35 <fileNamePattern>D:/IdeaProjects/springboot_review_1/log/out.log.%d{yyyy-MM-dd}.log</fileNamePattern> 36 <maxHistory>30</maxHistory><!-- 保留 30 天日志 --> 37 </rollingPolicy> 38 </appender> 39 40 <logger name="cn.bijian.springboot.mapper" level="DEBUG" /> 41 42 <root level="INFO"> 43 <appender-ref ref="CONSOLE"/> 44 <appender-ref ref="FILE"/> 45 </root> 46 </configuration>
31、index.jsp
1 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 3 <html> 4 <head> 5 <title>index</title> 6 </head> 7 <body> 8 <h3>${data}</h3> 9 </body> 10 </html>
32、GeneratorMapper.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE generatorConfiguration 3 PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 4 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> 5 <generatorConfiguration> 6 <!-- 指定连接数据库的 JDBC 驱动包所在位置,指定到你本机的完整路径 --> 7 <classPathEntry location="D:\java\chajian\mysql-connector-java-8.0.23.jar"/> 8 9 <!-- 配置 table 表信息内容体,targetRuntime 指定采用 MyBatis3 的版本 --> 10 <context id="tables" targetRuntime="MyBatis3"> 11 <!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 --> 12 <commentGenerator> 13 <property name="suppressAllComments" value="true"/> 14 <!-- <property name="suppressAllComments" value="false" />--> 15 </commentGenerator> 16 <!-- 配置数据库连接信息 --> 17 <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" 18 connectionURL="jdbc:mysql://localhost:3306/spring?serverTimezone=UTC" 19 userId="root" 20 password="123456"> 21 </jdbcConnection> 22 <!-- 生成model类,targetPackage指定model类的包名,targetProject指定生成的model放在eclipse的哪个工程下面--> 23 <javaModelGenerator targetPackage="cn.bijian.springboot.model" targetProject="src/main/java"> 24 <property name="enableSubPackages" value="false"/> 25 <property name="trimStrings" value="false"/> 26 </javaModelGenerator> 27 <!--生成MyBatis的Mapper.xml文件,targetPackage指定mapper.xml文件的包名,targetProject指定生成的mapper.xml放在eclipse的哪个工程下面--> 28 <sqlMapGenerator targetPackage="cn.bijian.springboot.mapper" targetProject="src/main/java"> 29 <property name="enableSubPackages" value="false"/> 30 </sqlMapGenerator> 31 <!--生成MyBatis的Mapper接口类文件,targetPackage指定Mapper接口类的包名,targetProject指定生成的Mapper接口放在eclipse的哪个工程下面--> 32 <javaClientGenerator type="XMLMAPPER" targetPackage="cn.bijian.springboot.mapper" targetProject="src/main/java"> 33 <property name="enableSubPackages" value="false"/> 34 </javaClientGenerator> 35 <!-- 数据库表名及对应的 Java 模型类名 --> 36 <table tableName="account" domainObjectName="Account" 37 enableCountByExample="false" 38 enableUpdateByExample="false" 39 enableDeleteByExample="false" 40 enableSelectByExample="false" 41 selectByExampleQueryId="false"/> 42 </context> 43 </generatorConfiguration>
33、pom.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 <modelVersion>4.0.0</modelVersion> 5 <parent> 6 <groupId>org.springframework.boot</groupId> 7 <artifactId>spring-boot-starter-parent</artifactId> 8 <version>2.3.10.RELEASE</version> 9 <relativePath/> <!-- lookup parent from repository --> 10 </parent> 11 <groupId>cn.bijian.springboot</groupId> 12 <artifactId>springboot_review_1</artifactId> 13 <version>0.0.1-SNAPSHOT</version> 14 <name>springboot_review_1</name> 15 <description>Demo project for Spring Boot</description> 16 <properties> 17 <java.version>1.8</java.version> 18 </properties> 19 <dependencies> 20 <dependency> 21 <groupId>org.springframework.boot</groupId> 22 <artifactId>spring-boot-starter-web</artifactId> 23 </dependency> 24 25 <dependency> 26 <groupId>org.springframework.boot</groupId> 27 <artifactId>spring-boot-starter-test</artifactId> 28 <scope>test</scope> 29 </dependency> 30 <!--解决@ConfigurationProperties注解出现的警告问题--> 31 <dependency> 32 <groupId>org.springframework.boot</groupId> 33 <artifactId>spring-boot-configuration-processor</artifactId> 34 </dependency> 35 <!--!!!!!!!!!!!!!!!!!!!!!!!!前端使用JSP!!!!!!!!!!!!!!!!!!!!!!!!!!!--> 36 <!--引入SpringBoot内置的Tomcat对JSP的解析包,如果只是使用JSP页面可以只添加该依赖--> 37 <dependency> 38 <groupId>org.apache.tomcat.embed</groupId> 39 <artifactId>tomcat-embed-jasper</artifactId> 40 </dependency> 41 <!--如果需要使用servlet必须添加以下两个依赖--> 42 <dependency> 43 <groupId>javax.servlet</groupId> 44 <artifactId>javax.servlet-api</artifactId> 45 </dependency> 46 <dependency> 47 <groupId>javax.servlet.jsp</groupId> 48 <artifactId>javax.servlet.jsp-api</artifactId> 49 <version>2.3.1</version> 50 </dependency> 51 <!--如果需要使用JSTL必须添加该依赖--> 52 <dependency> 53 <groupId>javax.servlet</groupId> 54 <artifactId>jstl</artifactId> 55 </dependency> 56 <!--mybatis整合SpringBoot的起步依赖--> 57 <dependency> 58 <groupId>org.mybatis.spring.boot</groupId> 59 <artifactId>mybatis-spring-boot-starter</artifactId> 60 <version>2.1.1</version> 61 </dependency> 62 <!--mysql的驱动依赖--> 63 <dependency> 64 <groupId>mysql</groupId> 65 <artifactId>mysql-connector-java</artifactId> 66 </dependency> 67 <!--SpringBoot热部署--> 68 <dependency> 69 <groupId>org.springframework.boot</groupId> 70 <artifactId>spring-boot-devtools</artifactId> 71 </dependency> 72 <!--redis依赖--> 73 <dependency> 74 <groupId>org.springframework.boot</groupId> 75 <artifactId>spring-boot-starter-data-redis</artifactId> 76 </dependency> 77 <!--日志依赖--> 78 <dependency> 79 <groupId>org.projectlombok</groupId> 80 <artifactId>lombok</artifactId> 81 </dependency> 82 <!--Thymeleaf依赖--> 83 <dependency> 84 <groupId>org.springframework.boot</groupId> 85 <artifactId>spring-boot-starter-thymeleaf</artifactId> 86 </dependency> 87 </dependencies> 88 89 <build> 90 <plugins> 91 <plugin> 92 <groupId>org.springframework.boot</groupId> 93 <artifactId>spring-boot-maven-plugin</artifactId> 94 </plugin> 95 <!--mybatis代码自动生成插件--> 96 <plugin> 97 <groupId>org.mybatis.generator</groupId> 98 <artifactId>mybatis-generator-maven-plugin</artifactId> 99 <version>1.3.6</version> 100 <configuration> 101 <configurationFile>GeneratorMapper.xml</configurationFile> 102 <verbose>true</verbose> 103 <overwrite>true</overwrite> 104 </configuration> 105 </plugin> 106 </plugins> 107 <!--jsp文件必须编译到指定的META-INF/resources目录下才能访问,否则访问不到。建议使用模板技术--> 108 <resources> 109 <resource> 110 <!--源文件位置--> 111 <directory>src/main/webapp</directory> 112 <!--指定编译到META-INF/resources,该目录不能乱写--> 113 <targetPath>META-INF/resources</targetPath> 114 <!--指定要把哪些文件编译进去,**表示webapp目录及其子目录,*.*表示所有文件--> 115 <includes> 116 <include>**/*.*</include> 117 </includes> 118 </resource> 119 120 <!--默认情况下mybatis的xml文件不会编译到target的class目录下,需配置。此外,可放在resources目录下,配置文件properties中需配置--> 121 <!-- <resource>--> 122 <!-- <directory>src/main/java</directory>--> 123 <!-- <includes>--> 124 <!-- <include>**/*.*</include>--> 125 <!-- </includes>--> 126 <!-- </resource>--> 127 128 <!--resources资源文件夹配置--> 129 <resource> 130 <directory>src/main/resources</directory> 131 <includes> 132 <include>**/*.*</include> 133 </includes> 134 </resource> 135 </resources> 136 137 </build> 138 139 </project>