(1)系统的学习一边 spring mvc,感觉平时的使用都过于流于表面。
(2)为模仿 mvc 做准备
(3)为了超越 mvc 打下基础,比如 blade 这个应用。
也可以参考 spring WebFlux
(1)系统的学习一边 spring mvc,感觉平时的使用都过于流于表面。
(2)为模仿 mvc 做准备
(3)为了超越 mvc 打下基础,比如 blade 这个应用。
也可以参考 spring WebFlux
The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet
that dispatches requests to handlers,
with configurable handler mappings, view resolution, locale, time zone and theme resolution as well as support for uploading files.
The default handler is based on the @Controller
and @RequestMapping
annotations, offering a wide range of flexible handling methods.
Spring Web MVC是基于Servlet API构建的原始Web框架,从一开始就已包含在Spring框架中。
正式名称“ Spring Web MVC”来自其源模块的名称(spring-webmvc),但它通常被称为“ Spring MVC”。
与Spring Web MVC并行,Spring Framework 5.0引入了一个反应式堆栈Web框架,其名称“ Spring WebFlux”也基于其源模块(spring-webflux)。
有关基线信息以及与Servlet容器和Java EE版本范围的兼容性,请参见Spring Framework Wiki。
spring-web模块提供了一些有用的过滤器:
Form Data
Forwarded Headers
Shallow ETag
CORS
浏览器只能通过HTTP GET或HTTP POST提交表单数据,但非浏览器客户端也可以使用HTTP PUT,PATCH和DELETE。
Servlet API需要 ServletRequest.getParameter*()
方法来仅支持HTTP POST的表单字段访问。
spring-web 模块提供 FormContentFilter 来拦截内容类型为 application/x-www-form-urlencoded
的HTTP PUT,PATCH和DELETE请求,从请求主体中读取表单数据,并包装ServletRequest以使表单数据可通过 ServletRequest.getParameter*()方法族获得。
Spring MVC提供了一个基于注释的编程模型,其中 @Controller
和 @RestController
组件使用注释来表达请求映射,请求输入,异常处理等。
带注释的控制器具有灵活的方法签名,无需扩展基类或实现特定的接口。
以下示例显示了由注释定义的控制器:
@Controller
public class HelloController {
@GetMapping("/hello")
public String handle(Model model) {
model.addAttribute("message", "Hello World!");
return "index";
}
}
@RequestMapping 处理程序方法具有灵活的签名,可以从一系列受支持的控制器方法参数和返回值中进行选择。
下表描述了受支持的控制器方法参数。
任何参数均不支持反应性类型。
支持JDK 8的java.util.Optional作为方法参数,并与具有必需属性(例如,@RequestParam,@RequestHeader等)的注释结合在一起,等效于required = false。
Controller method argument Description
WebRequest, NativeWebRequest
Generic access to request parameters and request and session attributes, without direct use of the Servlet API.
javax.servlet.ServletRequest, javax.servlet.ServletResponse
Choose any specific request or response type — for example, ServletRequest, HttpServletRequest, or Spring’s MultipartRequest, MultipartHttpServletRequest.
javax.servlet.http.HttpSession
Enforces the presence of a session. As a consequence, such an argument is never null. Note that session access is not thread-safe. Consider setting the RequestMappingHandlerAdapter instance’s synchronizeOnSession flag to true if multiple requests are allowed to concurrently access a session.
javax.servlet.http.PushBuilder
Servlet 4.0 push builder API for programmatic HTTP/2 resource pushes. Note that, per the Servlet specification, the injected PushBuilder instance can be null if the client does not support that HTTP/2 feature.
java.security.Principal
Currently authenticated user — possibly a specific Principal implementation class if known.
HttpMethod
The HTTP method of the request.
java.util.Locale
The current request locale, determined by the most specific LocaleResolver available (in effect, the configured LocaleResolver or LocaleContextResolver).
java.util.TimeZone + java.time.ZoneId
The time zone associated with the current request, as determined by a LocaleContextResolver.
java.io.InputStream, java.io.Reader
For access to the raw request body as exposed by the Servlet API.
java.io.OutputStream, java.io.Writer
For access to the raw response body as exposed by the Servlet API.
@PathVariable
For access to URI template variables. See URI patterns.
@MatrixVariable
For access to name-value pairs in URI path segments. See Matrix Variables.
@RequestParam
For access to the Servlet request parameters, including multipart files. Parameter values are converted to the declared method argument type. See @RequestParam as well as Multipart.
Note that use of @RequestParam is optional for simple parameter values. See “Any other argument”, at the end of this table.
@RequestHeader
For access to request headers. Header values are converted to the declared method argument type. See @RequestHeader.
@CookieValue
For access to cookies. Cookies values are converted to the declared method argument type. See @CookieValue.
@RequestBody
For access to the HTTP request body. Body content is converted to the declared method argument type by using HttpMessageConverter implementations. See @RequestBody.
HttpEntity
For access to request headers and body. The body is converted with an HttpMessageConverter. See HttpEntity.
@RequestPart
For access to a part in a multipart/form-data request, converting the part’s body with an HttpMessageConverter. See Multipart.
java.util.Map, org.springframework.ui.Model, org.springframework.ui.ModelMap
For access to the model that is used in HTML controllers and exposed to templates as part of view rendering.
RedirectAttributes
Specify attributes to use in case of a redirect (that is, to be appended to the query string) and flash attributes to be stored temporarily until the request after redirect. See Redirect Attributes and Flash Attributes.
@ModelAttribute
For access to an existing attribute in the model (instantiated if not present) with data binding and validation applied. See @ModelAttribute as well as Model and DataBinder.
Note that use of @ModelAttribute is optional (for example, to set its attributes). See “Any other argument” at the end of this table.
Errors, BindingResult
For access to errors from validation and data binding for a command object (that is, a @ModelAttribute argument) or errors from the validation of a @RequestBody or @RequestPart arguments. You must declare an Errors, or BindingResult argument immediately after the validated method argument.
SessionStatus + class-level @SessionAttributes
For marking form processing complete, which triggers cleanup of session attributes declared through a class-level @SessionAttributes annotation. See @SessionAttributes for more details.
UriComponentsBuilder
For preparing a URL relative to the current request’s host, port, scheme, context path, and the literal part of the servlet mapping. See URI Links.
@SessionAttribute
For access to any session attribute, in contrast to model attributes stored in the session as a result of a class-level @SessionAttributes declaration. See @SessionAttribute for more details.
@RequestAttribute
For access to request attributes. See @RequestAttribute for more details.
Any other argument
If a method argument is not matched to any of the earlier values in this table and it is a simple type (as determined by BeanUtils#isSimpleProperty, it is a resolved as a @RequestParam. Otherwise, it is resolved as a @ModelAttribute.
freemaker 作为一款非常优秀的 java 模板框架,和 spring-mvc 整合使用也是非常的方便。
│ pom.xml
│
└─src
├─main
│ ├─java
│ │ └─com
│ │ └─github
│ │ └─houbb
│ │ └─springmvc
│ │ └─freemarker
│ │ └─controller
│ │ IndexController.java
│ │
│ ├─resources
│ │ springmvc-freemarker.xml
│ │
│ └─webapp
│ └─WEB-INF
│ │ web.xml
│ │
│ └─view
│ index.ftl
父模板页面定义好布局,子模板可以重定义布局中的部分内容
使模板可以实现类似"类"的继承关系,并不限继承层次
base_head_content
base_body_content
在交互的过程中,其中一个关键的节点就是获取到客户端发送过来的请求参数,本篇文章,我们来罗列下SpringMVC对于各种数据的获取方式:
说明:以下重点在讲解如何获取参数上,所以返回的数据不是重点
1,普通方式,请求参数名跟Controller的方法参数一致
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/request")
public class RequestController {
@ResponseBody
@RequestMapping(value = "/common", method = RequestMethod.GET)
public String common(String username, String password) {
return username+password;
}
}
SpringMVC 中的Interceptor 拦截请求是通过 HandlerInterceptor 来实现的。
在SpringMVC 中定义一个Interceptor 非常简单,主要有两种方式,
(1)第一种方式是要定义的Interceptor类要实现了Spring 的HandlerInterceptor 接口,或者是这个类继承实现了HandlerInterceptor 接口的类,比如Spring 已经提供的实现了HandlerInterceptor 接口的抽象类HandlerInterceptorAdapter;
(2)第二种方式是实现Spring的WebRequestInterceptor接口,或者是继承实现了WebRequestInterceptor的类。