SpringBoot project back-end development process
Import dependencies
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
<dependencies>
<!--web启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
Create entry class
@SpringBootApplication
public class UserApp {
public static void main(String[] args) {
// 参数1 当前入口类的类对象 参数2 main函数的参数
SpringApplication.run(UserApp.class,args);
}
}
Create the configuration file application.yaml
#项目端口号
server:
port: 9090
servlet:
#项目名称:springboot项目访问时候默认没有项目名
context-path: /UserModel
Springboot integrated mybatis
Hand over the core components of mybatis to the spring factory for management
Introduce dependencies
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.31</version>
</dependency>
<!--整合mybatis启动器-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.3</version>
</dependency>
dao layer, service layer coding
Create mybatis-mapper in the resources directory
<?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.baizhi.dao.IUserDAO">
<!--用户注册-->
<insert id="saveUser" parameterType="com.baizhi.entity.User">
insert into t_user(id,name,password,sex,photo,birthday,email)
values (#{user.id},#{user.name},#{user.password},#{user.sex},#{user.photo},#{user.birthday},#{user.email})
</insert>
<!--根据用户名称和密码查询用户-->
<select id="queryUserByNameAndPassword" parameterType="com.baizhi.entity.User" resultType="com.baizhi.entity.User">
select id,name,password,sex,photo,birthday,email from t_user
</select>
</mapper>
Build configuration information for mybatis
server:
port: 9090
servlet:
context-path: /UserModel
jsp:
init-parameters:
development: true
tomcat:
uri-encoding: UTF-8
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://localhost:3306/upload?useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC&useSSL=false
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
mvc:
view:
prefix: /
suffix: .jsp
#post表单乱码提交
http:
encoding:
charset: utf-8
#文件上传
servlet:
multipart:
enabled: true
max-file-size: 1MB
location: D://Uninstall
mybatis:
type-aliases-package: com.baizhi.entity
mapper-locations: classpath:com/baizhi/mapper/*.xml
#开启mybatis的批处理,提升sql效率
executor-type: batch
Add an annotation to the entry class to specify the package to be scanned
@MapperScan(basePackages = "com.baizhi.dao")
There is no getter for property named'user' in'class** when configuring xml
mybatis会自动识别user对象的值,传到xml文件中,所以需要给对象指定映射。在userDao方法中给user对象添加上@Param注解,可解决这个问题。
int addUser(@Param("user") User user);
Springboot integrated jsp
1. Import the relevant jar supported by jsp parsing
<!--使内嵌的tomcat支持解析jsp-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<!--引入jsp的支持-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
2. Configure the view resolver
#添加视图解析器
spring:
mvc:
view:
prefix: /
suffix: .jsp
3. Start by plug-in or edit the environment in the upper right corner of the idea project
4. Hot deployment of configuration page
#提供页面热部署
server:
jsp-servlet:
init-parameters:
development: true
Custom implementation of dao, service, controller
Controller is implemented as follows
/**
* @RestController: 等价 @Controller + @ResponseBody
* @RequestMapping: 请求映射,在Spring4.0注解开发中对RequestMapping进行丰富,分别按照请求类型
* - @PostMapping 新增
* - @GetMapping 查询
* - @PutMapping 修改
* - @DeleteMapping 删除
* @RequestParam: 接收表单参数
*/
@RestController
@RequestMapping(value = "/formUserManager")
public class FormUserController {
private static final Logger LOGGER= LoggerFactory.getLogger(FormUserController.class);
@Autowired
IUserService userService;
//参数multipartFile是一个文件
@PostMapping(value = "/registerUser")
public User registerUser(User user,
@RequestParam(value = "multipartFile",required = false) MultipartFile multipartFile) throws IOException{
//对文件进行初步处理,获取前缀,后缀并进行打印
if(multipartFile!=null){
String fileName=multipartFile.getOriginalFilename();
String suffix=fileName.substring(fileName.lastIndexOf("."));
File tmpFile = File.createTempFile(fileName.substring(0,fileName.lastIndexOf(".")),suffix);
System.out.println(tmpFile.getName());
tmpFile.delete();
}
userService.saveUser(user);
return user;
}
@PostMapping(value = "/userLogin")
public User userLogin(User user){
return userService.queryUserByNameAndPassword(user);
}
@PutMapping(value = "/updateUser")
public void updateUser(User user,
@RequestParam(value = "multipartFile",required = false) MultipartFile multipartFile) throws IOException{
if(multipartFile!=null){
String fileName=multipartFile.getOriginalFilename();
String suffix=fileName.substring(fileName.lastIndexOf("."));
File tmpFile = File.createTempFile(fileName.substring(0,fileName.lastIndexOf(".")),suffix);
System.out.println(tmpFile.getName());
tmpFile.delete();
}
userService.updateUser(user);
}
@DeleteMapping(value = "/deleteUserByIds")
public void delteUserByIds(@RequestParam(value = "ids") Integer[] ids){
userService.deleteByUserIds(ids);
}
@GetMapping(value = "/queryUserByPage")
public List<User> queryUserByPage(@RequestParam(value = "page",defaultValue = "1") Integer pageNow,
@RequestParam(value = "rows",defaultValue = "10") Integer pageSize,
@RequestParam(value = "column",required = false) String column,
@RequestParam(value = "value",required = false) String value){
HashMap<String, Object> results = new HashMap<>();
results.put("total",userService.queryUserCount(column,value));
results.put("rows",userService.queryUserByPage(pageNow,pageSize,column,value));
return userService.queryUserByPage(pageNow,pageSize,column,value);
}
@GetMapping(value = "/queryUserById")
public User queryUserById(@RequestParam(value = "id") Integer id){
User user = userService.queryUserById(id);
return user;
}
}
Project Controller interface test
After the project's dao, service, and controller are developed, you can use postman to test by yourself, or you can use RestTemplate to test the project.
Add the RestTemplate class to the entry class of springboot
@SpringBootApplication
@MapperScans(value ={
@MapperScan(basePackages = "com.baizhi.dao")
})
public class UserModelRestApplication {
public static void main(String[] args) {
SpringApplication.run(UserModelRestApplication.class,args);
}
//SpringMVC中自带的一个Rest客户端工具,可以无缝和SpringBoot集成
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
Copy the classes in the controller to the package under the test folder, remove the original annotations, and replace them with the annotations for the springboot test. Remove the implementation of each method in the controller, and comment out with //, for each method Rewrite a test method
import static org.junit.Assert.*;
@SpringBootTest(classes = UserApp.class)
@RunWith(SpringRunner.class)
public class FormUserControllerTest {
@Autowired
private RestTemplate restTemplate;
private String prefix="http://localhost:9090/UserModel/formUserManager";
// @PostMapping(value = "/registerUser")
// public User registerUser(User user,
// @RequestParam(value = "multipartFile",required = false) MultipartFile multipartFile) throws IOException
//用户注册信息
@Test
public void testRegisterUser(){
//具体链接
String url=prefix+"/registerUser";
//构建表单参数(由于要传递文件所以使用MultiValueMap)
MultiValueMap<String,Object> formData=new LinkedMultiValueMap<>();
formData.add("name","王小五1");
formData.add("password","123456");
formData.add("sex","true");
formData.add("birthDay","2018-01-26");
formData.add("photo","user.png");
formData.add("email","[email protected]");
//上传文件信息 (上传的文件名不能为中文,否则出现500异常)
FileSystemResource fileSystemResource=new FileSystemResource("D:\\桌面壁纸/timg.jpg");
formData.add("multipartFile",fileSystemResource);
//提交请求
User user = restTemplate.postForObject(url, formData, User.class);
assertNotNull("用户",user);
System.out.println(user);
}
//删除用户信息
@Test
public void testDelteUserByIds(){
String url=prefix+"/deleteUserByIds?ids={ids}";
HashMap<String,Object> params=new HashMap<>();
params.put("ids","10,11,12");
restTemplate.delete(url,params);
}
@Test
public void testQueryUserByPage(){
String url=prefix+"/queryUserByPage?page={page}&rows={rows}&column={column}&value={value}";
Map<String,Object> params=new HashMap<>();
params.put("page",1);
params.put("rows",5);
params.put("column","name");
params.put("value","b");
restTemplate.getForObject(url,User[].class,params);
}
//使用Map,还是MultiValueMap看restTemplate调用方法时所需要的参数,如果使用Map,就要在url上添加传递的参数
}
When testing, note that the Get and Set methods of the class object automatically generated by the idea's annotations may have problems. If the Get and Set methods of the properties cannot be called in the service layer, you can write the corresponding Get and Set methods yourself.
When using restTemplate to test the controller layer interface, you must first start the springboot entry class, otherwise the Connection refused: connect exception will occur.