Spring MVC 学习

76 阅读3分钟

Spring MVC 学习

1. 请求与响应

1.1 请求

1.1.1 Json 数据传递

  1. 导入Json依赖
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.0</version>
</dependency>
  1. springMVCConfig类中,添加注解@EnableWebMvc,开启自动转换JSOn数据支持
@EnableWebMvc
  1. 在对应接口上,添加@RequestBody注解,即可接收
public class UserController {
    // 2.2 设置当前操作访问路径
    @RequestMapping("/save")
    // 2.3 设置当前操作的返回值类型
    @ResponseBody
    public String save(){
        System.out.println("user save....");
        return "{'module': 'springmvc'}";
    }

    @RequestMapping("/pojoParam")
    // 2.3 设置当前操作的返回值类型
    @ResponseBody
    public String pojoParam(@RequestBody User user){
        System.out.println("user save...." + user);
        return "{'module': 'springmvc'}";
    }

    @RequestMapping("/listParamForJson")
    // 2.3 设置当前操作的返回值类型
    @ResponseBody
    public String listParamForJson(@RequestBody List<User> likes){
        System.out.println("user save...." + likes);
        return "{'module': 'springmvc'}";
    }
}

1.1.2 日期类型参数传递

image.png

1.2 响应

public class UserController {
    @RequestMapping("/toJumpPage")
    @ResponseBody
    public String toJumpPage(){
        System.out.println("跳转");
        return "index.jsp";
    }

    @RequestMapping("/toText")
    @ResponseBody
    public String toText(){
        System.out.println("文本");
        return "response text";
    }

    @RequestMapping("/toJsonList")
    @ResponseBody
    public User toJsonList(){
        System.out.println("文本");
        User user = new User();
        user.setName("lyq");
        user.setAge(15);
        return user;
    }
}

1.3 REST 风格

image.png

案例

public class UserController {
    @RequestMapping(value = "/users", method = RequestMethod.POST)
    @ResponseBody
   public String save(){
       System.out.println("user save...");
       return "{'module' : 'user save'}";
    }

    @RequestMapping(value = "/users", method = RequestMethod.DELETE)
    @ResponseBody
    public String delete(Integer id){
        System.out.println("user delete..." + id);
        return "{'module' : 'user delete'}";
    }

    @RequestMapping(value = "/users/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public String update(@PathVariable Integer id){
        System.out.println("user update..." + id);
        return "{'module' : 'user update'}";
    }

    @RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getById(@PathVariable Integer id){
        System.out.println("user getById..." + id);
        return "{'module' : 'user getById'}";
    }

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    @ResponseBody
    public String getAll(){
        System.out.println("user getAll...");
        return "{'module' : 'user getAll'}";
    }
}

image.png

案例:对上述REST风格升级


@RequestMapping("/books")
@RestController

public class BookController {
    @PostMapping
    public String save(){
        System.out.println("user save...");
        return "{'module' : 'user save'}";
    }
    @DeleteMapping("/{id}")
    public String delete(Integer id){
        System.out.println("user delete..." + id);
        return "{'module' : 'user delete'}";
    }
    @PutMapping("/{id}")
    public String update(@PathVariable Integer id){
        System.out.println("book update..." + id);
        return "{'module' : 'book update'}";
    }
    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id){
        System.out.println("book getById..." + id);
        return "{'module' : 'book getById'}";
    }

    @GetMapping
    public String getAll(){
        System.out.println("book getAll...");
        return "{'module' : 'book getAll'}";
    }
}
  • 对静态资源进行放行 image.png

二、SSM 整合

2.1 SSM 整合流程

  1. 创建工程(Maven-webApp)
  2. 添加对应的文件夹(例如添加:java、resources)
  3. SSM 整合
    • Spring
      • SpringConfig
    • Mybatis
      • MybatisConfig
      • JdbcConfig
      • jdbc.properties
    • SpringMVC
      • ServletConfig
      • SpringMvcConfig
  4. 功能模块
    • 表与实体表
    • dao(接口+自动代理)
    • service(接口+实现类)
      • 业务层接口测试(整合 Junit)
    • controller
      • 表现层接口测试(PostMan)

2.2 表现层数据封装(和前端约定格式)

image.png image.png

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

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

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean update = bookService.update(book);
        return new Result(update? Code.UPDATE_OK : Code.UPDATE_ERR ,update);
    }
    @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);
    }
}

2.3 异常处理器

  • 出现异常现象的常见位置与常见诱因如下:
    • 框架内部抛出的异常:因使用不合规导致
    • 数据层抛出的异常:因外部服务器故障导致(例如∶服务器访问超时)
    • 业务层抛出的异常:因业务逻辑书写错误导致(例如:遍历业务书写操作,导致索引异常等)
    • 表现层抛出的异常:因数据收集、校验等规则导致(例如:不匹配的数据类型间导致异常)
    • 工具类抛出的异常:因工具类书写不严谨不够健壮导致(例如:必要释放的连接长期未释放等)

案例:在 Controller 表现层,新建异常处理类

@RestControllerAdvice
public class ProjectExceptionAdvice {
    @ExceptionHandler(Exception.class)
    public void doException(Exception ex){
        System.out.println("我抓住你了:" + ex);
    }
}

2.3.1 项目异常处理方案

  • 业务异常
    • 发送对应消息传递给用户,提醒规范操作
  • 系统异常
    • 发送固定消息传递给用户,安抚用户
  • 其他异常
    • 发送固定消息传递给用户,安抚用户

案例:自定义异常 BusinessException.class类

package com.lyq.exception;

/*
 *  @author 李永奇
 *  @version 1.0
 */
public class BusinessException extends RuntimeException{
    private Integer code;


    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public BusinessException(Integer code) {
        this.code = code;
    }

    public BusinessException(String message, Integer code) {
        super(message);
        this.code = code;
    }

    public BusinessException(String message, Throwable cause, Integer code) {
        super(message, cause);
        this.code = code;
    }

    public BusinessException(Throwable cause, Integer code) {
        super(cause);
        this.code = code;
    }

    public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Integer code) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.code = code;
    }
}

触发异常

image.png

在Controller里面定义处理异常类,对异常进行统一处理

/*
 *  @author 李永奇
 *  @version 1.0
 */
@RestControllerAdvice
public class ProjectExceptionAdvice {
    @ExceptionHandler(Exception.class)
    public Result doException(Exception ex){
        return new Result (1,null, ex.getMessage()) ;
    }

    @ExceptionHandler(Exception.class)
    public Result doBusinessException(BusinessException ex){
        return new Result (1,null, ex.getMessage()) ;
    }

    @ExceptionHandler(Exception.class)
    public Result doSystemException(SystemException ex){
        return new Result (1,null, ex.getMessage()) ;
    }
}