SpringBoot之訪問控制層Controller


首先,從模塊的業務場景和業務功能出發,考慮需要提供哪些接口,每個接口的名稱,需要哪些參數(是否必填、參數類型等),以及返回什么數據。這是從業務需求的角度來考慮的,不容易跑偏,避免編寫不需要的代碼,做無用功。

  • StudentController繼承BaseController
@Controller
@RequestMapping(value = "/student")
public class StudentController extends BaseController {

    @Autowired
    private StudentService studentService;

    @RequestMapping(value = "/students")
    public ModelAndView students(Integer classId) throws Exception {
        return feedback(studentService.findByClass(classId));
    }
}
  • 其中BaseController封裝訪問控制層公用方法
public class BaseController {

    protected ModelAndView feedback(Object obj) {
        Object result = obj != null ? obj : "success";
        Map<String, Object> data = new HashMap<>();
        data.put("errcode", 0);
        data.put("result", result);
        return new ModelAndView(new JsonView(data));
    }
}
  • 其中使用到了自定義視圖JsonView,用於接口返回json格式的數據,代碼如下:
public class JsonView extends AbstractView {

    private Object result;

    public JsonView(Object result) {
        super();
        this.result = result;
    }

    @Override
    protected void renderMergedOutputModel(Map<String, Object> map, HttpServletRequest httpServletRequest,
                                           HttpServletResponse response) throws Exception {
        response.setContentType("application/json; charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write(JSON.toJSONString(result));
    }
}
  • 這里我們用到了阿里巴巴的fastjson,通過pom.xml引入
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.28</version>
</dependency>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM