SpringMVC
1.依赖
2.注解
@RequestMapping ( "请求路径" )
属性:method设置请求方式
@RequestMapping ( value = "a" , method = RequestMethod . GET )
等同: @GetMapping
@PathVariable ( "路径参数名" ) -- > 获取路径参数
@RequestParam ( "请求参数名" ) -- > 获取请求参数
@RequestBody -- > 获取请求体数据,把前端json转换java对象
@ResponseBody -- > 将java对象转换为json数据发送给前端
@RestController = @ResponseBody + @Controller 将整个类方法返回值全部为json
@CookieValue ( "key" ) -- > 接受Cookie 值
@RequestHeader ( "请求头key" ) -- > 获取请求头信息
@CrossOrigin -- > 解决跨域问题
★:ModelAndView :
Model model: 存储域对象数据为request域
ModelAndView mav = new ModelAndView ( ) ;
mav. setViewName ( "welcome" ) ;
mav. addObject ( "message" , "hello kitty" ) ;
重定向和转发:
"forward:xxxx" -- > 转发
"redirect:xxx" -- > 重定向
RestFul : 增:/ user @PostMapper ( )
删: / user/ 1 @DeleteMapper ( )
改: / user @PutMapper ( )
查:/ user @GetMapper ( )
3.Web.xml
< servlet>
< servlet-name> SpringMVC</ servlet-name>
< servlet-class> org.springframework.web.servlet.DispatcherServlet</ servlet-class>
< init-param>
< param-name> contextConfigLocation</ param-name>
< param-value> classpath:springmvc.xml</ param-value>
</ init-param>
< load-on-startup> 1</ load-on-startup>
</ servlet>
< servlet-mapping>
< servlet-name> SpringMVC</ servlet-name>
< url-pattern> /</ url-pattern>
</ servlet-mapping>
< listener>
< listener-class> org.springframework.web.context.ContextLoaderListener</ listener-class>
</ listener>
< context-param>
< param-name> contextConfigLocation</ param-name>
< param-value> classpath:spring.xml</ param-value>
</ context-param>
4.扩展
1.异常处理器
@RestControllerAdvice
public class GlobalException {
@ExceptionHandler ( { ArithmeticException . class } )
public Result handlerException ( ) {
HashMap map = new HashMap ( ) ;
map. put ( "error" , "800" ) ;
return Result . error ( "数学异常" ) ;
}
}
2.拦截器
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle ( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request. getSession ( ) ;
Object user = session. getAttribute ( "user" ) ;
if ( user!= null ) {
return true ;
} else {
response. getWriter ( ) . write ( "请登录" ) ;
return false ;
}
}
}
< mvc: interceptors>
< mvc: interceptor>
< mvc: mapping path = " /public/resource/*" />
< mvc: exclude-mapping path = " /public/resource/login" />
< mvc: exclude-mapping path = " /public/resource/one" />
< mvc: exclude-mapping path = " /public/resource/two" />
< mvc: exclude-mapping path = " /public/resource/three" />
< bean class = " com.atguigu.interceptor.LoginInterceptor" />
</ mvc: interceptor>
</ mvc: interceptors>
3.校验
< dependency>
< groupId> org.hibernate.validator</ groupId>
< artifactId> hibernate-validator</ artifactId>
< version> 8.0.0.Final</ version>
</ dependency>
< dependency>
< groupId> org.hibernate.validator</ groupId>
< artifactId> hibernate-validator-annotation-processor</ artifactId>
< version> 8.0.0.Final</ version>
</ dependency>
@Data
public class User {
@Length ( min = 2 , max = 5 )
private String name;
@Range ( min = 18 , max = 100 )
private Integer age;
@Email
private String email;
}
@PostMapping ( "/user" )
public String getUser ( @Validated @RequestBody User user, BindingResult result) {
System . out. println ( user) ;
if ( result. hasErrors ( ) ) {
System . out. println ( result. getErrorCount ( ) ) ;
System . out. println ( result. getFieldError ( ) . toString ( ) ) ;
}
return "success" ;
}
4.文件上传
< dependency>
< groupId> commons-fileupload</ groupId>
< artifactId> commons-fileupload</ artifactId>
< version> 1.3.1</ version>
</ dependency>
@PostMapping ( "/upload/file" )
public String upload ( @RequestParam ( "photo" ) MultipartFile multipartFile) {
String realPath = servletRequest. getServletContext ( ) . getRealPath ( "/upload" ) ;
File file = new File ( realPath) ;
if ( ! file. exists ( ) ) {
file. mkdirs ( ) ;
}
String originalFilename = multipartFile. getOriginalFilename ( ) ;
String uuid = UUID . randomUUID ( ) . toString ( ) . replace ( "-" , "" ) ;
String savePath = realPath+ "/" + uuid+ originalFilename;
File saveFile = new File ( savePath) ;
try {
multipartFile. transferTo ( saveFile) ;
} catch ( IOException e) {
throw new RuntimeException ( e) ;
}
return "success" ;
}
< bean id = " multipartResolver" class = " org.springframework.web.multipart.commons.CommonsMultipartResolver" >
</ bean>
5.文件下载
@GetMapping ( "/download" )
public ResponseEntity < byte [ ] > download ( ) throws IOException {
String realPath = servletRequest. getServletContext ( ) . getRealPath ( "/upload/" ) ;
File file = new File ( realPath+ "08f0c2f974914b6abea451ceebb1d922微信图片_20211123210023.jpg" ) ;
InputStream is = new FileInputStream ( file) ;
byte [ ] body = new byte [ is. available ( ) ] ; ;
is. read ( body) ;
String encode = URLEncoder . encode ( file. getName ( ) , "UTF-8" ) ;
HttpHeaders headers = new HttpHeaders ( ) ;
headers. add ( "Content-Disposition" , "attchement;filename=" + encode) ;
HttpStatus statusCode = HttpStatus . OK ;
ResponseEntity < byte [ ] > entity = new ResponseEntity < byte [ ] > ( body, headers, statusCode) ;
return entity;
}
6.DispatcherServlet运行流程
1.前端请求先到DispatcherServlet,然后去寻找对应的handler,如果未配置<mvc:default-servlet-handler/>,未找到路径,则404,如果未配置,则404并且控制台报错No mapping found for http request with url
2.前端控制器匹配到合适headler,使用handlerMapping处理器根据xml配置,注解进行查找,找到具体的处理器,然后返回给DispatcherServlet
3.调用preHandle方法,然后通过handlerAdapter处理器将请求携带数据交给Controller,如果存在异常
则会执行handlerExceptionResolver,返回异常信息的ModelAndView如果无异常后端进行业务逻辑处理,最后返回ModelAndView
4.调用拦截器的postHandler方法
5.handlerAdapter将ModelAndView交给DispatcherServlet
6.DispatcherServlet通过具体的视图解析器ViewReslover,进行渲染,调用拦截器的afterCompletion方法
7.返回DispatcherServlet,最后响应用户