记录一个Spring MVC Controller层,跳转到前端页面以及返回参数的包装类
程序员文章站
2022-05-24 13:14:02
...
以下两个为常用方法
1. 进入到前端页面的方法为 createMav()
2. 返回ajax请求的方法为 successResponse()
代码实现 如下 :
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
/** Created by HUYONG on 2017/9/8*/
public abstract class BaseController {
public HttpServletRequest getRequest() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
return request;
}
public HttpServletResponse getResponse() {
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getResponse();
return response;
}
public Result successResponse() {
return successResponse(null);
}
public Result successResponse(Map<String, Object> model) {
Result result = new Result();
result.setRet(200);
result.setMsg("success");
result.setModel(model);
return result;
}
public Result successResponse(Map<String, Object> model, String msg) {
Result result = new Result();
result.setRet(200);
result.setMsg(msg);
result.setModel(model);
return result;
}
public ModelAndView createMav(String viewName, Map<String, ?> model) {
return new ModelAndView(viewName, model);
}
public int getStart(Integer start){
return start == null? 0 : start.intValue();
}
public int getLimit(Integer limit){
return limit == null? 10 : limit.intValue();
}
@JsonInclude(Include.NON_NULL)
public static class Result {
private int ret;
private String msg;
private Map<String, Object> model;
public int getRet() {
return ret;
}
public void setRet(int ret) {
this.ret = ret;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Map<String, Object> getModel() {
return model;
}
public void setModel(Map<String, Object> model) {
this.model = model;
}
public void addModel(String key, Object object) {
if (model == null) {
model = new HashMap<>();
}
model.put(key, object);
}
}
}
controller层具体使用 如下
@Controller
@RequestMapping("/admin/courseMt")
public class CourseMaintenanceController extends BaseController{
/**
* 进入web-inf 目录下的admin目录的index.jsp ,并传递参数 a ,index 页面 用 ${a} 获取
* @return
*/
@RequestMapping("/index")
public ModelAndView index(){
Map<String,Object> map = Maps.newConcurrentMap();
map.put("a","1");
return createMav("admin/index",map);
}
/**
* 返回前端JS发送ajax请求响应 , 由于 BaseController 进行封装,所以ajax返回数据用 data.model.a 获取
* @return
*/
@RequestMapping("/getCourseMtList")
@ResponseBody
public Result getCourseMtList(int pageNum,int pageSize){
Map<String,Object> map = Maps.newConcurrentMap();
map.put("a","1");
return successResponse(map); }
}
上一篇: 高绩效团队建设如何实现?