RESTful description REST is a set of constraints and principles. An architecture that follows the REST style is a RESTful architecture. Resources are the core of RESTful architecture, and a good RESTful architecture can clearly understand its operations and requirements through urls. Via the URL to locate resources, such as: com. Mobin/API/v1 / shenzhen/subways. / / to obtain a list of shenzhen metro com mobin/API/v1 / shenzhen/schools/school/GET shenzhen list 2. HTTP describes the GET operation: Access to resources POST: create resources PUT: update resources DELETE: DELETE the resource Such as: GET com mobin/API/v1 / shenzhen/subways / 1: The resource that obtains the subway information request with ID 1 is usually returned to the Client in JSON or XML. With RESTful architecture, only a set of RESTful API needs to be provided on the Sever side to share API design with Web, IOS and Android. Refer to GitHub’s API design specification

1. Place xxxmapper. XML and SQLmapconfig. XML in the directory corresponding to resource. 2

Mybatis. Mapper = classpath:mapper/* mapper.xml Mybatis. Config - location = classpath: mapper/config/sqlMapConfig XML 5 6 # 7 mybatis. Specify the alias type - aliases - package = Com. Mobin. Entity # 8 9 10 spring data source. The datasource. Url = JDBC: postgresql: / / localhost: 5432 / XXX 11 spring.datasource.driver-class-name = org.postgresql.Driver 12 spring.datasource.username = postgres 13 spring.datasource.password = xxxxCopy the code

MyBatis 3 officially provides a specific API to support dynamic SQL, you can use annotations +Java code to replace XML, but complex SQL statements still go through XML, XML is more intuitive (in fact, also disgusting), annotations for code intrusion is too serious, need to be recompiled after modification.

3. Log configuration The default Spring Boot log framework is Logback. This configuration is user-friendly and provides better performance. Console log configuration 2. Configuration of development, test, and production environments

1 ##logbcak-spring.xml 2 <? The XML version = "1.0" encoding = "utf-8"? > 3 <configuration debug="false"> 4 <contextName>${appname}</contextName> 5 <! - the console log configuration - > 6 < appender name = "STDOUT" class = "ch. Qos. Logback. Core. ConsoleAppender" > 7 < encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> 8 <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread]%-5level %logger{50} - %msg%n</pattern> 9 </encoder> 10 </appender> 11 12 <appender name="FILEPROD" class="ch.qos.logback.core.rolling.RollingFileAppender"> 13 <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> 14 <FileNamePattern>SpringBootRESTful.%d{yyyy-MM-dd}.log</FileNamePattern> 15 <! -- Log retention days --> 16 <MaxHistory>20</MaxHistory> 17 </rollingPolicy> 18 <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> 19 <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread]%-5level %logger{50} - %msg%n</pattern> 20 </encoder> 21 </appender> 22 23 <appender name="FILETEST" class="ch.qos.logback.core.rolling.RollingFileAppender"> 24 <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> 25 <FileNamePattern>test.SpringBootRESTful.%d{yyyy-MM-dd}.log</FileNamePattern> 26 <MaxHistory>20</MaxHistory> 27 </rollingPolicy> 28 <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> 29 <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread]%-5level %logger{50} - %msg%n</pattern> 30 </encoder> 31 </appender> 32 33 <! --> 34 <springProfile name="dev"> 35 <! Dao "level="DEBUG"> 37 <appender-ref ref="STDOUT"/> 38 </logger> 39 <root level="INFO"> 40 <appender-ref ref="STDOUT"/> 41 </root> 42 </springProfile> 43 44 <! Test environment log configuration --> 45 <springProfile name="test"> 46 <root level="DEBUG"> 47 <appender-ref ref="FILETEST"/> 48 <appender-ref ref="STDOUT"/> 49 </root> 50 </springProfile> 51 52 <! Log configuration in production environment --> 53 <springProfile name="prod"> 54 <root level="INFO"> 55 <appender-ref ="FILEINFO"/> 56 <appender-ref  ref="STDOUT"/> 57 </root> 58 </springProfile> 59 </configuration>Copy the code

4.1 In the API design specification, the handling of exceptions should be at least 1. 4.2 Using @RestControllerAdvice to define global exception handling @RestControllerAdvice is a new feature in Spring 4.3. This is equivalent to @ControllerAdvice+ResponseBody, so @RestControllerAdvice returns the error message as Json. Custom exception classes

1 # # com. Mobin. Exception. EntityNotFoundException 2 / / when there is no request resources thrown the exception 3 public class EntityNotFoundException extends RuntimeException{ 4 public EntityNotFoundException(String mes){ 5 super(mes); 6} 7}Copy the code

2. Define a global exception class

1 ##com.mobin.exception.GlobalExceptionHadlerActice 2 @RestControllerAdvice 3 public class GlobalExceptionHadlerActice {  4 private static final long serialVersionUID = 1L; 5 @ExceptionHandler(value = EntityNotFoundException.class) 6 public ErrorMessage entityNotFoundException(HttpServletRequest request, Exception e){ 7 ErrorMessage errorMessage = new ErrorMessage(); 8 errorMessage.setStatus(HttpStatus.NOT_FOUND.value()); 9 errorMessage.setMessage(e.getLocalizedMessage()); 10 errorMessage.setUrl(request.getRequestURL().toString()); 11 return errorMessage; 13 12}}Copy the code

ErrorMessage is a user-defined entity class that contains statusCode, Message, and URL fields.

3. Corresponding request method

1 ## com.mobin.controller.SubwayController 2 @RequestMapping(value="/{id}",method = RequestMethod.GET ) 3 public SubwayResult<Subway> getSubwayByID(@PathVariable Integer id) { 4 SubwayResult<Subway> result = new SubwayResult(); 5 Subway subway = subwayService.findSubwayByID(id); 6 if (subway == null){7 throw new EntityNotFoundException(" resources not exist "); 8 } 9 result.setStatus(HttpStatus.OK.value()); 10 result.setData(subway); 11 return result; 12}Copy the code

4. Test with curl

MOBIN: 1 ~ MOBIN $curl - XGET -w "\ n" 'localhost: 8089 / API/subways / 1999 2 {3 "message" : "resource does not exist," 4 "status" : 404, 5 "url":"http://localhost:8089/api/subways/1999" 6 }Copy the code

Using FastJSON 1. Introducing fastJSON dependencies 2. Customize WebMvcConfigurer and inherit WebMvcConfigurerAdapter 3. 4 rewrite configureMessageConverters method. Custom configuration FastJsonConfig 5. Add FastJsonHttpMessageConverter to the HttpMessageConverter corresponding code:

1 ##com.mobin.config.WebMvcConfigurer 2 @Configuration 3 public class WebMvcConfigurer extends WebMvcConfigurerAdapter{ 4 @Override 5 public void configureMessageConverters(List<HttpMessageConverter<? >> converters) { 6 FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); 7 FastJsonConfig config = new FastJsonConfig(); 8 config.setSerializerFeatures(SerializerFeature.WriteNullListAsEmpty, 9 SerializerFeature.WriteMapNullValue, 10 SerializerFeature.WriteNullStringAsEmpty, 11 SerializerFeature.WriteNullBooleanAsFalse, 12 SerializerFeature.PrettyFormat); 13 converter.setDateFormat("yyyy-MM-dd HH:mm:ss"); 14 converter.setFastJsonConfig(config); 15 converters.add(converter); 18 1617}}Copy the code

SerializerFeature. WriteNullListAsEmpty: List the type field to null output. [] rather than null SerializerFeature WriteMapNullValue: Showed empty fields SerializerFeature. WriteNullStringAsEmpty: string type field to null output time “” is not null SerializerFeature. WriteNullBooleanAsFalse: Boolean type fields for null output false null SerializerFeature. PrettyFormat: beautify the json output, otherwise it will as output in line

Solve the problem of the browser returns json display garbled (reference since: blog.csdn.net/kingboyworl…).

##application.properties
spring.http.encoding.charset=UTF-8
spring.http.encoding.enable=true
spring.http.encoding.force=trueCopy the code

PageHelper is a PageHelper plugin. MappedStatement supports paging for single tables and multiple tables. MappedStatement supports paging for multiple tables. MappedStatement supports paging for multiple tables. Just add a distribution code (usually on the Server layer) before SQL statement execution. If you manually set the limit and offset of SQL statement, the paging scenario will be very disgusting, even with MyBatis reverse engineering. Import the PageHelper dependency for Spring Boot. 2. Configure PageHelper in application.properties. Adds a paging code before the specified SQL statement

3 # pagehelperDialect = postgresQL 4 #pageNum<=0 PageNum Returns the last page if the total number of pages exceeds 5 pageHelper. Reasonable =trueCopy the code

Corresponding code:

1 ##com.mobin.service.impl.SubwayServiceImpl 2 public List<Subway> findSubways(int pageNum,int pageSize){ 3 Pagehelper. startPage(pageNum,pageSize,false); 5 return subwayMapper.findSubways(); 6}Copy the code

 

Project Address:

Github.com/MOBIN-F/Spr…

References:

GitHub API

How to use @RestControllerAdvice for handling Exception with RestfulApi

PageHelper usage

SerializerFeature usage details

Logback configuration