Preface
I have always used springmvc+mybatis to develop back-end interfaces. I have been idle recently. According to the existing functional requirements, I use springboot+mybatis to deploy a simple web project.
Tools used
Problems solved
1. How to create a springboot project with idea
2. How to configure server, database, mybatis, view parser
3. How to use mybatis generator to automatically generate code
4. How to use multipart to upload files
5. How to use springboot transactions
6. How to package tomcat deployment
Use idea to create springboot project
1. Open IDEA, File -> New -> Project, select Spring Initializr, and then next.
2. Modify Ariifact, the Name and package below will be automatically modified; Packaging has two modes, one is Jar and the other is War; because springboot comes with tomcat, the project can be jar and run directly; while my existing project is deployed on tomcat, I need to be war package; and then next.
3. Set the project dependency, then next, go to the next page, set the project name, and click finish to finish.
4. Enter the project
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.example</groupId> <artifactId>springbootdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>springbootdemo</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-jdbc</artifactId> </dependency> <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>com.microsoft.sqlserver</groupId> <artifactId>mssql-jdbc</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> </dependencies> <build> <plugins> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>
springmvc without configuration file
Two examples: 1. http request access and rendering the page 2. http request returns json string
-Configure data source and view rendering
-Add view rendering pom dependencies
-Create WelcomeController, welcome.jsp
New project structure
application.yml Configure data source and view rendering
# Data source and view configuration spring: datasource: url: jdbc:sqlserver://xx:1433;DatabaseName=xx username: xx password: xx driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver mvc: view: prefix: /WEB-INF/views/ suffix: .jsp
pom.xml adds view rendering dependency
<!-- Use jsp requires dependencies --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency>
Create a WelcomeController
package com.example.springbootdemo.web;import com.example.springbootdemo.entity.Welcome;import com.example.springbootdemo.response.Response;import com.example.springbootdemo.response.ResponseCode;import org.springframework.steretype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.ModelAndView;import java.util.ArrayList;import java.util.List;@Controller@RequestMapping("/welcome")public class WelcomeController { /** * Visit welcome.jsp page* @return */ @RequestMapping("welcomeIndex") public ModelAndView welcomeIndex(){ ModelAndView mv = new ModelAndView(); mv.setViewName("welcome"); mv.addObject("name","xx"); return mv; } /** * Return json string* @return */ @RequestMapping("getWelcomeInfo") @ResponseBody public Response getWelcomeInfo(){ /** * Test data*/ List<Welcome> welcomes = new ArrayList<>(); Welcome w1 = new Welcome(); w1.setId("1"); w1.setName("xx1"); w1.setAge(11); w1.setGender("female"); Welcome w2 = new Welcome(); w2.setId("2"); w2.setName("xx2"); w2.setAge(22); w2.setGender("Male"); welcomes.add(w1); welcomes.add(w2); Response response = new Response(); response.setData(welcomes); response.setRetcode(ResponseCode.SUCCESS); response.setRetdesc("Success"); return response; }}Create welcome.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head> <title>View rendering</title></head><body> Hello, ${name}</body></html>Start the project and access
http://localhost:8080/welcome/getWelcomeInfo
http://localhost:8080/welcome/welcomeIndex
Automatically generate code using mybatis generator
Used to create *Mapper.xml, model, dao files for tables
Add mybatis generator to automatically generate code plugin in pom.xml
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!-- mybatis generator Automatically generate code plug-in--> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> </plugin> </plugins> </build>Add generatorConfig.xml in the resources/generator folder configured in the pom.xml above
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration> <!-- Database Driver: Select the database driver package on your local hard disk--> <classPathEntry location="C:/Users/.m2/repository/com/microsoft/sqlserver/mssql-jdbc/6.2.2.jre8/mssql-jdbc-6.2.2.jre8.jar"/> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true"/> <!-- Whether to remove the automatically generated comments true: Yes: false: No--> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--Database link URL, username, password--> <jdbcConnection driverClass="com.microsoft.sqlserver.jdbc.SQLServerDriver" connectionURL="jdbc:sqlserver://xx:1433;DatabaseName=xx" userId="xx" password="xx"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- Generate model package name and location--> <javaModelGenerator targetPackage="com.example.springbootdemo.entity" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- Generate package name and location of mapping file --> <sqlMapGenerator targetPackage="mybatis" targetProject="src/main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- Generate package name and location of DAO --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.springbootdemo.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- The table to be generated is the table name in the database or the view name domainObjectName is the entity class name--> <table tableName="xx" domainObjectName="StudentBinding" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context></generatorConfiguration>
Use mybatis-generator:generate in maven to produce related classes based on the tables in the database
Edit Configurations -> Add -> Maven
Configure mybatis
Add mybatis configuration in application.yml
# mybatis configuration mybatis: mapper-locations: classpath*:mybatis/*Mapper.xml type-aliases-package: com.example.springbootdemo.entity
Add @Repository("studentBindingMapper") annotation in StudentBindingMapper.java to scan to
@Repository("studentBindingMapper")public interface StudentBindingMapper {}Add @MapperScan in SpringbootdemoApplication.java
package com.example.springbootdemo;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication@MapperScan("com.example.springbootdemo.mapper") public class SpringbootdemoApplication { public static void main(String[] args) { SpringApplication.run(SpringbootdemoApplication.class, args); }}Add service and controller layers
Project level
Add StudentBindingService
package com.example.springbootdemo.service;import com.example.springbootdemo.entity.StudentBinding;import java.util.List;public interface StudentBindingService { int deleteByPrimaryKey(Long id); int insert(StudentBinding record); int insertSelective(StudentBinding record); StudentBinding selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(StudentBinding record); int updateByPrimaryKey(StudentBinding record); void validTransaction(Long id); List<StudentBinding> getStudentBindByQuery(StudentBinding record);}Add StudentBindingServiceImpl
package com.example.springbootdemo.service.impl;import com.example.springbootdemo.entity.StudentBinding;import com.example.springbootdemo.mapper.StudentBindingMapper;import com.example.springbootdemo.service.StudentBindingService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.util.List;@Service(value = "studentBindingService")public class StudentBindingServiceImpl implements StudentBindingService { @Autowired private StudentBindingMapper studentBindingMapper; @Override public int deleteByPrimaryKey(Long id) { return studentBindingMapper.deleteByPrimaryKey(id); } @Override public int insert(StudentBinding record) { return studentBindingMapper.insert(record); } @Override public int insertSelective(StudentBinding record) { return studentBindingMapper.insertSelective(record); } @Override public StudentBinding selectByPrimaryKey(Long id) { return studentBindingMapper.selectByPrimaryKey(id); } @Override public int updateByPrimaryKeySelective(StudentBinding record) { return studentBindingMapper.updateByPrimaryKeySelective(record); } @Override public int updateByPrimaryKey(StudentBinding record) { return studentBindingMapper.updateByPrimaryKey(record); } @Override @Transactional public void validTransaction(Long id){ // After deletion, insert the data of the id studentBindingMapper.deleteByPrimaryKey(id); StudentBinding record = new StudentBinding(); record.setId(id); studentBindingMapper.insertSelective(record); } @Override public List<StudentBinding> getStudentBindByQuery(StudentBinding record) { return studentBindingMapper.getStudentBindByQuery(record); }}Added StudentBindingController
package com.example.springbootdemo.web;import com.example.springbootdemo.entity.StudentBinding;import com.example.springbootdemo.response.Response;import com.example.springbootdemo.response.ResponseCode;import com.example.springbootdemo.service.StudentBindingService;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.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.servlet.ModelAndView;import java.io.File;import java.io.IOException;import java.util.List;@Controller@RequestMapping(value = "/studentBind")public class StudentBindingController { @Autowired private StudentBindingService studentBindingService; /** * Delete bound student information according to the request parameters* @param id * @return */ @RequestMapping("deleteByPrimaryKey") @ResponseBody public Response deleteByPrimaryKey(Long id){ Response response = new Response(); if(id==null){ response.setRetcode(ResponseCode.PARAMARTER_ERROR); response.setRetdesc("parameter error"); return response; } try{ studentBindingService.deleteByPrimaryKey(id); response.setRetcode(ResponseCode.SUCCESS); response.setRetdesc("DeleteSuccess"); } catch (Exception e){ e.printStackTrace(); response.setRetcode(ResponseCode.FAILED); response.setRetdesc("DeleteException"); } return response; } /** * Add bound student information according to the request parameters* @param record * @return */ @RequestMapping("insertSelective") @ResponseBody public Response insertSelective(StudentBinding record){ Response response = new Response(); if(record==null){ response.setRetcode(ResponseCode.PARAMARTER_ERROR); response.setRetdesc("parameter error"); return response; } try{ studentBindingService.insertSelective(record); response.setRetcode(ResponseCode.SUCCESS); response.setRetdesc("Add Success"); }catch (Exception e){ e.printStackTrace(); response.setRetcode(ResponseCode.FAILED); response.setRetdesc("Add Exception"); } return response; } /** * According to the request parameters, query the bound student information* @param id * @return */ @RequestMapping("selectByPrimaryKey") @ResponseBody public Response selectByPrimaryKey(Long id){ Response response = new Response(); if(id==null){ response.setRetcode(ResponseCode.PARAMARTER_ERROR); response.setRetdesc("parameter error"); return response; } try{ StudentBinding studentBinding = studentBindingService.selectByPrimaryKey(id); response.setData(studentBinding); response.setRetcode(ResponseCode.SUCCESS); response.setRetdesc("Query Success"); } catch (Exception e){ e.printStackTrace(); response.setRetcode(ResponseCode.FAILED); response.setRetdesc("Query Exception"); } return response; } /** * Verify whether the @Transaction annotation is easy to use* @param id * @return */ @RequestMapping("validTransaction") @ResponseBody public Response validTransaction(Long id){ Response response = new Response(); if(id==null){ response.setRetcode(ResponseCode.PARAMARTER_ERROR); response.setRetdesc("parameter error"); return response; } try{ studentBindingService.validTransaction(id); response.setRetcode(ResponseCode.SUCCESS); } catch (Exception e){ e.printStackTrace(); response.setRetcode(ResponseCode.FAILED); } return response; } /** * Render jsp page* @return */ @RequestMapping("welcomeIndex") public ModelAndView welcomeIndex(){ List<StudentBinding> studentBindings = studentBindingService.getStudentBindByQuery(new StudentBinding());// model.addAttribute("studentBindings",studentBindings); ModelAndView mv = new ModelAndView(); mv.setViewName("welcome"); mv.addObject("studentBindings",studentBindings); return mv; } /** * Jump to upload file page* @return */ @RequestMapping("multipartIndex") public String multipartIndex(){ return "multipart-index"; } /** * Upload the file to the specified directory* @param file * @return */ @RequestMapping("/upload") @ResponseBody public Response upload(@RequestParam("file") MultipartFile file){ Response response = new Response(); if (file.isEmpty()){ response.setRetcode(ResponseCode.PARAMARTER_ERROR); response.setRetdesc("parameter error"); return response; } try { String filePath = "D://ceshi//upload//"; File dir = new File(filePath); if(!dir.isDirectory()){ dir.mkdir(); } String fileOriginalName = file.getOriginalFilename(); File writeFile = new File(filePath + fileOriginalName); //Write the file to disk file.transferTo(writeFile); response.setRetcode(ResponseCode.SUCCESS); response.setRetdesc("Uploaded successfully"); } catch (IOException e) { e.printStackTrace(); response.setRetcode(ResponseCode.FAILED); response.setRetdesc("Upload failed"); } return response; }}After restarting the project, you can access various interfaces
springboot configuration transactions
There are two ways to configure transactions in springboot
1. In the SpringbootdemoApplication.java project entrance, add the @EnableTransactionManagement annotation to start the transaction
2. Add @Transactional annotation to the service implementation class, then all methods of the class are managed through transactions; you can also directly add @Transactional annotation to the service implementation class methods, then only transaction management is performed on this method. There are examples of adding transactions to methods in the above code.
Springboot package for tomcat deployment
Edit Configuration -> Maven -> Add -> Start -> Copy the war package -> tomcat webapp -> Modify the name of the war package -> tomcat bin -> startup.bat
After tomcat is started, visit http://localhost:8080/springbootdemo/welcome/welcomeIndex for verification
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.