用springboot框架搭建一个简单的web项目,可以返回页面或者ajax请求的结果。用mybatis-plus查询mysql数据库。完整代码地址:cat
创建一个maven项目
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wangjx</groupId>
<artifactId>cat</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>cat</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- web必须要,thymeleaf是因为我用的是thymeleaf框架作为前端页面,这也是springboot的默认前端-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- mybatis框架的加强版,做了一些封装更加方便处理mybatis,这个依赖已经有mybatis,所以不需要额外加mybatis包-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!-- mysql连接驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 方便开发的包,具体可以看lombok的相关文章 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<!-- alibaba开发的json包用来封装转换等操作 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
spring:
# 数据库连接池配置
datasource:
url: jdbc:mysql://127.0.0.1/corollago?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
username: root
password: null
driver-class-name: com.mysql.cj.jdbc.Driver
# 指定数据库连接池的类型,我用的是HikariDataSource,这也是springboot的默认连接池,特点是性能好,但是没有连接状态的监控,有这方便的需要的话,请考虑alibaba出品的Druid
type: com.zaxxer.hikari.HikariDataSource
mvc:
servlet:
# 项目启动根路径,这样启动的时候访问路径就是localhost:8080
path: /
# 应用名称
application:
name: cat
# 页面配置,没配好会影响返回页面的时候找不到资源
thymeleaf:
cache: false
prefix: classpath:/templates/
suffix: .html
mode: HTML5
encoding: UTF-8
# 输出日志的配置
logging:
pattern:
# 控制台输出格式
console: "%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr([%t]){faint} \\(%file:%line\\) %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"
# 指定包下的日志输出等级,DEBUG < INFO < WARN < ERROR
level:
org.springframework: warn
ccom.zaxxer.hikari: info
com.wangjx.cat.aop: info
file:
# 只保存10天日志
max-history: 10
# 日志存放路径
path: logs
测试数据库
创建一个数据库corollago(名字随便,但是要跟application.yml中数据库连接池中的一致),然后创建一个用户表
CREATE TABLE `t_user` (
`id` bigint(20) NOT NULL,
`account` varchar(20) DEFAULT NULL,
`name` varchar(20) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
配置返回页面功能
DemoController页面controller
package com.wangjx.cat.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 页面controller的demo
*/
@Controller
@RequestMapping
public class DemoController {
@GetMapping("/hello")
public String index(Model model) {
model.addAttribute("name", "Paul");
model.addAttribute("time", System.currentTimeMillis());
return "/hello";
}
}
- @Controller 是返回页面,@RestController是返回json结果。
- 类上的@RequestMapping中的路径加上方法上的路径配置连一起才是这个方法的访问路径,这个index的方法访问路径就是:
http://localhost:8080/hello
- @GetMapping("/hello") = @RequestMapping(value="/hello",method=RequestMethod.GET)
- model的变量名要和html中的变量名一致
前端资源
页面路径是:/resources/templates/hello.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>hello.html</title>
<link href="css/hello.css" rel="stylesheet">
<script src="js/hello.js"></script>
</head>
<body>
<h1 id="test">INDEX</h1>
<div>NAME:<span th:text="${name}"></span></div>
<div>TIME:<span th:text="${time}"></span></div>
<div><button type="button" onclick="test()">TEST</button></div>
</body>
</html>
css样式路径是:/resources/static/css/hello.css
#test {
color: red;
}
js脚本路径是:/resources/static/js/js.css
function test() {
alert('你点击了按钮');
}
返回ajax的json请求的配置
RestController页面controller
package com.wangjx.cat.rest.controller;
import com.alibaba.fastjson.JSONObject;
import com.wangjx.cat.bean.HttpJsonResult;
import com.wangjx.cat.bean.TUser;
import com.wangjx.cat.dao.TUserMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* rest返回json字符串的controller的demo
*/
@RestController
@RequestMapping("/rest")
public class DemoRestController {
private final TUserMapper tUserMapper;
public DemoRestController(TUserMapper tUserMapper) {
this.tUserMapper = tUserMapper;
}
@GetMapping("/index")
public String index() {
JSONObject json = new JSONObject();
json.put("name", "demo");
json.put("time", System.currentTimeMillis());
return json.toJSONString();
}
@GetMapping("/users")
public String users() {
List<TUser> users = tUserMapper.findAll();
return HttpJsonResult.success("查找所有用户成功", users).toJSONString();
}
}
- 返回json需要指定为@RestController
- 访问地址为:
http://localhost:8080/rest/index
返回结果为:
{
"name": "demo",
"time": 1574528989160
}
AOP的配置
创建一个拦截器
拦截器的作用是在执行方法之前都需要进行检查,可以在这里做一些操作
package com.wangjx.cat.aop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 常见的拦截器,平平无奇,可以做一些如登录检查之类的
*/
@Slf4j
public class UrlInterceptor extends HandlerInterceptorAdapter {
/**
* 在请求处理之前进行调用(Controller方法调用之前)
* 基于URL实现的拦截器
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String path = request.getServletPath();
// 这写你拦截需要干的事儿,比如取缓存,SESSION,权限判断等
log.debug("====================================");
log.debug("UrlInterceptor 拦截了一下:{}", path);
log.debug("====================================");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.debug("postHandle 渲染html之前");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.debug("afterCompletion 处理完请求所有事情之后");
}
}
注册拦截器
拦截器只有注册才能生效
package com.wangjx.cat.configuration;
import com.wangjx.cat.aop.UrlInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 后面的/**是拦截所有请求
registry.addInterceptor(new UrlInterceptor()).addPathPatterns("/**");
}
}
配置数据库访问
这里用的是mybatis-plus,如果选择只用mybatis或者用jpa请看别的博客。
定义一个mapper
package com.wangjx.cat.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wangjx.cat.bean.TUser;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface TUserMapper extends BaseMapper<TUser> {
@Select("select * from t_user")
List<TUser> findAll();
}
- mybatis-plus已经帮实现了一些常见的操作,我这边加了一个findAll(),查询所有的用户用于测试
- 这个TUserMapper的使用在DemoRestController中。
启动类上需要指定mapper的位置
@MapperScan 注解中指定位置才能扫描到这些类
package com.wangjx.cat;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.wangjx.cat.dao")
public class CatApplication {
public static void main(String[] args) {
SpringApplication.run(CatApplication.class, args);
}
}
结束
以上,一个web项目的基本功能都有了。如是缺少一些类,可以去github上的项目看看:cat