SpringMVC 入门之@RequestMapping
反思:
-
@RequestMapping注解在什么时候使用?
-
@RequestMapping 常和哪几个注解一起使用?他们分别起什么作用?
-
@ RequestMapping 常用属性值有哪些?
-
param 有几种使用方式?
-
衍生的@RequestMapping有哪些?分别起什么作用?
-
value这个属性占位符会用吗?
-
get 与post 区别是什么?
-
什么情况下是get,什么情况下是post?
-
有些时候获取前端的数据时,中文是乱码?怎么处理?
-
获取前端的传递的参数有哪几种方式?
-
前后端采用json 传递信息,需要填加依赖吗?要的话SpringMvc配套处理json对象的依用什么?返回给前端时需要添加什么注解在对应方法上?如果不在对应方法上添加注解在类上添加什么注解?
-
发现静态资源css,js等没法获取?什么原因?需要添加什么配置可以解决?
@Request Mapping注解
@RequestMapping 是SpringMVC 控制器的一个映射注解,将请求映射到相应的处理方方法上去。
/**
* Assign a name to this mapping.
* <p><b>Supported at the type level as well as at the method level!</b>
* When used on both levels, a combined name is derived by concatenation
* with "#" as separator.
* @see org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder
* @see org.springframework.web.servlet.handler.HandlerMethodMappingNamingStrategy
*/
String name() default "";
/**
* The primary mapping expressed by this annotation.
* <p>This is an alias for {@link #path}. For example,
* {@code @RequestMapping("/foo")} is equivalent to
* {@code @RequestMapping(path="/foo")}.
* <p><b>Supported at the type level as well as at the method level!</b>
* When used at the type level, all method-level mappings inherit
* this primary mapping, narrowing it for a specific handler method.
* <p><strong>NOTE</strong>: A handler method that is not mapped to any path
* explicitly is effectively mapped to an empty path.
*/
@AliasFor("path")
String[] value() default {};
/**
* The path mapping URIs (e.g. {@code "/profile"}).
* <p>Ant-style path patterns are also supported (e.g. {@code "/profile/**"}).
* At the method level, relative paths (e.g. {@code "edit"}) are supported
* within the primary mapping expressed at the type level.
* Path mapping URIs may contain placeholders (e.g. <code>"/${profile_path}"</code>).
* <p><b>Supported at the type level as well as at the method level!</b>
* When used at the type level, all method-level mappings inherit
* this primary mapping, narrowing it for a specific handler method.
* <p><strong>NOTE</strong>: A handler method that is not mapped to any path
* explicitly is effectively mapped to an empty path.
* @since 4.2
*/
@AliasFor("value")
String[] path() default {};
/**
* The HTTP request methods to map to, narrowing the primary mapping:
* GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE.
* <p><b>Supported at the type level as well as at the method level!</b>
* When used at the type level, all method-level mappings inherit this
* HTTP method restriction.
*/
RequestMethod[] method() default {};
/**
* The parameters of the mapped request, narrowing the primary mapping.
* <p>Same format for any environment: a sequence of "myParam=myValue" style
* expressions, with a request only mapped if each such parameter is found
* to have the given value. Expressions can be negated by using the "!=" operator,
* as in "myParam!=myValue". "myParam" style expressions are also supported,
* with such parameters having to be present in the request (allowed to have
* any value). Finally, "!myParam" style expressions indicate that the
* specified parameter is <i>not</i> supposed to be present in the request.
* <p><b>Supported at the type level as well as at the method level!</b>
* When used at the type level, all method-level mappings inherit this
* parameter restriction.
*/
String[] params() default {};
/**
* The headers of the mapped request, narrowing the primary mapping.
* <p>Same format for any environment: a sequence of "My-Header=myValue" style
* expressions, with a request only mapped if each such header is found
* to have the given value. Expressions can be negated by using the "!=" operator,
* as in "My-Header!=myValue". "My-Header" style expressions are also supported,
* with such headers having to be present in the request (allowed to have
* any value). Finally, "!My-Header" style expressions indicate that the
* specified header is <i>not</i> supposed to be present in the request.
* <p>Also supports media type wildcards (*), for headers such as Accept
* and Content-Type. For instance,
* <pre class="code">
* @RequestMapping(value = "/something", headers = "content-type=text/*")
* </pre>
* will match requests with a Content-Type of "text/html", "text/plain", etc.
* <p><b>Supported at the type level as well as at the method level!</b>
* When used at the type level, all method-level mappings inherit this
* header restriction.
* @see org.springframework.http.MediaType
*/
String[] headers() default {};
/**
* Narrows the primary mapping by media types that can be consumed by the
* mapped handler. Consists of one or more media types one of which must
* match to the request {@code Content-Type} header. Examples:
* <pre class="code">
* consumes = "text/plain"
* consumes = {"text/plain", "application/*"}
* consumes = MediaType.TEXT_PLAIN_VALUE
* </pre>
* Expressions can be negated by using the "!" operator, as in
* "!text/plain", which matches all requests with a {@code Content-Type}
* other than "text/plain".
* <p><b>Supported at the type level as well as at the method level!</b>
* If specified at both levels, the method level consumes condition overrides
* the type level condition.
* @see org.springframework.http.MediaType
* @see javax.servlet.http.HttpServletRequest#getContentType()
*/
String[] consumes() default {};
/**
* Narrows the primary mapping by media types that can be produced by the
* mapped handler. Consists of one or more media types one of which must
* be chosen via content negotiation against the "acceptable" media types
* of the request. Typically those are extracted from the {@code "Accept"}
* header but may be derived from query parameters, or other. Examples:
* <pre class="code">
* produces = "text/plain"
* produces = {"text/plain", "application/*"}
* produces = MediaType.TEXT_PLAIN_VALUE
* produces = "text/plain;charset=UTF-8"
* </pre>
* <p>If a declared media type contains a parameter (e.g. "charset=UTF-8",
* "type=feed", "type=entry") and if a compatible media type from the request
* has that parameter too, then the parameter values must match. Otherwise
* if the media type from the request does not contain the parameter, it is
* assumed the client accepts any value.
* <p>Expressions can be negated by using the "!" operator, as in "!text/plain",
* which matches all requests with a {@code Accept} other than "text/plain".
* <p><b>Supported at the type level as well as at the method level!</b>
* If specified at both levels, the method level produces condition overrides
* the type level condition.
* @see org.springframework.http.MediaType
*/
String[] produces() default {};
看以上源码@RequestMapping注解只能在类上和方法上使用,当在类上使用时,会和方法上注解路径进行合并。可以解决多个控制器中有相同命名的action.
常用成员 主要是value (请求路径),param(参数设置)method(设置请求方式)
常和@RequestParam(“设置传参别名”),@ResponseBody(返回值是json) @RequestBody 使用。
Param的用法
params属性用来设置通过请求参数来映射请求。
对于RequestMapping注解来说:
-
value属性是一个数组,只要满足数组中的任意一个路径,就能映射成功
-
method属性也是一个数组,只要满足数组中任意一个请求方式,就能映射成功。
-
params属性也是一个数组,不过要求请求参数必须和params数组中要求的所有参数完全一致后,才能映射成功。
4种常用方法:
-
params={“name”, “age”} 表示:请求参数中必须包含 name和 age,才能与当前标注的方法进行映射。
-
params={“!name”, “age”}表示:请求参数中不能包含name参数,但必须包含age参数,才能与当前标注的方法进行映射。
-
params={“name=admin”, “age”}) 表示:请求参数中必须包含name参数,并且参数的值必须是admin,另外也必须包含age参数,才能与当前标注的方法进行映射。
-
params={“name!=admin”, “password”}) 表示:请求参数中必须包含name参数,但参数的值不能是admin,另外也必须包含age参数,才能与当前标注的方法进行映射。
如果参数不对的话会报400错误
value的使用
value属性是该注解最核心的属性,value属性填写的是请求路径,也就是说通过该请求路与对应的控制器的方法绑定在一起。通过以上源码可知,value属性是一个字符串数组。既然是数组,就表示可以提供多个路径,也就是说,在SpringMVC中,多个不同的请求路径可以映射同一个控制器的同一个方法 value={”路径1“,“路径2”}
value是可以用来匹配路径的,路径支持模糊匹配,我们把这种模糊匹配称之为Ant风格。关于路径中的通配符包括:
-
?,代表任意一个字符
-
*,代表0到N个任意字符,
-
**代表0到N个任意字符,并且路径中可以出现路径分隔符 /
注意: 通配符在使用时,左右不能出现字符,只能是 /**/
衍生注解
- GetMapping:要求前端必须发送get请求
- PutMapping:要求前端必须发送put请求
- DeleteMapping:要求前端必须发送delete请求
- PatchMapping:要求前端必须发送patch请求
- PostMapping:要求前端必须发送posst请求
Get与Post请求的区别
-
get请求发送数据的时候,数据会挂在URI的后面,并且在URI后面添加一个“?”,"?"后面是数据。这样会导致发送的数据回显在浏览器的地址栏上。
-
get请求只能发送普通的字符串。并且发送的字符串长度有限制,不同的浏览器限制不同。这个没有明确的规范。get请求无法发送大数据量。
-
post请求可以发送任何类型的数据,包括普通字符串,流媒体等信息:视频、声音、图片。post请求可以发送大数据量,理论上没有长度限制
-
就安全性而言Post是不安全的,应为post请求可以向服务器写入数据。
-
get支持缓存,post不支持
处理中文乱码问题
解决方法在web.xml添加一个过滤器:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
获取传参的方式
package com.dqw.controller;
import com.dqw.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
@RequestMapping("/user")
@Controller
public class UserController {
@RequestMapping(value = "/getAllUsers",method =RequestMethod.GET)
@ResponseBody
public List<User> findAll(){
ArrayList<User> users = new ArrayList<>();
users.add(new User("李四",25));
users.add(new User("王五",25));
users.add(new User("赵六",25));
users.add(new User("小明",25));
users.add(new User("小霞",25));
return users;
}
@RequestMapping(value = "/getAllUsers",method = RequestMethod.POST)
@ResponseBody //返回值是json对象
public List<User> findAll2(){
ArrayList<User> users = new ArrayList<>();
users.add(new User("李四",25));
users.add(new User("王五",25));
users.add(new User("赵六",25));
users.add(new User("小明",25));
users.add(new User("小霞",25));
return users;
}
@RequestMapping(value = "/geInfo",method = RequestMethod.POST)
public String getInfo(String name,Integer age){
System.out.println(name+"----"+age);
return "success";
}
@RequestMapping(value = "/geInfo",method = RequestMethod.GET)
public String getInfo3(String name,Integer age){
System.out.println(name+"----"+age);
return "success";
}
@RequestMapping("/geInfo2")
public String getInfo2(User user){
System.out.println(user);
return "success";
}
@RequestMapping(value = "/geInfo3")
public String getInfo4(@RequestParam("name") String uname,@RequestParam("age") Integer uage){
System.out.println(uname+"----"+uage);
return "success";
}
@RequestMapping(value = "/geInfo4")
public String getInfo5(HttpServletRequest request){
String uname = request.getParameter("name");
int uage = Integer.parseInt("age");
System.out.println(uname+"----"+uage);
return "success";
}
}
使用Json来传递数据
-
添加依赖
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.14.1</version> </dependency>
-
配置驱动
<?xml version="1.0" encoding="UTF-8"?><context:component-scan base-package="com.dqw.controller"></context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/admin/"></property> <property name="suffix" value=".jsp"></property> <property name="contentType" value="text/jsp;charset=UTF-8"></property> </bean> <!-- 设置注解驱动--> <mvc:annotation-driven></mvc:annotation-driven> <!-- 设置放行静态资源--> <mvc:default-servlet-handler></mvc:default-servlet-handler>
静态资源问题
静态资源被defaultServlet全部拦截了需要设置放行。(查看Tomcat配置文件可以看到)