简述

  SpringMVC 是一种基于 Java 的实现 MVC 设计模型的请求驱动类型的轻量级 Web 框架,属于 Spring FrameWork 的后续产品,已经融合在 Spring Web Flow 里面。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,从而在使用 Spring 进行 WEB 开发时,可以选择使用 Spring的 Spring MVC 框架或集成其他 MVC 开发框架,如 Struts1(现在一般不用),Struts2 等。

  SpringMVC 已经成为目前最主流的 MVC 框架之一,并且随着 Spring3.0 的发布,全面超越 Struts2,成为最优秀的 MVC 框架。它通过一套注解,让一个简单的 Java 类成为处理请求的控制器,而无须实现任何接口。同时它还支持RESTful 编程风格的请求。

SpringMVC的优势

  SpringMVC有清晰的模块划分,把任务分配给角色各司其职

  和spring其他框架能进行无缝连接

  可适配,通过 HandlerAdapter 可以支持任意的类作为处理器。

  可定制性,HandlerMapping、ViewResolver 等能够非常简单的定制

SpringMVC的执行流程

RequestMapping注解

  用于建立请求 URL 和处理请求方法之间的对应关系,它可以放在类上,也可以放在方法上,它的value属性和path属性是一个路径

  method属性用于指定请求的类型,它是枚举类型,method = RequestMethod.POST即为post请求,method = RequestMethod.GET即为get请求

  headers属性指定请求的头部,比如headers = “content-type=text/*” 可以指定网页的数据编码类型

  params属性可以指定请求的参数,如果参数不匹配就无法响应

  被RequestMapping注解的方法可以加参数,可以用来接受http的请求数据,但变量名和请求的key名要一致

SpringMVC相关注解

  通过代码侵入性较弱的注解的方式,springmvc提供了一套实现各种功能的注解,常用注解如下:

@Controller

  @Controller标注在类上,表明这个类就是一个SpringMVC Controller 对象。分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了@RequestMapping 注解。

@Controller
public class StudentController {
    
}

@RequestMapping

  @RequestMapping注解标注到方法上并关联一个url路径,表示该路径的请求会由该方法进行处理

  如果不加下面的@ResponseBody注解,返回值会通过视图处理器ViewResolver处理为页面的URL,然后跳转到对应页面中

@Controller
public class StudentController {
    @RequestMapping("/getStudent")
    String getStudent(){
        return "student";
    }
}

  像这样返回string,会跳转到

@ResponseBody  

  @ResponseBody注解标注在方法上,表示该方法返回值会通过HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

  或者标注在类上,表示该类所有方法均设置成ResponseBody方法返回数据

@Controller
public class StudentController {
    @RequestMapping("/getStudent")
    @ResponseBody
    public String getStudent(){
        return "student";
    }
}

  现在这个方法的返回值会被视为HTTP的响应体

  如果返回值是类,那么框架会自动序列化为JSON格式

@Controller
public class StudentController {
    @RequestMapping("/getStudent")
    @ResponseBody
    public Student getStudent(){
        return new Student("xiaoming",18);
    }
}

@RequestBody

  @RequestBody注解标注在方法参数前面,用来解析前端请求体中传递给后端的json字符串中的数据,像这样前端的json数据会被解析封装为一个Student类

@Controller
public class StudentController {
@RequestMapping("/getStudent")
@ResponseBody
public String getStudent(@RequestBody Student student){
System.out.println(student);
return "student";
}
}

@ResponseStatus

  @ResponseStatus注解用于返回特定的HTTP状态码,例如下面代码返回的是201

@Controller
public class StudentController {
    @RequestMapping("/getStudent")
    @ResponseBody
    @ResponseStatus(HttpStatus.CREATED)
    public String getStudent(@RequestBody Student student){
        System.out.println(student);
        return "student";
    }
}

@PathVariable

  @PathVariable注解使用在方法参数前,用于取出放在url上的参数,需配合RequestMapping使用

  在url里用大括号将要传入的参数进行标注,我们就可以把url上的参数拿到了

@Controller
public class StudentController {
    @RequestMapping("/student/{id}")
    @ResponseBody
    public String getStudent(@PathVariable Integer id){
        System.out.println(id);
        return "student";
    }
}

@RequestParam

  @RequestParam注解标注在参数前,用于获取get请求中url用?方式传递的参数

@Controller
public class StudentController {
    @RequestMapping("/student")
    @ResponseBody
    public String getStudent(@RequestParam Integer id){
        System.out.println(id);
        return "student";
    }
}

参数校验

  我们可以校验前端传入的参数是否符合我们的要求

  一种方法是我们可以手动取出前端的参数,自己判空,为空抛异常,但是这样太麻烦了

  我们可以在封装的类的成员上标注@NotNull,这是JDK提供的注解

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    @NotNull
    private String name;
    private Integer age;
}

  然后在Controller类中方法的参数列表上标注@Valid,此时框架就会自动帮我们校验该参数的状态

@Controller
public class StudentController {
    @RequestMapping("/student")
    @ResponseBody
    public String getStudent(@RequestBody @Valid Student student){
        return student.toString();
    }
}

异常处理

ResponseStatusException

  我们可以在需要抛出异常的地方抛出spring框架为我们提供的异常ResponseStatusException

@Controller
public class StudentController {
    @RequestMapping("/student")
    @ResponseBody
    public String getStudent(){
        throw new ResponseStatusException(HttpStatus.NOT_FOUND,"Student not fund!");
    }
}

  我们在异常中设置http的状态码和异常的信息

  如果使用此方法的话要在yml进行配置

server:
  error:
    include-message: always

自己定义的异常

  我们可以抛出自己定义的异常,方便我们定义业务中的问题,同时发生异常后的返回数据格式我们也可以自己定义

  例如我们定义如下的错误返回数据

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ErrorResult {
    private String message;
}

  我们定义了如下的自定义异常

public class StudentNotFoundException extends RuntimeException {
    public StudentNotFoundException(String message) {
        super(message);
    }
}

  然后我们创建一个类用于处理异常,然后可以使用@ControllerAdvice注解进行标注,在类中每一个方法对应一个异常

  然后我们就可以构建我们的错误返回数据类,并将错误信息返回至前端

@ExceptionHandler(CarNotFoundException.class)
public ResponseEntity<ErrorResult> handle(CarNotFoundException ex) {
ErrorResult errorResult = new ErrorResult(ex.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResult);
}

  我们也可以直接返回errorResult,此时记得要加@ResponseBody

@ExceptionHandler(StudentNotFoundException.class)
@ResponseBody
public ErrorResult handle(StudentNotFoundException ex) {
    ErrorResult errorResult = new ErrorResult(ex.getMessage());
    return errorResult;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  

 

 

 

 

 

 

  

 

原文地址:http://www.cnblogs.com/CNLayton/p/16819211.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性