Controller layer encoding Specification

1, Controller layer

MVC controller design layer belongs to the control layer; designed to: accept the request and respond to requests; therefore, the layer is thin as far as possible, to avoid writing code that relates to the business process.

Separating the front and rear ends of the development of the design mode and it is recommended @RestController annotations, which corresponds to a combination @ResponseBody + @Controller use.

1) If the annotation except @RestController Controller class, the method can not return the Controller jsp pages, or html, viewresolver InternalResourceViewResolver inoperative configuration, the content is returned Return the contents of the default turn into json string.

2) If you need to return to a specific page, you need to use @Controller with the view resolver InternalResourceViewResolver job.
    If you need to return JSON, XML or custom mediaType content to a page, you need to add in the corresponding method @ResponseBody comment.

In summary, the use of annotation @Controller, on a corresponding method, the parser may parse the view of the return jsp, html pages, and jump to the corresponding page; if the page to return json etc., the need to add annotations @ResponseBody


1) path setting request

Use annotations @PostMapping ( "/ page"), the class name and method name can be added on.

Note divided according to different business use, avoid indiscriminate use scrawl.

2) setting request mode

    Usual POST / GET. Use Notes: @RequestMapping and @GetMapping @PostMapping.

    Spring4.3 the introduction of {@ GetMapping, @ PostMapping, @ PutMapping, @ DeleteMapping, @ PatchMapping} to help simplify the mapping method and HTTP common semantics better method annotated 

The annotation HTTP Get mapped to specific processing method

    @GetMapping annotation is a combination, which is an abbreviation @RequestMapping (method = RequestMethod.GET) of

    @PostMapping annotation is a combination, which is an abbreviation @RequestMapping (method = RequestMethod.POST) of

3) setting request parametrically

form submission, directly or specific parameter name vo received;

@Controller
public class LoginController {

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(UserVO user){
        System.out.println("POJO: " + user.getClass().getName() + 
                ", hash code: " + user.hashCode() + ", " + user.toString());
        return "redirect:/";
    }

}

@RequestParam

@RequestParam(value="", required=true, defaultValue="")

@RequestParam has three attributes:

(1) value: request parameter name (must be configured)

(2) required: if necessary, the default is true, i.e., the request must include the parameter, if it does not, an exception is thrown (optional)

(3) defaultValue: the default value if the value is set, required automatically set to false

@ApiOperation(value = "根据id查询") 
@PostMapping("/show")
public Responses show(@RequestParam(value="userId",defaultValue="-1") Long userId) {
    Record data = recordService.getOne(vo.getId());
    return Responses.success(data);

}

the n-submit, use annotations @RequestBody.

@RequestBody main POST method for receiving a distal json string data passed to the back end (the request body data); GET mode when no request body, so use @RequestBody received data, can not use the GET distal submission data, but rather submitted with the POST method. In the same receiver's back-end method, @ RequestBody and @RequestParam () can be used simultaneously, @ RequestBody can only have at most one, and @RequestParam () can have more.

Note: a request, only a requestBody; a request can have multiple RequestParam.

 @ApiOperation(value = "根据id查询") 
 @PostMapping("/get")
 public Responses getOne(@Validated @RequestBody IdVO vo){
     Record data = recordService.getOne(vo.getId());
     return Responses.success(data);
 }

athVariable

@RestController
@RequestMapping("/")
public class ChineseDrugController {
	@ResponseBody
	@RequestMapping(value = "/{name}")
	public String showName(@PathVariable String name, @PathVariable(value = "name", required = false) String sex) {
		return "Hello " + name + sex;
	}

@fthfrm

url:http://127.0.0.1:8080/sexvalue/namevalue?name=唐&sex=男

@RestController
@RequestMapping(value = "/{sex}")
public class ChineseDrugController {
	@ResponseBody
	@RequestMapping(value = "/{name}")
	public String showName(@PathVariable(value = "name") String name, @PathParam(value = "sex") String sex) {
		return "Hello " + name + " " + sex;
	}
}

Note: The above code is just to show good flexibility features, so the actual development to avoid any use.

4) verification request parameter

Parameter check

① using annotations @Validated, so that automatic calibration parameters take effect, which is spring-contex of annotations;

②vo class custom check all kinds, such as @NotNull, etc., he is not repeated under javax validation-api annotations in here;

③ program level check.

A method as Example

@ApiOperation(value = "应用类型和应用关系绑定")
@PostMapping("/applicationTypeBind")
public Boolean applicationTypeBind(@Validated @RequestBody ApplicationBindVO vo){
    applicationTypeService.applicationTypeBind(vo);
    return true;
}

VO class corresponding to Example

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Set;

@Data
@ApiModel(value = "ApplicationBindVO",description = "关系绑定vo")
public class ApplicationBindVO {

    @NotNull
    @ApiModelProperty("应用类型id")
    private Long typeId;

    @ApiModelProperty("应用id集合")
    private List<Long> applicationIdList;
}

 5) into the parametric design parameters

Based business may be, as far as possible unified format;

Distal response parameters (APP / PC), typically a layer of re-encapsulation, convenient unitary front end, returns the following

Responses.success(data);
import com.fasterxml.jackson.annotation.JsonView;
import com.myfutech.common.util.enums.ResponseCode;
import com.myfutech.common.util.vo.BaseView;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(value = "Responses",description = "响应信息")
public class Responses<T> {
   
 @JsonView({BaseView.class})
    @ApiModelProperty("响应编码")
    private String code;
    
    @JsonView({BaseView.class})
    @ApiModelProperty("响应消息")
    private String msg;
    
    @JsonView({BaseView.class})
    @ApiModelProperty("响应体")
    private T result;
    
    public static <T> Responses<T> success() {
        return new Responses(ResponseCode.SUCCESS_CODE, "", (Object)null);
    }

    public static <T> Responses<T> success(T result) {
        return new Responses(ResponseCode.SUCCESS_CODE, "", result);
    }

    public static <T> Responses<T> success(String msg, T result) {
        return new Responses(ResponseCode.SUCCESS_CODE, msg, result);
    }

    public static <T> Responses<T> error(String msg) {
        return new Responses(ResponseCode.ERROR_CODE, msg, (Object)null);
    }

    public static <T> Responses<T> error(ResponseCode code) {
        return new Responses(code, code.getDefaultMsg(), (Object)null);
    }

    public static <T> Responses<T> error(ResponseCode code, String msg) {
        return new Responses(code, msg, (Object)null);
    }

    public Responses() {
    }

    private Responses(ResponseCode code, String msg, T result) {
        this.code = code.getCode();
        this.msg = msg;
        this.result = result;
    }

    public String getCode() {
        return this.code;
    }

    public boolean notSuccess() {
        return !ResponseCode.SUCCESS_CODE.getCode().equals(this.code);
    }

    public String getMsg() {
        return this.msg;
    }

    public T getResult() {
        return this.result;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public void setResult(T result) {
        this.result = result;
    }
    
    
}

6) automatically generates interface documentation

    使用SwaggerAPI,

    Common Annotations

//加载类名之上
@Api(tags = "日志相关接口", description="操作日志",
        consumes= MediaType.APPLICATION_JSON_UTF8_VALUE,
        produces=MediaType.APPLICATION_JSON_UTF8_VALUE)


//加在方法名之上
@ApiOperation(value = "查询分页列表")

//加载实体或VO类名之上
@Data
@ApiModel(value = "ApprovalRoleModifyVO",description = "审批角色修改信息")
public class ApprovalRoleModifyVO{

 @Api : acting on the class, the class label for a specific implementation content. This class is a flag indicating swagger of resources. 

    parameter: 

    ①tags: You can use tags () allows you to set the properties of multiple tags for the operation, instead of using the property. 

    ②description: description may describe such effect. 

@ApiOperation : A method for indicating that the operation of a http request.

@ApiModel : a method, field, or data on an explanatory model attribute change operation 

 2, an example of a relatively standard controller class

package com.myfutech.employee.service.provider.ctrl;

import com.myfutech.common.util.Responses;
import com.myfutech.common.util.vo.IdVO;
import com.myfutech.common.util.vo.Page;
import com.myfutech.common.util.vo.Pageable;
import com.myfutech.employee.service.api.vo.response.record.RecordListVo;
import com.myfutech.employee.service.provider.model.Record;
import com.myfutech.employee.service.provider.service.RecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 *  相关接口
 */
@Api(tags = "日志相关接口", description="操作日志",
        consumes= MediaType.APPLICATION_JSON_UTF8_VALUE,
        produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/record")
public class RecordCtrl {


    private static final Logger log = LoggerFactory.getLogger(RecordCtrl.class);

    @Resource(name="recordService") 
    private RecordService recordService;

    @ApiOperation(value = "查询分页列表")
    @PostMapping("/page")
    public Page<RecordListVo> page( @RequestBody Pageable pageable){
        Page<RecordListVo> list = recordService.findConditionPage(pageable);
        return list;
    }
    @ApiOperation(value = "根据id查询") 
    @PostMapping("/get")
    public Responses getOne(@Validated @RequestBody IdVO vo){
        Record data = recordService.getOne(vo.getId());
        return Responses.success(data);
    }
    @ApiOperation(value = "新增") 
    @PostMapping("/add")
    public Responses add(@Validated(Record.Create.class) @RequestBody Record data){
        recordService.save(data);
        return Responses.success();
    }
    @ApiOperation(value = "更新") 
    @PostMapping("/update")
    public Responses update(@Validated(Record.Update.class) @RequestBody Record data){
        recordService.save(data);
        return Responses.success();
    }
    @ApiOperation(value = "删除") 
    @PostMapping("/delete")
    public Responses delete(@Validated @RequestBody IdVO vo){
        recordService.deleteById(vo.getId());
        return Responses.success();
    }
}

 

Guess you like

Origin blog.csdn.net/jiahao1186/article/details/90634764