controller層在MVC設(shè)計(jì)中屬于控制層;設(shè)計(jì)初衷:接受請(qǐng)求并響應(yīng)請(qǐng)求;所以,該層盡量輕薄,避免編寫涉及業(yè)務(wù)處理的代碼。
前后端分離的開發(fā)設(shè)計(jì)模式下,推薦使用@RestController注解,它相當(dāng)于@ResponseBody + @Controller的組合使用。
1) 如果只是使用@RestController注解Controller類,則Controller中的方法無(wú)法返回jsp頁(yè)面,或者h(yuǎn)tml,配置的視圖解析器InternalResourceViewResolver不起作用,返回的內(nèi)容就是Return 里的內(nèi)容,默認(rèn)轉(zhuǎn)成json串。
2) 如果需要返回到指定頁(yè)面,則需要用 @Controller配合視圖解析器InternalResourceViewResolver才行。
??? 如果需要返回JSON,XML或自定義mediaType內(nèi)容到頁(yè)面,則需要在對(duì)應(yīng)的方法上加上@ResponseBody注解。
總之,使用@Controller 注解,在對(duì)應(yīng)的方法上,視圖解析器可以解析return 的jsp,html頁(yè)面,并且跳轉(zhuǎn)到相應(yīng)頁(yè)面;若返回json等內(nèi)容到頁(yè)面,則需要加@ResponseBody注解
1)設(shè)定請(qǐng)求路徑
使用注解@PostMapping("/page"),類命名和方法命名之上都可以加。
注意按照不同業(yè)務(wù)進(jìn)行劃分使用,避免亂寫亂用。
2)設(shè)置請(qǐng)求方式
? ??常用的POST/GET。使用注解:@RequestMapping ??和 ?@GetMapping @PostMapping。
? ? Spring4.3中引進(jìn)了{@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping} 來(lái)幫助簡(jiǎn)化常用的HTTP方法的映射 并更好地表達(dá)被注解方法的語(yǔ)義?
該注解將HTTP Get 映射到 特定的處理方法上
? ? @GetMapping是一個(gè)組合注解,它是@RequestMapping(method = RequestMethod.GET)的縮寫
? ? @PostMapping是一個(gè)組合注解,它是@RequestMapping(method = RequestMethod.POST)的縮寫
3)設(shè)置請(qǐng)求參數(shù)方式
①表單提交,直接使用vo類或具體參數(shù)名接收;
@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 有三個(gè)屬性:
(1)value:請(qǐng)求參數(shù)名(必須配置)
(2)required:是否必需,默認(rèn)為 true,即 請(qǐng)求中必須包含該參數(shù),如果沒有包含,將會(huì)拋出異常(可選配置)
(3)defaultValue:默認(rèn)值,如果設(shè)置了該值,required 將自動(dòng)設(shè)為 false
@ApiOperation(value = "根據(jù)id查詢")
@PostMapping("/show")
public Responses show(@RequestParam(value="userId",defaultValue="-1") Long userId) {
? ? Record data = recordService.getOne(vo.getId());
? ? return Responses.success(data);
}
③n提交,使用注解@RequestBody。
@RequestBody主要用來(lái)接收前端以POST方式傳遞給后端的json字符串中的數(shù)據(jù)的(請(qǐng)求體中的數(shù)據(jù)的);GET方式無(wú)請(qǐng)求體,所以使用@RequestBody接收數(shù)據(jù)時(shí),前端不能使用GET方式提交數(shù)據(jù),而是用POST方式進(jìn)行提交。在后端的同一個(gè)接收方法里,@RequestBody與@RequestParam()可以同時(shí)使用,@RequestBody最多只能有一個(gè),而@RequestParam()可以有多個(gè)。
注:一個(gè)請(qǐng)求,只有一個(gè)RequestBody;一個(gè)請(qǐng)求,可以有多個(gè)RequestParam。
@ApiOperation(value = "根據(jù)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;
}
⑤@PathParam
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;
}
}
說明:以上代碼僅僅展示功能上有很好的靈活性,實(shí)際開發(fā)中避免如此任意使用?。
4)校驗(yàn)請(qǐng)求參數(shù)
參數(shù)校驗(yàn)
①使用注解@Validated,使得參數(shù)自動(dòng)校驗(yàn)生效,它是spring-contex中的注解;
②vo類中自定義各類校驗(yàn),比如@NotNull等,他是javax下validation-api中的注解此處不贅述;
③程序?qū)用娴男r?yàn)。
方法示例如下
@ApiOperation(value = "應(yīng)用類型和應(yīng)用關(guān)系綁定")
@PostMapping("/applicationTypeBind")
public Boolean applicationTypeBind(@Validated @RequestBody ApplicationBindVO vo){
? ? applicationTypeService.applicationTypeBind(vo);
? ? return true;
}
對(duì)應(yīng)VO類示例
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 = "關(guān)系綁定vo")
public class ApplicationBindVO {
? ? @NotNull
? ? @ApiModelProperty("應(yīng)用類型id")
? ? private Long typeId;
? ? @ApiModelProperty("應(yīng)用id集合")
? ? private List<Long> applicationIdList;
}
?5)入?yún)⒊鰠⒃O(shè)計(jì)
依據(jù)業(yè)務(wù)而定,格式盡量做到統(tǒng)一;
響應(yīng)前端(APP/PC)的參數(shù),一般再封裝一層,方便前端統(tǒng)一處理,如下返回
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 = "響應(yīng)信息")
public class Responses<T> {
@JsonView({BaseView.class})
? ? @ApiModelProperty("響應(yīng)編碼")
? ? private String code;
? ? @JsonView({BaseView.class})
? ? @ApiModelProperty("響應(yīng)消息")
? ? private String msg;
? ? @JsonView({BaseView.class})
? ? @ApiModelProperty("響應(yīng)體")
? ? 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) 自動(dòng)生成接口文檔
? ? 使用SwaggerAPI,
? ? 常用注解
//加載類名之上
@Api(tags = "日志相關(guān)接口", description="操作日志",
? ? ? ? consumes= MediaType.APPLICATION_JSON_UTF8_VALUE,
? ? ? ? produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
//加在方法名之上
@ApiOperation(value = "查詢分頁(yè)列表")
//加載實(shí)體或VO類名之上
@Data
@ApiModel(value = "ApprovalRoleModifyVO",description = "審批角色修改信息")
public class ApprovalRoleModifyVO{
?@Api:作用在類上,用來(lái)標(biāo)注該類具體實(shí)現(xiàn)內(nèi)容。表示標(biāo)識(shí)這個(gè)類是swagger的資源 。?
? ? 參數(shù):?
? ? ①tags:可以使用tags()允許您為操作設(shè)置多個(gè)標(biāo)簽的屬性,而不是使用該屬性。?
? ? ②description:可描述描述該類作用。?
@ApiOperation:用于方法,表示一個(gè)http請(qǐng)求的操作 。
@ApiModel:用于方法,字段 ,表示對(duì)model屬性的說明或者數(shù)據(jù)操作更改?
?2、一個(gè)相對(duì)標(biāo)準(zhǔn)controller類示例
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;
/**
*? 相關(guān)接口
*/
@Api(tags = "日志相關(guān)接口", 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 = "查詢分頁(yè)列表")
? ? @PostMapping("/page")
? ? public Page<RecordListVo> page( @RequestBody Pageable pageable){
? ? ? ? Page<RecordListVo> list = recordService.findConditionPage(pageable);
? ? ? ? return list;
? ? }
? ? @ApiOperation(value = "根據(jù)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();
? ? }
}