一、SpringMVC请求

依赖注入:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.smiledog</groupId>
  5. <artifactId>springMVC_day01</artifactId>
  6. <version>1.0-SNAPSHOT</version>
  7. <packaging>war</packaging>
  8. <!--依赖管理-->
  9. <dependencies>
  10. <!--springMVC-->
  11. <dependency>
  12. <groupId>org.springframework</groupId>
  13. <artifactId>spring-webmvc</artifactId>
  14. <version>5.1.5.RELEASE</version>
  15. </dependency>
  16. <!--servlet-->
  17. <dependency>
  18. <groupId>javax.servlet</groupId>
  19. <artifactId>servlet-api</artifactId>
  20. <version>2.5</version>
  21. <scope>provided</scope>
  22. </dependency>
  23. <!--jsp-->
  24. <dependency>
  25. <groupId>javax.servlet</groupId>
  26. <artifactId>jsp-api</artifactId>
  27. <version>2.0</version>
  28. <scope>provided</scope>
  29. </dependency>
  30. <!-- 实体类注解依赖 -->
  31. <dependency>
  32. <groupId>org.projectlombok</groupId>
  33. <artifactId>lombok</artifactId>
  34. <version>1.16.8</version>
  35. <scope>provided</scope>
  36. </dependency>
  37. </dependencies>
  38. <build>
  39. <plugins>
  40. <!-- 设置编译版本为1.8 -->
  41. <plugin>
  42. <groupId>org.apache.maven.plugins</groupId>
  43. <artifactId>maven-compiler-plugin</artifactId>
  44. <version>3.1</version>
  45. <configuration>
  46. <source>1.8</source>
  47. <target>1.8</target>
  48. <encoding>UTF-8</encoding>
  49. </configuration>
  50. </plugin>
  51. </plugins>
  52. </build>
  53. </project>

spring-mvc:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:mvc="http://www.springframework.org/schema/mvc"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="
  7. http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/mvc
  10. http://www.springframework.org/schema/mvc/spring-mvc.xsd
  11. http://www.springframework.org/schema/context
  12. http://www.springframework.org/schema/context/spring-context.xsd
  13. ">
  14. <!--开启注解组件扫描-->
  15. <context:component-scan base-package="com.smiledog"/>
  16. <!--开启mvc注解支持-->
  17. <mvc:annotation-driven/>
  18. <!--自定义视图解析器-->
  19. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  20. <property name="prefix" value="/jsp/"></property>
  21. <property name="suffix" value=".jsp"></property>
  22. </bean>
  23. </beans>

web.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  5. version="2.5">
  6. <!--前端控制器-->
  7. <servlet>
  8. <servlet-name>DispatcherServlet</servlet-name>
  9. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  10. <!--加载指定配置文件-->
  11. <init-param>
  12. <param-name>contextConfigLocation</param-name>
  13. <param-value>classpath:sprin-mvc.xml</param-value>
  14. </init-param>
  15. <!--指定servlettomcat启动时创建-->
  16. <load-on-startup>4</load-on-startup>
  17. </servlet>
  18. <!--拦截url规则:/(默认)-->
  19. <servlet-mapping>
  20. <servlet-name>DispatcherServlet</servlet-name>
  21. <url-pattern>/</url-pattern>
  22. </servlet-mapping>
  23. </web-app>

1、简单类型

简单类型包括:基本类型,基本类型的包装类,字符串

  1. @RequestMapping("/param")
  2. @Controller
  3. public class SimpleParamController {
  4. /*
  5. 简单类型
  6. */
  7. @RequestMapping("/simpleParam")
  8. public String simplParam(String username,int age){
  9. System.out.println(username);
  10. System.out.println(age);
  11. return "success" ;
  12. }
  13. }
  14. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  15. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  16. <html>
  17. <head>
  18. <title>Title</title>
  19. </head>
  20. <body>
  21. <a href="${pageContext.request.contextPath}/param/simpleParam?username=jack&age=15">
  22. 简单类型</a>
  23. </body>
  24. </html>

2、对象类型

  1. @Data //lombok依赖1.18.10
  2. @NoArgsConstructor
  3. @AllArgsConstructor
  4. public class User {
  5. private String username;
  6. private Integer age;
  7. }
  8. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  9. /*
  10. 对象类型
  11. */
  12. @RequestMapping("/objectParam")
  13. public String simplParam(User user){
  14. System.out.println(user.getUsername());
  15. System.out.println(user.getAge());
  16. return "success" ;
  17. }
  18. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  19. <html>
  20. <head>
  21. <title>Title</title>
  22. </head>
  23. <body>
  24. <form action="${pageContext.request.contextPath}/param/objectParam">
  25. 姓名:
  26. <input type="text" name="username" /> <br>
  27. 年龄:
  28. <input type="text" name="age" >
  29. 表单中的name属性必须跟User类中的成员变量的名称一致,否则值将为null.
  30. <input type="submit" value="提交">
  31. </form>
  32. </body>
  33. </html>

3、数组类型

  1. <form action="${pageContext.request.contextPath}/param/arrayParam">
  2. <input type="checkbox" name="ids" value="1"> 矢泽优步老湿 <br>
  3. <input type="checkbox" name="ids" value="2"> 樱井莉亚老湿 <br>
  4. <input type="checkbox" name="ids" value="3"> 吉泽明步老湿 <br>
  5. <input type="checkbox" name="ids" value="4"> 泷泽萝拉老湿 <br>
  6. <input type="checkbox" name="ids" value="5"> 波多野结衣老湿 <br>
  7. <input type="submit" value="数组类型">
  8. </form>
  9. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  10. @RequestMapping("/arrayParam")
  11. public String simplParam(Integer[] ids){
  12. System.out.println(Arrays.toString(ids));
  13. return "success" ;
  14. }

4、集合类型

集合中存储User对象

  1. package com.smiledog.bean;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. import java.util.List;
  6. import java.util.Map;
  7. /**
  8. * @author SmILeDog
  9. **/
  10. @AllArgsConstructor
  11. @NoArgsConstructor
  12. @Data
  13. public class UserOv {
  14. private String username;
  15. private Integer age;
  16. private List<User> userList;
  17. private Map<String,User> userMap;
  18. }
  19. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  20. <form action="${pageContext.request.contextPath}/helloWorld/jihe" method="get">
  21. 姓名: <input type="text" name="username">
  22. 年龄: <input type="text" name="age"> <br/>
  23. user属性中的姓名:<input type="text" name="user.username"><br/>
  24. user属性中的年龄:<input type="text" name="user.age"> <br/>
  25. list中第一个user对象的年龄:<input type="text" name="userList[0].age"> <br/>
  26. list中第一个user对象的姓名:<input type="text" name="userList[0].username"> <br/>
  27. list中第二个user对象的年龄: <input type="text" name="userList[1].age"> <br/>
  28. list中第二个user对象的姓名: <input type="text" name="userList[1].username"> <br/>
  29. map中第一个键值对中值user对象的年龄: <input type="text" name="userMap['one'].age"> <br/>
  30. map中第一个键值对中值user对象的姓名: <input type="text" name="userMap['one'].username"> <br/>
  31. map中第二个键值对中值user对象的年龄: <input type="text" name="userMap['two'].age"> <br/>
  32. map中第二个键值对中值user对象的姓名: <input type="text" name="userMap['two'].username"><br/>
  33. <input type="submit" value="复杂类型">
  34. </form>
  35. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  36. /**
  37. * 集合类型
  38. * 集合存储User对象
  39. */
  40. @RequestMapping("/jihe")
  41. public String jihe(UserOv userOV) {
  42. System.out.println("获取集合类型参数成功....");
  43. System.out.println(userOV.getUsername());
  44. System.out.println(userOV.getAge());
  45. System.out.println(userOV.getUserList());
  46. System.out.println(userOV.getUserMap());
  47. // 转发到success.jsp页面
  48. return "success";
  49. }

对象中存储数组

二、解决中文乱码问题

如果是get请求,tomcat8以上版本的服务器统一了UTF-8编码,不会出现乱码
如果是post请求,由于servlet规范当中的post默认编码是ISO08859-1,就会乱码
web.xml文件添加以下代码

  1. <!--中文乱码过滤器-->
  2. <filter>
  3. <filter-name>CharacterEncodingFilter</filter-name>
  4. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  5. <init-param>
  6. <param-name>encoding</param-name>
  7. <param-value>UTF-8</param-value>
  8. </init-param>
  9. </filter>
  10. <filter-mapping>
  11. <filter-name>CharacterEncodingFilter</filter-name>
  12. <url-pattern>/*</url-pattern>
  13. </filter-mapping>

三、自定义类型转换器

用于时间格式的转换:前端输入的日期字符串,到后端要转换成Date类型数据

日期格式转换类:

  1. package com.smiledog.convert;
  2. import org.springframework.core.convert.converter.Converter;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5. /**
  6. * 日期类型转换器
  7. * @author SmILeDog
  8. **/
  9. public class DateConverter implements Converter<String, Date> {
  10. @Override
  11. public Date convert(String dateStr) {
  12. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  13. Date date = null;
  14. try {
  15. date = dateFormat.parse(dateStr);
  16. } catch (Exception e) {
  17. e.printStackTrace();
  18. }
  19. return date;
  20. }
  21. }

xml编写:

  1. <!--开启mvc注解支持-->
  2. <mvc:annotation-driven conversion-service="conversionService"/>
  3. <!-- 扩展自定义的类型转换器 -->
  4. <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
  5. <property name="converters">
  6. <set>
  7. <bean class="com.smiledog.convert.DateConverter"></bean>
  8. </set>
  9. </property>
  10. </bean>

测试:

  1. package com.smiledog.web;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import java.text.SimpleDateFormat;
  5. import java.util.Date;
  6. /**
  7. * @author SmILeDog
  8. **/
  9. @Controller
  10. public class DateTimeFormatTest {
  11. /**
  12. * 日期格式化注解版
  13. * @param birthday 前端传过来的时间字符串
  14. * @return
  15. @RequestMapping("/getTime")
  16. public String getTime(@DateTimeFormat(pattern ="yyyy-MM-dd")Date birthday){
  17. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
  18. System.out.println(dateFormat.format(birthday));
  19. return "success";
  20. }*/
  21. @RequestMapping("/getTime")
  22. public String getTime(Date birthday){
  23. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
  24. System.out.println(dateFormat.format(birthday));
  25. return "success";
  26. }
  27. }

四、SpringMVC相关注解

@RequestParam

用于将指定的请求参数赋给方法中的形参,可以接收普通参数,也可以接收对象
常用于:数据查询时的分页操作
相关属性:value:请求参数名(必须)
required:表示是否必须,默认为true,请求该方法是必须携带参数和值
defaultValue:可设置请求参数的默认值

  1. @RequestParam(value="参数名",required="true/false",defaultValue=" ")
  1. <a href="/requestParam?pageNum=1&size=5">请求参数(分页)</a><br>
  1. @RequestMapping("requestParam")
  2. public String requestParam(
  3. @RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
  4. @RequestParam(value = "size",defaultValue = "10")Integer size){
  5. System.out.println("页码:"+pageNum);
  6. System.out.println("每页展示的数据:"+size);
  7. return "success";
  8. }

@RequestHeader

获取指定的请求头,相当于Servlet中的getHeader()方法

  1. <a href="${pageContext.request.contextPath}/requestHeader">请求头</a>
  1. @RequestMapping("/requestHeader")
  2. public String requestHeader(
  3. @RequestHeader("User-Agent") String userAgent ,
  4. @RequestHeader("cookie") String cookie){
  5. System.out.println(userAgent);
  6. System.out.println(cookie);
  7. return "success" ;
  8. }

@CookieValue

获取指定Cookie的值

  1. <a href="${pageContext.request.contextPath}/cookieValue">获取指定的Cookie</a>
  1. @RequestMapping("/cookieValue")
  2. public String cookieValue(
  3. @CookieValue("JSESSIONID") String cookie){
  4. System.out.println(cookie);
  5. return "success" ;
  6. }