首先,从模块的业务场景和业务功能出发,考虑需要提供哪些接口,每个接口的名称,需要哪些参数(是否必填、参数类型等),以及返回什么数据。这是从业务需求的角度来考虑的,不容易跑偏,避免编写不需要的代码,做无用功。
- 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>