java -- SpringMVC表现层数据封装详解

表现层数据封装

介绍

1. ModelAndView

ModelAndView是Spring MVC提供的一个对象,用于封装模型数据和视图信息。当Controller处理完用户请求后,会返回一个ModelAndView对象给DispatcherServlet,DispatcherServlet再解析这个对象,找到对应的视图,并将模型数据传递给视图进行渲染。

java 复制代码
@RequestMapping("/hello")  
public ModelAndView hello() {  
    ModelAndView mv = new ModelAndView();  
    mv.addObject("message", "Hello, World!");  
    mv.setViewName("hello");  
    return mv;  
}

2. ModelMap

ModelMap是一个实现了Map<String, Object>接口的类,用于存储模型数据。Spring MVC会自动将ModelMap中的数据添加到请求对象中,从而可以在视图中访问。

在Controller的方法中,可以通过添加ModelMap类型的参数来接收模型数据,或者返回ModelAndView时通过addObject方法添加数据。

java 复制代码
@RequestMapping("/hello")  
public String hello(ModelMap model) {  
    model.addAttribute("message", "Hello, World!");  
    return "hello";  
}

3. @ModelAttribute

@ModelAttribute注解可以用在方法上或参数上。当用在方法上时,表示该方法的返回值会自动添加到模型中。当用在参数上时,表示该参数的值将从请求参数、路径变量、Session或Model中自动获取。

  • 用在方法上
java 复制代码
@ModelAttribute  
public void populateModel(@RequestParam String userId, Model model) {  
    User user = userService.getUser(userId);  
    model.addAttribute("user", user);  
}
  • 用在参数上
java 复制代码
@RequestMapping("/editUser")  
public String editUser(@ModelAttribute("user") User user) {  
    // 这里user对象的属性已经根据请求参数被填充  
    return "editUser";  
}

4. @RequestParam 和 @PathVariable

  • @RequestParam用于将请求参数绑定到你的控制器处理方法的参数上。
java 复制代码
@RequestMapping("/user")  
public String getUser(@RequestParam("id") String userId) {  
    // 使用userId...  
    return "user";  
}
  • @PathVariable用于将URL模板变量绑定到你的控制器处理方法的参数上。
java 复制代码
@RequestMapping("/user/{userId}")  
public String getUser(@PathVariable("userId") String userId) {  
    // 使用userId...  
    return "user";  
}

1 表现层响应数据的问题

问题:我们表现层增删改方法返回true或者false表示是否成功,getById()方法返回一个json对象,getAll()方法返回一个json对象数组,这里就出现了三种格式的响应结果,极其不利于前端解析。

解决:我们需要统一响应结果的格式

2 定义Result类封装响应结果

2.1 Result类封装响应结果
java 复制代码
public class Result {
    //描述统一格式中的数据
    private Object data;
    //描述统一格式中的编码,用于区分操作,可以简化配置0或1表示成功失败
    private Integer code;
    //描述统一格式中的消息,可选属性
    private String msg;

    public Result() {
    }
    public Result(Integer code,Object data) {
        this.data = data;
        this.code = code;
    }
    public Result(Integer code, Object data, String msg) {
        this.data = data;
        this.code = code;
        this.msg = msg;
    }
     //同学们自己添加getter、setter、toString()方法
}

注意事项:

Result类中的字段并不是固定的,可以根据需要自行增减

2.2 Code类封装响应码
java 复制代码
//状态码
public class Code {
    public static final Integer SAVE_OK = 20011;
    public static final Integer DELETE_OK = 20021;
    public static final Integer UPDATE_OK = 20031;
    public static final Integer GET_OK = 20041;

    public static final Integer SAVE_ERR = 20010;
    public static final Integer DELETE_ERR = 20020;
    public static final Integer UPDATE_ERR = 20030;
    public static final Integer GET_ERR = 20040;
}

注意事项:

Code类的常量设计也不是固定的,可以根据需要自行增减,例如将查询再进行细分为GET_OK,GET_ALL_OK,GET_PAGE_OK

3 表现层数据封装返回Result对象

java 复制代码
@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);
        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Book book = bookService.getById(id);
        Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
        String msg = book != null ? "" : "数据查询失败,请重试!";
        return new Result(code,book,msg);
    }

    @GetMapping
    public Result getAll() {
        List<Book> bookList = bookService.getAll();
        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = bookList != null ? "" : "数据查询失败,请重试!";
        return new Result(code,bookList,msg);
    }
}
相关推荐
api茶飘香32 分钟前
守护应用边界:通过反射API实现安全的输入输出过滤
java·开发语言·python·安全·django·virtualenv·pygame
杀死一只知更鸟debug33 分钟前
策略模式的小记
java·开发语言·策略模式
nice6666033 分钟前
CSS的基本语法
java·前端·css·visual studio code
efls11134 分钟前
Qt_了解Qt Creator
开发语言·qt
请揣满RMB38 分钟前
Qt常用控件——QRadioButton和QCheckBox
开发语言·c++·qt
阿巴~阿巴~38 分钟前
C_深入理解指针(五) —— sizeof和strlen的对比、数组和指针笔试题解析、指针运算笔试题解析
c语言·开发语言·数据结构·算法
安全在心中2 小时前
python-网页自动化(三)
运维·python·自动化
爱吃桃子的ICer2 小时前
[UVM]3.核心基类 uvm_object 域的自动化 copy() compare() print() pack unpack
开发语言·前端·ic设计
Slow2 小时前
自动化焊缝定义程序fe-safe
运维·python·自动化
ever_up9733 小时前
EasyExcel的导入与导出及在实际项目生产场景的一下应用例子
java·开发语言·数据库