入门
创建jar maven项目
pom.xml 文件添加
<!--spring boot 父依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
<dependencies>
<!-- spring boot 配置web的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
控制器
package com.gwl.web.controller;
import com.gwl.model.User;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("user")
public class UserController {
@RequestMapping("{id}")
//自动返回json格式数据
@ResponseBody
public User userInfo(@PathVariable Integer id) {
User user = new User("zhangsan", "123456");
user.setId(id);
return user;
}
}
创建一个App类,启动springboot
package com.gwl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@EnableAutoConfiguration
//@ComponentScan(basePackages = {"com.gwl.web.controller","com.gwl.web.controller2"})
@ComponentScan(basePackages = "com.gwl.web.controller")
public class App
{
public static void main( String[] args )
{
// 启动springboot项目
SpringApplication.run(App.class,args);
}
}
访问 http://localhost:8080/user/3
查看项目实际的依赖
mvn dependency:tree
静态资源的访问
在main下创建resources文件夹,右键resources,选择Resources Root
在resources下创建static文件夹,static下创建images文件夹,在images文件夹内放入图片 hi.png,创建后的目录如下
访问 http://localhost:8080/images/hi.png 显示图片
捕获全局异常
创建捕获异常类
package com.gwl.web.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
//控制器切面
@ControllerAdvice
public class GlobalExceptionHandler {
//捕获运行时异常
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public Map<String, Object> exceptionHander() {
Map<String, Object> map = new HashMap<>();
map.put("msg", "错误");
map.put("code", "303");
return map;
}
}
在 App 启动类中添加扫描
@ComponentScan(basePackages = "com.gwl.web")
控制器出现异常
Web页面
Spring Boot提供了默认配置的模板引擎主要有以下几种:
- Thymeleaf
- FreeMarker
- Velocity
- Groovy
- Mustache
Spring Boot建议使用这些模板引擎,避免使用JSP,若一定要使用JSP将无法实现Spring Boot的多种特性,当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。也可以修改这个路径。
Freemarker的使用
在resources下创建templates文件夹
pom.xml 添加 freeMarker 的依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
控制器
package com.gwl.web.controller;
import com.gwl.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("student")
public class StudentController {
@RequestMapping("/list")
public String list(Model model) {
model.addAttribute("username", "zhangsan");
model.addAttribute("age", 18);
List<Student> list = new ArrayList();
list.add(new Student(2, "lisi", "123"));
list.add(new Student(5, "wangwu", "12356"));
model.addAttribute("studentList", list);
return "student/list";
}
}
list.ftl
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8"/>
<title></title>
</head>
<body>
欢迎
${username}
<#if age <= 17>小哥
<#elseif age <= 30>先生
<#else>大叔
</#if>登录
<table border="1">
<tr>
<td>id</td>
<td>名字</td>
<td>密码</td>
</tr>
<#list studentList?sort_by("id")?reverse as stu>
<tr>
<td> ${stu.id}</td>
<td> ${stu.username}</td>
<td> ${stu.password}</td>
</tr>
</#list>
</table>
</body>
</html>
访问 http://localhost:8080/student/list
jsp的使用
创建war maven工程
pom.xml 添加依赖包
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.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-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
</dependencies>
在main下创建resources文件夹,右键resources,选择Resources Root
在 resources 下创建配置文件 application.properties
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
server.servlet.context-path=/test
server.port=8888
在main下创建java文件夹,右键java,选择Sources Root
控制器
package com.gwl.web.controller;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
@EnableAutoConfiguration
@RequestMapping("user")
public class UserController {
@RequestMapping("list")
public String list() {
return "user/list";
}
public static void main(String[] args) {
SpringApplication.run(UserController.class,args);
}
}
在 WEB-INF 下创建 view/user 文件夹,创建list.jsp文件
访问 http://localhost:8888/test/user/list
Spring Boot使用JDBC
pom.xml 添加依赖
<!-- JDBC -->
<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.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
在 resources 下创建配置文件 application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=root123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
Service
package com.gwl.service.impl;
import com.gwl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void add(String username, String password) {
String sql = "insert into user(username,password) values (?,?)";
jdbcTemplate.update(sql, username, password);
}
}
controller
package com.gwl.web.controller;
import com.gwl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("add")
@ResponseBody
public String add(String username, String password) {
userService.add(username, password);
return "success";
}
}
在 App 启动类中添加扫描 service 包
@ComponentScan(basePackages = {"com.gwl.web","com.gwl.service"})
访问 http://localhost:8080/user/add?username=zhangsan&password=123456
Spring Boot使用Mybatis
pom.xml 添加依赖
<!-- mybaties -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
在 resources 下创建配置文件 application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=root123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
UserMapper
package com.gwl.mapper;
import com.gwl.model.User;
import org.apache.ibatis.annotations.Param;
public interface UserMapper {
public int save(@Param("username") String username, @Param("password") String password);
public User getuser(@Param("username") String username);
}
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.gwl.mapper.UserMapper">
<insert id="save">
insert into user (username,password) VALUES(#{username},#{password})
</insert>
<select id="getuser" resultType="com.gwl.model.User" parameterType="string">
select * from user where username = #{username}
</select>
</mapper>
pom.xml 添加
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
注解方式 --- 不需要在 pom.xml 文件中添加配置和添加 UserMapper.xml
package com.gwl.mapper; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; public interface UserMapper { @Insert("insert user(username,password) values (#{username},#{password})") public int save(@Param("username") String username, @Param("password") String password); // @Insert("insert user(username,password) values (#{arg0},#{arg1})") // public int save(String username, String password); }
service
package com.gwl.service.impl;
import com.gwl.mapper.UserMapper;
import com.gwl.model.User;
import com.gwl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public void add(String username, String password) {
userMapper.save(username, password);
}
@Override
public User get(String username) {
return userMapper.getuser(username);
}
}
controller
package com.gwl.web.controller;
import com.gwl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("add")
@ResponseBody
public String add(String username, String password) {
userService.add(username, password);
return "success";
}
@RequestMapping("get")
@ResponseBody
public User find(String username) {
return userService.get(username);
}
}
在 App 启动类中添加
@MapperScan(basePackages = "com.gwl.mapper")
访问 http://localhost:8080/user/add?username=zhangsan&password=1234567
访问 http://localhost:8080/user/get?username=lisi111
事务 @Transactional
@Transactional
public class UserServiceImpl implements UserService {
}