Restful style interfaces written using SpringBoot

I. Introduction
    Restful url to regulate a coding style, usually a URL corresponds to a resource, similar to the form of access http://xxx.com/xx/{id}/{id}.

    For chestnuts, there are many brands to choose when we buy a mobile phone in a shopping site, but there are a lot of models in each brand, then https://mall.com/mobile/iphone/6 represents Iphone6, https: //mall.com/mobile/iphone/7 and https://mall.com/mobile/iphone/8 they represent the Iphone7 and Iphone8.

    SpringBoot built SpringMvc, but also provides @RequestParam, @RequestBody and @PathVariable three notes acquired client parameters, two of which are the parameters acquired the client post submitted, and @PathVariable acquisition parameters are accessed from the url .
    Closer to home, let the user management system, for example, write a set of Restful style interfaces in SpringBoot it.

Second, the development environment

  • IDE:IntelliJ IDEA
  • Official website address: https: //www.jetbrains.com/idea/download/
  • JDK:1.8
  • Database: MySQL
  • Build tools: Maven

Third, write your own Restful program

 

1. Create SpringBoot project, as shown below:

 

 Click Next, select some basic project parameters, as follows:

 

 Click Next, select the components we need, here we choose MySQL, JPA, WEB components as part of our development components. As shown below:

 

 

 

 Click Finish to complete the creation of the project, project structure below:

 

 

2. The project dependencies Maven pom.xml configuration as follows:

<?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.forMelo</groupId>
    <artifactId>myrestfulproject</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
 
    <name>myrestfulproject</name>
    <description>Demo project for Spring Boot</description>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.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-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</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>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
 
</project>

3. Data source, JPA configuration

SpringBoot default configuration file for application.properties, we will modify it to application.yml format, .yml properties file layered and more readable. application.yml specific configuration is as follows:

 

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8
    driverClassName: com.mysql.jdbc.Driver
    username: root
    password: 1
  jpa:
    database: MySQL
    show-sql: true
    hibernate:
      ddl-auto: update
      naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy

Here we test the mysql create database table created using SQLyog t_user_info, as shown below:

 

 4. Preparation of a controller entity class and UserController.java User.java

UserController.java

package com.formelo.controller;
 
import com.formelo.entity.User;
import com.formelo.repository.UserJPARepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
import java.util.List;
 
/**
 * Created by songqiuming on 2018/1/7.
 */
@RestController
public class UserController {
 
    @Autowired
    private UserJPARepository userJPARepository;
 
    /**
     * 查询用户列表
     * @return
     */
    @GetMapping(value = "/user")
     Public List <the User> findUserList () {
         return userJPARepository.findAll (); 
    } 
 
    / ** 
     * query according to a user Id 
     * @param ID 
     * @return 
     * / 
    @GetMapping (value = "/ User / Query / {ID} " )
     public the user findUserOne (@PathVariable (" ID " ) Integer ID) {
         return userJPARepository.findOne (ID); 
    } 
 
    / ** 
     * Add user 
     * @param name 
     * @param Age 
     * @param Country 
     *@return
     */
 
    @PostMapping(value = "/user")
    public User addUser(@RequestParam("name") String name, @RequestParam("age") int age,
                        @RequestParam("country") String country){
        User user = new User();
        user.setName(name);
        user.setAge(age);
        user.setCountry(country);
        return userJPARepository.save(user);
    }
 
    /**
     * 删除用户
     * @param id  用户编号
     * @return
     */
    @DeleteMapping(value = "/user/{id}")
    public  List<User> deleteUser(@PathVariable("id") Integer id){
        userJPARepository.delete(id);
        return userJPARepository.findAll();
    }
 
    /**
     * 更新用户
     * @param id
     * @param name
     * @param age
     * @param country
     * @return
     */
    @PutMapping(value = "/user/{id}")
    public User updateUser(@PathVariable("id") Integer id, @RequestParam("name") String name,
                           @RequestParam("age") int age, @RequestParam("country") String country){
        User user = userJPARepository.findById(id);
        user.setName(name);
        user.setAge(age);
        user.setCountry(country);
        return userJPARepository.save(user);
    }
 
    /**
     * 根据国家查询用户
     * @param country
     * @return
     */
    @GetMapping(value = "/user/{country}")
    public List<User> findByCountry(@PathVariable("country") String country){
        return userJPARepository.findByCountry(country);
    }
 
}

User.java

package com.formelo.entity;
 
import javax.persistence.*;
 
/**
 * Created by songqiuming on 2018/1/7.
 */
@Entity
@Table(name = "t_user_info")
public class User {
 
    private static final long serialVersionUID = -3039703447657705408L;
 
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;
    @Column(name = "name")
    private String name;
    @Column(name="age")
    private int age;
    @Column(name="country")
    private String country;
 
    public User() {
    }
 
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String getCountry() {
        return country;
    }
 
    public void setCountry(String country) {
        this.country = country;
    }
 
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", country='" + country + '\'' +
                '}';
    }
}

5. Create JPA 

Creating UserJPARepository.java, it inherits JpaRepository interfaces within SpringDataJPA, interact with the database.

UserJPARepository.java

package com.formelo.repository;
 
import com.formelo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
 
import java.util.List;
 
/**
 * Created by songqiuming on 2018/1/7.
 */
public interface UserJPARepository extends JpaRepository<User,Long> {
    User findById(Long id);
    List<User> findByCountry(String country);
}

6. Start project

Everywhere so far, we have completed a set of encoding restful style interface, run MyrestfulprojectApplication the main method to start the project, the console output:

"C:\Program Files\Java\jdk1.8.0_102\bin\java" ...
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.9.RELEASE)
 
2018-01-09 21:57:41.533  INFO 6884 --- [           main] com.formelo.MyrestfulprojectApplication  : Starting MyrestfulprojectApplication on DESKTOP-6SJA93T with PID 6884 (D:\myproject\myrestfulproject\target\classes started by songqiuming in D:\myproject\myrestfulproject)
2018-01-09 21:57:41.560  INFO 6884 --- [           main] com.formelo.MyrestfulprojectApplication  : No active profile set, falling back to default profiles: default
2018-01-09 21:57:41.763  INFO 6884 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@65466a6a: startup date [Tue Jan 09 21:57:41 CST 2018]; root of context hierarchy
2018-01-09 21:57:47.897  INFO 6884 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-01-09 21:57:47.969  INFO 6884 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-01-09 21:57:47.972  INFO 6884 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.23
2018-01-09 21:57:48.358  INFO 6884 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-01-09 21:57:48.359  INFO 6884 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 6609 ms
2018-01-09 21:57:48.663  INFO 6884 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2018-01-09 21:57:48.669  INFO 6884 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-01-09 21:57:48.670  INFO 6884 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-01-09 21:57:48.670  INFO 6884 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-01-09 21:57:48.670  INFO 6884 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-01-09 21:57:49.598  INFO 6884 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-01-09 21:57:49.656  INFO 6884 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2018-01-09 21:57:49.817  INFO 6884 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.12.Final}
2018-01-09 21:57:49.819  INFO 6884 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2018-01-09 21:57:49.820  INFO 6884 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2018-01-09 21:57:49.976  INFO 6884 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Tue Jan 09 21:57:50 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Tue Jan 09 21:57:50 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Tue Jan 09 21:57:50 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Tue Jan 09 21:57:50 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Tue Jan 09 21:57:50 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Tue Jan 09 21:57:51 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Tue Jan 09 21:57:51 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Tue Jan 09 21:57:51 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Tue Jan 09 21:57:51 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Tue Jan 09 21:57:51 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2018-01-09 21:57:51.225  INFO 6884 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2018-01-09 21:57:52.092  INFO 6884 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000228: Running hbm2ddl schema update
2018-01-09 21:57:52.229  INFO 6884 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-01-09 21:57:53.483  INFO 6884 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@65466a6a: startup date [Tue Jan 09 21:57:41 CST 2018]; root of context hierarchy
2018-01-09 21:57:53.666  INFO 6884 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/user],methods=[POST]}" onto public com.formelo.entity.User com.formelo.controller.UserController.addUser(java.lang.String,int,java.lang.String)
2018-01-09 21:57:53.667  INFO 6884 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/user/{country}],methods=[GET]}" onto public java.util.List<com.formelo.entity.User> com.formelo.controller.UserController.findByCountry(java.lang.String)
2018-01-09 21:57:53.669  INFO 6884 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/user/{id}],methods=[DELETE]}" onto public java.util.List<com.formelo.entity.User> com.formelo.controller.UserController.deleteUser(java.lang.Long)
2018-01-09 21:57:53.669  INFO 6884 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/user/{id}],methods=[GET]}" onto public com.formelo.entity.User com.formelo.controller.UserController.findUserOne(java.lang.Long)
2018-01-09 21:57:53.670  INFO 6884 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/user/{id}],methods=[PUT]}" onto public com.formelo.entity.User com.formelo.controller.UserController.updateUser(java.lang.Long,java.lang.String,int,java.lang.String)
2018-01-09 21:57:53.670  INFO 6884 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/user],methods=[GET]}" onto public java.util.List<com.formelo.entity.User> com.formelo.controller.UserController.findUserList()
2018-01-09 21:57:53.673  INFO 6884 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-01-09 21:57:53.674  INFO 6884 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-01-09 21:57:53.761  INFO 6884 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-01-09 21:57:53.762  INFO 6884 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-01-09 21:57:53.945  INFO 6884 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-01-09 21:57:54.419  INFO 6884 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-01-09 21:57:54.520  INFO 6884 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-01-09 21:57:54.525  INFO 6884 --- [           main] com.formelo.MyrestfulprojectApplication  : Started MyrestfulprojectApplication in 14.573 seconds (JVM running for 16.939)

7. Interface testing

Let's open the postman test interface. First, several data inserted into the database, the corresponding request is as follows:

 

  • Query User List

 

 

 

 

According to a user query ID:

 

 Add user:

 

 

 

 Update User:

 

 

 

 

Guess you like

Origin www.cnblogs.com/qingmuchuanqi48/p/11854207.html