一、SpringMVC请求
依赖注入:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.smiledog</groupId>
<artifactId>springMVC_day01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<!--依赖管理-->
<dependencies>
<!--springMVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!--jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- 实体类注解依赖 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.8</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 设置编译版本为1.8 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
spring-mvc:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<!--开启注解组件扫描-->
<context:component-scan base-package="com.smiledog"/>
<!--开启mvc注解支持-->
<mvc:annotation-driven/>
<!--自定义视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!--前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加载指定配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:sprin-mvc.xml</param-value>
</init-param>
<!--指定servlet在tomcat启动时创建-->
<load-on-startup>4</load-on-startup>
</servlet>
<!--拦截url规则:/(默认)-->
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
1、简单类型
简单类型包括:基本类型,基本类型的包装类,字符串
@RequestMapping("/param")
@Controller
public class SimpleParamController {
/*
简单类型
*/
@RequestMapping("/simpleParam")
public String simplParam(String username,int age){
System.out.println(username);
System.out.println(age);
return "success" ;
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/param/simpleParam?username=jack&age=15">
简单类型</a>
</body>
</html>
2、对象类型
@Data //lombok依赖1.18.10
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String username;
private Integer age;
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
对象类型
*/
@RequestMapping("/objectParam")
public String simplParam(User user){
System.out.println(user.getUsername());
System.out.println(user.getAge());
return "success" ;
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/param/objectParam">
姓名:
<input type="text" name="username" /> <br>
年龄:
<input type="text" name="age" >
表单中的name属性必须跟User类中的成员变量的名称一致,否则值将为null.
<input type="submit" value="提交">
</form>
</body>
</html>
3、数组类型
<form action="${pageContext.request.contextPath}/param/arrayParam">
<input type="checkbox" name="ids" value="1"> 矢泽优步老湿 <br>
<input type="checkbox" name="ids" value="2"> 樱井莉亚老湿 <br>
<input type="checkbox" name="ids" value="3"> 吉泽明步老湿 <br>
<input type="checkbox" name="ids" value="4"> 泷泽萝拉老湿 <br>
<input type="checkbox" name="ids" value="5"> 波多野结衣老湿 <br>
<input type="submit" value="数组类型">
</form>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@RequestMapping("/arrayParam")
public String simplParam(Integer[] ids){
System.out.println(Arrays.toString(ids));
return "success" ;
}
4、集合类型
集合中存储User对象
package com.smiledog.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Map;
/**
* @author SmILeDog
**/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class UserOv {
private String username;
private Integer age;
private List<User> userList;
private Map<String,User> userMap;
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<form action="${pageContext.request.contextPath}/helloWorld/jihe" method="get">
姓名: <input type="text" name="username">
年龄: <input type="text" name="age"> <br/>
user属性中的姓名:<input type="text" name="user.username"><br/>
user属性中的年龄:<input type="text" name="user.age"> <br/>
list中第一个user对象的年龄:<input type="text" name="userList[0].age"> <br/>
list中第一个user对象的姓名:<input type="text" name="userList[0].username"> <br/>
list中第二个user对象的年龄: <input type="text" name="userList[1].age"> <br/>
list中第二个user对象的姓名: <input type="text" name="userList[1].username"> <br/>
map中第一个键值对中值user对象的年龄: <input type="text" name="userMap['one'].age"> <br/>
map中第一个键值对中值user对象的姓名: <input type="text" name="userMap['one'].username"> <br/>
map中第二个键值对中值user对象的年龄: <input type="text" name="userMap['two'].age"> <br/>
map中第二个键值对中值user对象的姓名: <input type="text" name="userMap['two'].username"><br/>
<input type="submit" value="复杂类型">
</form>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* 集合类型
* 集合存储User对象
*/
@RequestMapping("/jihe")
public String jihe(UserOv userOV) {
System.out.println("获取集合类型参数成功....");
System.out.println(userOV.getUsername());
System.out.println(userOV.getAge());
System.out.println(userOV.getUserList());
System.out.println(userOV.getUserMap());
// 转发到success.jsp页面
return "success";
}
对象中存储数组
二、解决中文乱码问题
如果是get请求,tomcat8以上版本的服务器统一了UTF-8编码,不会出现乱码
如果是post请求,由于servlet规范当中的post默认编码是ISO08859-1,就会乱码
web.xml文件添加以下代码
<!--中文乱码过滤器-->
<filter>
<filter-name>CharacterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
三、自定义类型转换器
用于时间格式的转换:前端输入的日期字符串,到后端要转换成Date类型数据
日期格式转换类:
package com.smiledog.convert;
import org.springframework.core.convert.converter.Converter;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 日期类型转换器
* @author SmILeDog
**/
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String dateStr) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = dateFormat.parse(dateStr);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
}
xml编写:
<!--开启mvc注解支持-->
<mvc:annotation-driven conversion-service="conversionService"/>
<!-- 扩展自定义的类型转换器 -->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.smiledog.convert.DateConverter"></bean>
</set>
</property>
</bean>
测试:
package com.smiledog.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author SmILeDog
**/
@Controller
public class DateTimeFormatTest {
/**
* 日期格式化注解版
* @param birthday 前端传过来的时间字符串
* @return
@RequestMapping("/getTime")
public String getTime(@DateTimeFormat(pattern ="yyyy-MM-dd")Date birthday){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(dateFormat.format(birthday));
return "success";
}*/
@RequestMapping("/getTime")
public String getTime(Date birthday){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(dateFormat.format(birthday));
return "success";
}
}
四、SpringMVC相关注解
@RequestParam
用于将指定的请求参数赋给方法中的形参,可以接收普通参数,也可以接收对象
常用于:数据查询时的分页操作
相关属性:value:请求参数名(必须)
required:表示是否必须,默认为true,请求该方法是必须携带参数和值
defaultValue:可设置请求参数的默认值
@RequestParam(value="参数名",required="true/false",defaultValue=" ")
<a href="/requestParam?pageNum=1&size=5">请求参数(分页)</a><br>
@RequestMapping("requestParam")
public String requestParam(
@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
@RequestParam(value = "size",defaultValue = "10")Integer size){
System.out.println("页码:"+pageNum);
System.out.println("每页展示的数据:"+size);
return "success";
}
@RequestHeader
获取指定的请求头,相当于Servlet中的getHeader()方法
<a href="${pageContext.request.contextPath}/requestHeader">请求头</a>
@RequestMapping("/requestHeader")
public String requestHeader(
@RequestHeader("User-Agent") String userAgent ,
@RequestHeader("cookie") String cookie){
System.out.println(userAgent);
System.out.println(cookie);
return "success" ;
}
@CookieValue
获取指定Cookie的值
<a href="${pageContext.request.contextPath}/cookieValue">获取指定的Cookie</a>
@RequestMapping("/cookieValue")
public String cookieValue(
@CookieValue("JSESSIONID") String cookie){
System.out.println(cookie);
return "success" ;
}