Spring MVC -- HelloWorld and RequestMapping request mode

HelloWorld

1. Import jar package
2. Configure web XML file

<!-- to configure DispatcherServlet -->
 <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- to configure DispatcherServlet An initialization parameter, configuration spring
		mvc Location and name of the configuration file -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<!-- Configure which requests can be sent to servlet -->
		<url-pattern>/</url-pattern>
	</servlet-mapping>

3. Add mvc configuration file

<!-- Scan package, that's all@Controller Annotations work-->
<context:component-scan base-package="com.atguigu.springmvc"></context:component-scan>
<!-- How to configure the view parser handler Method returns a physical view that resolves to the actual-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

4. Write a controller for handlers
Use @ RequestMapping to map this request

@Controller
public class HelloWorld {
	/**
	 * 1.Use the @ RequestMapping annotation to parse the requested url
	 * 2.The return value will parse the actual physical view through the view parser. For the internal resource view resolver, the following parsing will be done
	 * Get such a physical view through prefix + return + suffix, and then forward it
	 * @return
	 */
	@RequestMapping("/helloworld")
	public String hello() {
		
		System.out.println("hello world");
		return "success";
		
		
	}

Operation process of helloworld

1. When the client clicks the connection, it will send a hello request
2. The client comes to the tomcat server
3. The front controller of spring MVC receives all requests
4. Let's see which match between the request address and the @ RequestMapping annotation to find out
Which method of which class
5. The front-end controller finds the target processor class and target method, and directly uses the return to execute the target method
6. After the method is executed, there will be a return value. Spring MVC believes that this return value is the page address and.
7. After getting the return value of this method, use the view parser to string to get the complete page address
8. Get the page address and the front controller will help us forward it to the page

2

. @ RequestMapping tells spinmvc what requests this method handles. This / can be omitted and starts under the default current project
Habit plus better / hello /hello
@Use of RequestMapping

3

. if you do not specify the use of the configuration file?
Originally designated
If you do not specify, you will also find a file by default:
/WEB-INF/springDispatcherServlet-servlet.xml
Create a servlet called front-end controller under / WEB-INF of web application xml

4


/Intercept all requests, not jsp pages jsp request
/Intercept all requests, intercept jsp pages, * jsp request
Processing * jsp to tomcat to do
All projects are based on small web XML is inherited from the big web xml
DefaultServlet is a tool for processing static resources in Tomcat
Except jsp And servlet are static resources;
index.html, static resource, tomcat will find this resource under the server and return it
1. Large web of the server One defaultservlet in XML is URL pattern=/
2. We configured the URL pattern of the front-end controller=/
Static resources will come to DispatcherServlet (front-end controller) to see which method has @ RequestMapping
3. Why can jsp access? Because we don't overwrite the configuration of JspServlet in the server
4, / * directly intercepts all requests. We write / to cater to the Rest style URL address

@RequestMapping mapping

1.@RequestMapping mapping request annotation

 spring MVC uses the @ RequestMapping annotation to specify which URL requests can be processed for the controller
 @ RequestMapping can be marked at the class definition and method definition of the controller
• mark on class: provide preliminary request mapping information. Relative to the root directory of the WEB application, that is, the basic path, specify a reference path for the request addresses of all methods of the current class
 mark on method: provide further subdivision mapping information. Relative to the URL marked on the class.
 if @ RequestMapping is not marked on the class, the URL marked at the method is relative to the root directory of the WEB application
Function: after the dispatcher servlet intercepts the request, it determines the processing method corresponding to the request through the mapping information provided by @ RequestMapping on the controller

2.RequestMapping request method


① Standard HTTP request header
② Map request parameters, request methods, or request headers
@In addition to mapping requests using request URL s, RequestMapping can also map requests using request methods, request parameters, and request headers
@value, method, parameters and heads of RequestMapping
It represents the mapping conditions of request URL, request method, request parameter and request header respectively. They are related to each other. The joint use of multiple conditions can make the request mapping more accurate.

③ params and headers support simple expressions:
param1: indicates that the request must contain a request parameter named param1

eg: params={"username"}
The request must be sent with a name username Parameters without direct jump 404

! param1: indicates that the request cannot contain a request parameter named param1

When sending, you must not bring it. If you bring it, you can 404
## eg: 

@RequestMapping("/canhsu")
	public String cansh(@RequestParam(value="username")String username,
	                    @RequestParam(value="age" ,required=false,defaultValue="0" )int age
			) {
		
		System.out.println("username"+age);
		return "success";
	}
<a href="canhsu?username=atguigu&age=10">parameter test</a>

param1 != value1: indicates that the request contains a request parameter named Param1, but its value cannot be value1
{"param1=value1", "param2"}: the request must contain two request parameters named param1 and param2, and the value of param1 parameter must be value1

headers: restrict the current access. Only one restricted browser is allowed to access

3.RequestMapping supports Ant path style

 Ant style resource addresses support three matching characters: [understand]
?: Matches a character in the file name
: matches any character in the file name
: matching multiple paths
 @ RequestMapping also supports Ant style URL s:
/user//createUser
Match URL s such as / user/aaa/createUser, / user/bbb/createUser
/user/**/createUser
Match URL s such as / user/createUser, / user/aaa/bbb/createUser
/user/createUser??
Match URL s such as / user/createUseraa, / user/createUserbb, etc

8. Experimental code

① Define controller method

//Ant style resource addresses support three kinds of matching characters
//@RequestMapping(value="/testAntPath/*/abc")
//@RequestMapping(value="/testAntPath/**/abc")
@RequestMapping(value="/testAntPath/abc??")
public String testAntPath(){
System.out.println("testAntPath...");
return "success";
}

② Page links

<!-- Ant The style resource address supports three kinds of matching characters -->
<a href="springmvc/testAntPath/*/abc">testAntPath</a>
<a href="springmvc/testAntPath/xxx/yyy/abc">testAntPath</a>
<a href="springmvc/testAntPath/abcxx">testAntPath</a>

4.RequestMapping mapping request placeholder PathVariable annotation

@PathVariable is a placeholder for mapping URL bindings
The URL with placeholder is spring 3 0, which is a milestone in the development of spring MVC towards the goal of REST
With @ PathVariable, you can bind the placeholder parameter in the URL to the input parameter of the controller processing method:
The {xxx} placeholder in the URL can be bound to the input parameter of the operation method through @ PathVariable("xxx").

//@The PathVariable annotation can pass the request parameters in the request URL path to the input parameters of the processing request method
@RequestMapping(value="/testPathVariable/{id}")
public String testPathVariable(@PathVariable("id") Integer id){
System.out.println("testPathVariable...id="+id);
return "success";
}

② Request link

<!-- test @PathVariable -->
<a href="springmvc/testPathVariable/1">testPathVariable</a>

What is the. REST style?

REST: representative state transfer. (resource) presentation layer state transformation. It is the most popular Internet software architecture. It has clear structure, conforms to standards, is easy to understand, and is easy to expand, so it is being adopted by more and more websites
/order/1 HTTP GET: query the order with id = 1
/order/1 HTTP DELETE: delete the order with id = 1
/order/1 HTTP PUT: update order with id = 1
/order HTTP POST: new order

Use POJO as parameter

 use POJO object to bind request parameter values
 Spring MVC will automatically match the request parameter name and POJO attribute name, and automatically fill in the attribute value for the object. Cascading properties are supported. For example: dept.deptId, dept.address Tel et al
handler

	@RequestMapping("/pojo")
	public String pojo(com.atguigu.springmvc.Book.Book book) {
		System.out.println("pojo"+book);
			
		return "success";
jsp
<form action="pojo" method="POST">
username:<input type="text" name="name"/></br>
author:<input type="text" name="author"/></br>
money:<input type="text" name="money"/></br>
<input type="submit" value="Submit">
</form>


Use the Servlet native API as a parameter

 what servlet API type parameters can MVC's Handler method accept
1)HttpServletRequest
2)HttpServletResponse
3)HttpSession
4)java.security.Principal
5)Locale
6)InputStream
7)OutputStream
8)Reader
9)Writer

/**
 * You can use the native API of servlet as the parameter of the target method. The following types are supported:
 */
@RequestMapping("/testServletAPI")
public void testServletAPI(HttpServletRequest request,HttpServletResponse response, Writer out) throws IOException {
System.out.println("testServletAPI, " + request + ", " + response);
out.write("hello springmvc");
//return "success";
}
<!-- test Servlet API As a processing request parameter -->
<a href="springmvc/testServletAPI">testServletAPI</a>

Keywords: Web Development Spring Spring MVC

Added by luke_barnes on Wed, 12 Jan 2022 09:52:23 +0200