Jun 01, 2021 Article blog
2. Second, SpringMVC simple to use
3. Third, use @RequestMapping map request
6. Six, @RequestParam binding request parameter values
7. 7. @RequestHeader the property value of the binding request header
8. Eight, @CookieValue the cookie value in the binding request
9. Nine, POJO object binding request parameter values
10.. Ten, the parameters of the Servlet API type that theHandler method can receive in MVC
MVC
frameworks available today
超越 Struts2
to become the best MVC framework
POJO
the controller that processes requests without implementing any interfaces.
REST
URL requests are supported
松散耦合可插拔
component structure is more scalable and flexible than other MVC frameworks
<!-- 配置 DispatcherServlet -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置 DispatcherServlet 的一个初始化参数: 配置 SpringMVC 配置文件的位置和名称 -->
<!--
实际上也可以不通过 contextConfigLocation 来配置 SpringMVC 的配置文件, 而使用默认的.
默认的配置文件为: /WEB-INF/<servlet-name>-servlet.xml
-->
<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>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="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-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 配置自定扫描的包 -->
<context:component-scan base-package="cbuc.life.springmvc"></context:component-scan>
<!-- 配置视图解析器: 如何把 handler 方法返回值解析为实际的物理视图 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
@Controller
public class HelloWorldController {
/**
1. 使用 @RequestMapping 注解来映射请求的 URL
2. 返回值会通过视图解析器解析为实际的物理视图, 对于 InternalResourceViewResolver 视图解析器, 会做如下的解析:
通过 prefix + returnVal + 后缀 这样的方式得到实际的物理视图, 然会做转发操作
==> /WEB-INF/views/success.jsp
*/
@RequestMapping("/helloworld")
public String hello(){
System.out.println("hello world");
return "success";
}
}
Create a suces .jsp under/WEB-INF/views/directory
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>成功跳转页面</h1>
</body>
</html>
(Recommended course: Spring tutorial)
@RequestMapping
annotations to specify to the controller which URL requests can be processed
类
definition and the
方法
definition can be labeled
WEB 应用的根目录
DispatcherServlet
intercepts the request, the mapping information provided by
@RequestMapping
on the controller determines how the request is handled.
value, method, params, and heads of the @RequestMapping represent the mapping criteria for the request URL, the request method, the request parameters, and the request header, respectively, and they are the relationship with , using multiple conditions to make the request map more precise.
/**
* 可以使用 params 和 headers 来更加精确的映射请求. params 和 headers 支持简单的表达式.
*
* @return
*/
@RequestMapping(value = "testParamsAndHeaders",
params = { "username","age!=10" },
headers = { "Accept-Language=en-US,zh;q=0.8" },
method = RequestMethod.POST)
public String test() {
System.out.println("test...");
return "success";
}
?
: Matches a character in the file name
/user/createUser?
Matches URLs such as /user/createUser a or user/createUser b
*
: Matches any character in the file name
/user/*/createUser
Matches URLs such as /user/aaa/createUser or /user/bbb/createUser
**
: Matches multi-tier paths
/user/\ /createUser**
Matches URLs such as /user/createUser or /user/aaa/bbb/createUser
A placeholder that maps URL bindings
@PathVariable
you can bind placeholder parameters in a URL to the parameters of the controller's processing method:
{xxx}
in the URL can be bound to the parameters of the action method by
@PathVariable("xxx")
/**
* @PathVariable 可以来映射 URL 中的占位符到目标方法的参数中.
*/
@RequestMapping("/testPathVariable/{id}")
public String test(@PathVariable("id") Integer id) {
System.out.println("id: " + id);
return "success";
}
复制代码
“
REST
The Representation State Transfer. ( Resource) performance layer state transformation. I t is one of the most popular Internet software architectures. It is well structured, standard-compliant, easy to understand, easy to expand, so it is getting more and more website adoption
Example:
GET
Gets the
order record for id s 1
DELETE
Delete
the order record for id s 1
PUT
Update
the order record for id s 1
POST
A new order record has been
added
value
The parameter name
required
Whether it is necessary;
/**
* @RequestParam 来映射请求参数. value 值即请求参数的参数名 required 该参数是否必须. 默认为 true
* defaultValue 请求参数的默认值
*/
@RequestMapping(value = "/testRequestParam")
public String testRequestParam(
@RequestParam(value = "username") String username,
@RequestParam(value = "age", required = false, defaultValue = "0") int age) {
System.out.println("testRequestParam, username: " + username + ", age: " + age);
return "success";
}
/**
* 映射请求头信息 用法同 @RequestParam
*/
@RequestMapping("/testRequestHeader")
public String testRequestHeader(
@RequestHeader(value = "Accept-Language") String al) {
System.out.println("testRequestHeader, Accept-Language: " + al);
return "success";
}
/**
* @CookieValue: 映射一个 Cookie 值. 属性同 @RequestParam
*/
@RequestMapping("/testCookieValue")
public String testCookieValue(@CookieValue("JSESSIONID") String sessionId) {
System.out.println("testCookieValue: sessionId: " + sessionId);
return "success";
}
/**
* Spring MVC 会按请求参数名和 POJO 属性名进行自动匹配, 自动为该对象填充属性值。支持级联属性。
* 如:dept.deptId、dept.address.tel 等
*/
@RequestMapping("/testPojo")
public String testPojo(User user) {
System.out.println("testPojo: " + user);
return "success";
}
(Recommended micro-class: Spring micro-class.) )
1)
ModelAndView
When the processing method returns a value type of ModelAndView, the method body can add model data through the object, which contains both view information and model data information.
2)
Map 及 Model
When you enter org.springframework.ui.Model, org.springframework.ui.ModelMap, or java.uti.Map, the data in the map is automatically added to the model when the processing method returns.
3)
@SessionAttributes:
Staging a property in the model to HttpSession so that it can be shared between multiple requests (from the session domain)
@SessionAttributes
on the Controller
class,
and Spring MVC staging the corresponding properties in the model to
HttpSession
@SessionAttributes
In addition to specifying the properties that need to be placed in a session through the property name, you can specify which model properties need to be placed in the session through the object type of the model property
1) @SessionAttributes (types-user.class): All properties in the implied model that are user-.class are added to the session
2) @SessionAttributes (value s"user1", "user2"): the property of the object in the implied model named user1, user2, is added to the session
3) @SessionAttributes (types," user.class, Dept.class): All properties in the implied model that are User .class, Dept .class, are added to the session
4) @SessionAttributes (value," "user1," "user2", types, "Dept.class"): the properties of the implied model named user1, user2, and all properties of type Dept .class are added to the session
4)
@ModelAttribute
When the method is labeled with the annotation, the object in the parameter is placed in the data model
@ModelAttribute
note on method definitions: Spring MVC calls methods labeled
@ModelAttribute
at the method level one by one before calling the target processing method.
@ModelAttribute
annotations before entering the method:
ModelAndView
object is eventually returned.
For processing methods that return types such as
String,
View,
or
ModeMap,
Spring MVC also internally assembles them into a ModelAndView object that contains views of
logical names
and
model objects.
ViewResolver
View
can be a
JSP
or a view in various forms of expression, such as
Excel
JFreeChart
and so on.
We only need to implement the View interface to customize the view
@Component
public class HelloView implements View{
@Override
public String getContentType() {
return "text/html";
}
@Override
public void render(Map<String, ?> model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.getWriter().print("hello view, time: " + new Date());
}
}
@RequestMapping("/testView")
public String testView(){
System.out.println("testView");
return "helloView"; //这里返回的就是我们自定义的视图
}
ServletException
exception is thrown
Configurations in the SpringMVC .xml:
<!-- 配置视图解析器: 如何把 handler 方法返回值解析为实际的物理视图 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置视图 BeanNameViewResolver 解析器: 使用视图的名字来解析视图 -->
<!-- 通过 order 属性来定义视图解析器的优先级, order 值越小优先级越高 -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<property name="order" value="100"></property>
</bean>
Source: Public No. -- A Good Book of Small Dishes Author: Cai Wei
Above is
W3Cschool编程狮
about (hard core!)
This article gives you an in-depth understanding of SpringMVC) related to the introduction, I hope to help you.