@ModelAttribute 用法

2023-08-15 09:42:54 浏览数 (1)

代码语言:javascript复制
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class BaseController {
    private String userId;

    @ModelAttribute
    public void getUserId(HttpServletRequest request){
        userId = String.valueOf(request.getAttribute("user-id"));
    }

    public String getUserId(){
        return userId;
    }
}

可以调用getUserId即可获取用户创建人信息

代码语言:javascript复制
@RestController
@RequestMapping("/hello/world")
@Validated
public class HelloController extends BaseController{
    @Resource
    private XXService xxService;

    @PostMapping("/create")
    @Operation(summary = "创建XXX")
    public CommonResult<String> addXXXX(@Valid @RequestBody XXCreateReqDTO createReqDTO) {
        createReqDTO.setCreatorId(getUserId());
        return success(xxService.createBizFlow(createReqDTO));
    }
}

0 人点赞