1.spring通过Model带值到页面
1.1先上maven依赖包,引入springMVC、jsp、jstl、servlet3.0的依赖
<!-- springmvc依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<!-- servlet3.0的依赖包-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
<!--防止冲突 于tomcat中的servlet冲突 -->
<scope>provided</scope>
</dependency>
<!--el表达式的依赖包 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
1.2 在web.xml中配置DispatcherServlet
<!-- springMvc的核心前端控制器DispatcherServlet -->
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- 必须指定springmvc的初始化路径 参数为contextConfigLocation -->
<!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如springMvc-servlet.xml-->
<param-name>contextConfigLocation</param-name>
<!-- 此处为空会报错 Could not open ServletContext resource [/WEB-INF/springMvc-servlet.xml] -->
<!-- 如果配置了spring的ContextLoaderListener监听器会默认去找/WEB-INF/applicationContext.xml-->
<!-- spring是父容器,springmvc是子容器 -->
<!-- 此处作为spring的简单实现 ,必须在配置文件中指定扫描包让spring可以找到容器 -->
<param-value>classpath:springMvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 拦截路径 -->
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
1.3 在web.xml引入的springMvc-servlet.xml中配置视图解析器
<!--扫描注解->
<context:annotation-config />
<!-- 设置使用注解的类所在的jar包 ,包括递归子包中的类都会被扫描-->
<context:component-scan base-package="cn.hxl"></context:component-scan>
<!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
<!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
1.4 上代码在model中放值,jsp页面取值
@Controller
public class SpringMvc {
//spring返回jsp 在model中放入对象
@RequestMapping("/writeHello")
public String writeHello(Model model){
model.addAttribute("hello", "hello");
return "hello";
}
}
必须在jsp页面引入<%@ taglib uri=“http://java.sun.com/jsp/jstl/core” prefix=“c” %>才可以用el表达式
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>writeHello</title>
</head>
<body>
${hello }
</body>
</html>
访问页面
2. @PathVariable应用
//从请求路径中获取值 一般和freemarker配置使用 或基于resful风格的请求
@RequestMapping("/{name}")
@ResponseBody
//返回字符串
public String writeHello(@PathVariable String name){
return name;
}
页面访问
3.矩阵变量 @MatrixVariable
3.1 矩阵变量可以在任何路径段落中出现,每对矩阵变量之间使用一个分号“;”隔开。比如这样的
URI: “/cars;color=red;year=2012” 。多个值可以用逗号隔开 “color=red,green,blue” ,或者
重复变量名多次 “color=red;color=green;color=blue” 。
//@MatrixVariable必须和@PathVariable配合使用
//请求格式 http://localhost:8080/SpringMvc2/matri/car;color=red;
//produces处理返回值的中文乱码
@RequestMapping(value="/matri/{car}",produces = "application/json; charset=utf-8")
@ResponseBody
public String getCar(@PathVariable String car,@MatrixVariable String color){
System.out.println(color);
return color+"色跑车";
}
页面返回
必须在xml中添加如下配置
<mvc:annotation-driven enable-matrix-variables="true"/>
3.2 直接上代码
@RequestMapping(value="/matri1/{name}/color/{color}",produces = "application/json; charset=utf-8")
@ResponseBody
//基于多个路径取值
//{name} 取值 name {color} 取值 color
//pathVar对应路径,value对应参数 defaultValue默认参数的值
//格式 @MatrixVariable(value="name",pathVar="name",defaultValue="test") String name
//请求路径 http://localhost:8080/SpringMvc2/matri1/car;name=qq/color/color;color=red
//matri1/car;name=qq 对应 {name} 取值 name
///color/color;color=red {color} 取值 color
public String getCar2(
@MatrixVariable(value="name",pathVar="name",defaultValue="test") String name,
@MatrixVariable(value="color",pathVar="color",defaultValue="test") String color){
System.out.println(name);
return color+"色"+name+"跑车";
}
页面返回
3.3 直接上代码
@RequestMapping(value="/matri2/{car}/color/{color}",produces = "application/json; charset=utf-8")
@ResponseBody
//基于多个路径对应多个值
//@MatrixVariable Map<String, String> matrixVars 多路径多参数
//@MatrixVariable(pathVar="color") Map<String, String> petMatrixVars
//取出color路径上绑定的值
//请求路径 http://localhost:8080/SpringMvc2/matri2/car;name=qq;color=bule/color/color;color=red;name=ad
//matri2/car;name=qq;color=bule 第一个路径对应两值
//color/color;color=red;name=ad 第二个路径 对应两值
//@MatrixVariable(pathVar="color") Map<String, String> colorMatrixVars 取color路径上的值
//{name=qq, color=bule}==={color=red, name=ad}
public String getCar3(
@MatrixVariable Map<String, String> matrixVars,
@MatrixVariable(pathVar="color") Map<String, String> colorMatrixVars){
return matrixVars+"==="+colorMatrixVars;
}
页面返回
4.@RequestMapping中的属性值
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
String name() default "";//设置请求的名称
String[] value() default {};//设置请求路径
String[] path() default {};//同上,
RequestMethod[] method() default {};//设置请求的方法类型 :get 、post
String[] params() default {}; //设置请求参数信息
String[] headers() default {};//设置请求头信息
String[] consumes() default {};// 设置请求内容信息
String[] produces() default {};//设置响应内容信息
}
//指定请求中提交内容类型(Content-Type),例如application/json, text/html;
//MediaType 可以指定Content-Type的各种类型,可以通过类型过滤请求
@RequestMapping(value="/consumes/test",consumes="application/json; charset=utf-8")
@ResponseBody
//返回字符串
public String consumes(String name){
return name;
}
//指定响应中提交内容类型(Content-Type),例如application/json, text/html;
@RequestMapping(value="/produces/test",produces="application/json; charset=utf-8")
@ResponseBody
//返回字符串
public String produces(String name){
return name;
}
// 表示只接收本机发来的请求 headers设置过滤请求 可以通过request中Headers的属性设置过滤
@RequestMapping(path="/login/user", headers="Host=localhost:8080")
public String login() {
return "success";
}
// 该方法将接收 /user/index 发来的请求,且请求参数必须为 username=zhangsan&password=123456
@RequestMapping(value = "/user/index", params={"username=zhangsan","password=123456"})
@ResponseBody
public String index() {
return "success";
}
/**
使用name属性须知
* 1.spring必须是4.1版本以上
2.支持EL 3.0的容器中(比如tomcat容器必须选择tomcat7以上版本)
3.JSP页面注意不能是index.jsp
4.必须在视图解析器的映射范围中
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
jsp必须在/WEB-INF/jsp/目录下
5.每个RequestMapping 都会默认分配一个名称name,规则是类名中大写字母和方法名中间加上#,
当然如果这样觉得太复杂了,你可以直接指定RequestMapping 的name,然后直接使用它。
注意:如果你指定了当前RequestMapping 的name属性的值,则不可以使用先前默认规则来获取url,否则将会报错
例如:我们例子中的controller类名为SpringMvc 控制器中有个方法叫做getUser 那么他的默认分配name为SM#getUser
6.前台页面必须引入<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
请求获取 <a href="${s:mvcUrl('SM#getUser').arg(0,"123").build()}">获取用户</a>
SM#getUser是请求名称 arg指定参数
我们设置name为text,name前台请求为
<a href="${s:mvcUrl('test').arg(0,"123").build()}">获取用户</a>
* @param id
* @return
*/
@RequestMapping(value="/user/getUser/{id}",produces="application/json; charset=utf-8",name="test")
@ResponseBody
public String getUser(@PathVariable int id) {
return "id为"+id+"的用户";
}
5.springMVC注解整理
@ModelAttribute注解类型将参数绑定到Model对象
@RequestMapping(value="/modelAttributeTest", method = RequestMethod.POST)
public String modelAttributeTest(@ModelAttribute User user){
System.out.println("modelAttribute Test");
System.out.println("userid: " + user.getUserId());
System.out.println("username: " + user.getUserName());
System.out.println("userpwd: " + user.getUserPwd());
return "hello";
}
@RequestParam GET和POST请求传的参数会自动转换赋值到 @RequestParam 所注解的变量上
用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。提交方式为get或post。(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)
RequestParam实质是将Request.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段。
get方式中query String的值,和post方式中body data的值都会被Servlet接受到并转化到Request.getParameter()参数集中,所以@RequestParam可以获取的到。
@RequestMapping(value="/requestParamTest", method = RequestMethod.GET)
public String requestParamTest(@RequestParam(value="username") String userName, @RequestParam(value="usernick") String userNick){
System.out.println("requestParam Test");
System.out.println("username: " + userName);
System.out.println("usernick: " + userNick);
return "hello";
}
@RequestBody 注解可以接收json格式的数据,并将其转换成对应的数据类型 ,只应用于post请求 处理HttpEntity传递过来的数据,一般用来处理非Content-Type: application/x-www-form-urlencoded编码格式的数据。 GET请求中,因为没有HttpEntity,所以@RequestBody并不适用。 POST请求中,通过HttpEntity传递的参数,必须要在请求头中声明数据的类型Content-Type,SpringMVC通过使用HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据,然后绑定到相应的bean上。 @RequestBody用于post请求,不能用于get请求 这里涉及到使用@RequestBody接收不同的对象 1. 创建一个新的entity,将两个entity都进去。这是最简单的,但是不够“优雅”。 2. 用Map<String, Object>接受request body,自己反序列化到各个entity中。 3. 类似方法2,不过更为generic,实现自己的HandlerMethodArgumentResolver
@RequestMapping(value="/findBookByName", method = RequestMethod.POST)
@ResponseBody
public DbBook findBookByName(@RequestBody DbBook book){
System.out.println("book: " + book.toString());
System.out.println("book name: " + book.getTitle());
String bookName = book.getTitle();
DbBook book = wxService.findBookByName(bookName);
return book;
}
@RequestHeader 注解,可以把Request请求header部分的值绑定到方法的参数上。
以下是一个request的header头信息
Host localhost:8080
Accept text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language fr,en-gb;q=0.7,en;q=0.3
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 300
通过以下代码设置头信息
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive) {
//...
}
**把request header部分的 Accept-Encoding的值,绑定到参数encoding上了, Keep-Alive header的值绑定到参数keepAlive上**
@CookieValue 可以把Request header中关于cookie的值绑定到方法的参数上。
例如有如下Cookie值:
JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie) {
//...
}
即把JSESSIONID的值绑定到参数cookie上。
@SessionAttributes:
**该注解用来绑定HttpSession中的attribute对象的值,便于在方法中的参数里使用。
该注解有value、types两个属性,可以通过名字和类型指定要使用的attribute 对象;
@Controller
@RequestMapping("/editPet.do")
@SessionAttributes("pet")
public class EditPetForm {
// ...
}
@RequestPart这个注解用在multipart/form-data表单提交请求的方法上。
2.支持的请求方法的方式MultipartFile,属于Spring的MultipartResolver类。这个请求是通过http协议传输的
@RequestMapping("uploadFile")
public JsonResult uploadFile(@RequestPart("file") MultipartFile file, @RequestParam String bucket){
String fileUrl = aliossService.uploadFile(file, bucket);
Map<String,String> result = new HashMap<>();
result.put("fileUrl",fileUrl);
return success(result);
}