java springmvc注解详解_spring mvc 常用注解详解

a1c980ec5b005e94da9c09b6a41995d2.png

前言

现在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了。不过要想灵活运用Spring MVC来应对大多数的Web开发,就必须要掌握它的配置及原理。

Spring mvc 介绍

Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发,Spring Web MVC也是要简化我们日常Web开发

3aed4aed13e9aebba0384987e3e2630a.png

image.png

spring mvc 常用注解详解

@Controller

在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ,然后再把该Model 返回给对应的View 进行展示。在SpringMVC 中提供了一个非常简便的定义Controller 的方法,你无需继承特定的类或实现特定的接口,只需使用@Controller 标记一个类是Controller ,然后使用@RequestMapping 等一些注解用以定义请求URL 请求和Controller 方法之间的映射,这样的Controller 就能被外界访问到。其标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象。分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用@RequestMapping 注解。@Controller 只是定义了一个控制器类,而使用@RequestMapping 注解的方法才是真正处理请求的处理器。此外我们还需要将controller注册到spring里

@RequestMapping

RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径,作用于方法上,表明该处理器的请求地址=父路径+方法上url+method,其拥有6个属性

1、 value, method;定义处理器访问的具体体质

value: 指定请求的实际地址,指定的地址可以是URI Template 模式;

method: 指定请求的method类型, GET、POST、PUT、DELETE等;

2、consumes,produces 定义处理器内容类型

consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

3、params,headers 定义处理器处理类型

params: 指定request中必须包含某些参数值,才让该方法处理!

headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

@PathVariable

用于将请求URL中的模板变量映射到功能处理方法的参数上,即取出uri模板中的变量作为参数。如:

@Controller

public class TestController {

@RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET)

public String getLogin(@PathVariable("userId") String userId,

@PathVariable("roleId") String roleId){

System.out.println("取出请求路径携带的参数->User Id : " + userId);

System.out.println("取出请求路径携带的参数->Role Id : " + roleId);

return "hello";

}

}

@requestParam

@requestParam主要用于在SpringMVC后台控制层获取参数,类似一种是request.getParameter("name"),它有三个常用参数:defaultValue = "0", required = false, value = "isApp";defaultValue 表示设置默认值,required 铜过boolean设置是否是必须要传入的参数,value 值表示接受的传入的参数类型。

@ResponseBody

作用: 该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。使用时机:返回的数据不是html标签的页面,而是其他某种格式的数据时(如json等)使用;

@RequestBody

该注解常用来处理Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;它是通过使用HandlerAdapter 配置的HttpMessageConverters来解析post data body,然后绑定到相应的bean上的。

@RequestMapping(value = "/something", method = RequestMethod.PUT)

public void handle(@RequestBody String body, Writer writer) throws IOException {

writer.write(body);

}

spring mvc 拦截器配置

preHandle:预处理回调方法,返回值:true表示继续流程,false表示流程中断(如登录检查失败),不会继续续调用其他的拦截器或处理器,此时我们需要通过response来产生响应;

postHandle:后处理回调方法,实现处理器的后处理(但在渲染视图之前),此时我们可以通过modelAndView(模型和视图对象)对模型数据进行处理或对视图进行处理,modelAndView也可能为null。

afterCompletion:整个请求处理完毕回调方法,即在视图渲染完毕时回调,如性能监控中我们可以在此记录结束时间并输出消耗时间,还可以进行一些资源清理,类似于try-catch-finally中的finally,但仅调用处理器执行链中preHandle返回true的拦截器的afterCompletion。

public class Login implements HandlerInterceptor {

@Override

public void afterCompletion(HttpServletRequest httpRequest,

HttpServletResponse httpResponse, Object arg2, Exception arg3)

throws Exception {

}

@Override

public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,

Object arg2, ModelAndView arg3) throws Exception {

}

@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response,

Object object) throws Exception {

/*HttpServletRequest httpRequest = (HttpServletRequest) request;

HttpServletResponse httpResponse = (HttpServletResponse) response;*/

String urlString = request.getRequestURI();

///olForum/forumList.html模拟登录页

if(urlString.endsWith("forumList.html")){

return true;

}

//请求的路径

String contextPath=request.getContextPath();

/*httpRequest.getRequestDispatcher("/olForum/forumList").forward(httpRequest, httpResponse);*/

/*response.sendRedirect(contextPath+"/olForum/forumList.html");*/

response.sendRedirect(contextPath + "/olForum/forumList.html?login=aaa");

return false;

/*httpResponse.sendRedirect(httpRequest.getContextPath()+"/olForum/forumList.html");

return;*/

}

}

xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc"

xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:p="http://www.springframework.org/schema/p"

xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd

http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

p:prefix="/WEB-INF/views/" p:suffix=".jsp"/>

spring mvc 静态资源放问配置

1689504dab8651f57b3cf0349d92c7eb.png

image.png

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

spring mvc 文件上传

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

前端

选择文件:

后端

@RequestMapping(value = "taskUpload", produces = "text/html;charset=UTF-8", method = RequestMethod.POST)

public ResponseEntity taskUpload(@Validated Task task, HttpServletRequest request) throws Exception {

if (StringUtils.isNotBlank(task.getAnnouncement())) {

String type = task.getType();

return Optional.ofNullable(taskService.saveSelective(task))

.filter((value) -> value > 0)

.map(result -> new ResponseEntity<>(type + "公告发布成功", HttpStatus.OK))

.orElse(ResponseEntity.status(HttpStatus.NOT_FOUND).body("公告发布失败"));

}

File newFile = null;

try {

CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(

request.getSession().getServletContext());

if (request instanceof MultipartHttpServletRequest) {

// 将request变成多部分request

MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

Iterator iter = multiRequest.getFileNames();

// 检查form中是否有enctype="multipart/form-data"

if (multipartResolver.isMultipart(request) && iter.hasNext()) {

// 获取multiRequest 中所有的文件名

while (iter.hasNext()) {

List fileRows = multiRequest.getFiles(iter.next().toString());

if (fileRows != null && fileRows.size() != 0) {

for (MultipartFile file : fileRows) {

if (file != null && !file.isEmpty()) {

// 文件新路径

String filePath = getFilePath(request, file.getOriginalFilename());

newFile = new File(filePath);

// 写文件到磁盘

file.transferTo(newFile);

String type = task.getType();

if (newFile.exists()) {

CraFile craFile = new CraFile();

craFile.setFilePath(filePath);

craFile.setFileType(task.getType());

Integer integer = fileService.saveSelective(craFile);

if (integer > 0) {

task.setFileId(craFile.getId());

return Optional.ofNullable(taskService.saveSelective(task))

.filter((value) -> value > 0)

.map(result -> new ResponseEntity<>(type + "上传成功", HttpStatus.OK))

.orElse(ResponseEntity.status(HttpStatus.NOT_FOUND).body("上传失败"));

}

} else {

return ResponseEntity.status(HttpStatus.NOT_FOUND).body("上传失败");

}

}else {

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("未能检测到上传文件");

}

}

}

}

}

}

} catch (Exception ex) {

ex.printStackTrace();

if (newFile != null) {

if (newFile.exists()) {

newFile.delete();

}

}

return ResponseEntity.status(HttpStatus.NOT_FOUND).body("上传失败");

}

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器繁忙");

}

spring mvc 工作流程详解

56ccaf823e4ce558eeb8c9e5eef8b691.png

image.png

1、 用户发送请求至前端控制器DispatcherServlet。

2、 DispatcherServlet收到请求调用HandlerMapping处理器映射器。

3、 处理器映射器找到具体的处理器(可以根据xml配置、注解进行查找),生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。

4、 DispatcherServlet调用HandlerAdapter处理器适配器。

5、 HandlerAdapter经过适配调用具体的处理器(Controller,也叫后端控制器)。

6、 Controller执行完成返回ModelAndView。

7、 HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet。

8、 DispatcherServlet将ModelAndView传给ViewReslover视图解析器。

9、 ViewReslover解析后返回具体View。

10、DispatcherServlet根据View进行渲染视图(即将模型数据填充至视图中)。

11、 DispatcherServlet响应用户。

关注作者,我会不定期在思否分享Java,Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化、分布式架构,BATJ面试 等资料...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值