Spring MVC day01 请求参数问题及常用注解
Posted wx5d9e78e914c3e
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring MVC day01 请求参数问题及常用注解相关的知识,希望对你有一定的参考价值。
文章目录
一、Spring MVC基本概念1-1 Spring MVC的优势
1-2 SpringMVC 和 Struts2 的优略分析
二、 SpringMVC 的入门2-1 SpringMVC 的入门案例
- 创建WEB工程,引入开发的jar包
<properties>
<spring.version>5.0.2.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
- 配置web.xml配置文件
<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:springmvc.xml</param-value>
</init-param>
<!-- 配置servlet启动时加载对象 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
- 编写springmvc.xml的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<!--配置Spring配置容器时要扫描的包-->
<context:component-scan base-package="com.qgc"></context:component-scan>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--Spring开启注解-->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
- 编写HelloController控制器类
@Controller
public class HelloController
@RequestMapping(path = "/hello")
public String sayHello()
System.out.println("Spring配置成功");
return "success";
2-2 入门程序执行流程
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bNcnySHF-1581502120032)(https://raw.githubusercontent.com/1519059197/img_note/master/小书匠/1581488134957.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jN4S48bi-1581502120032)(https://raw.githubusercontent.com/1519059197/img_note/master/小书匠/springmvc执行流程原理.jpg)]
2-3 入门案例中涉及的组件
- DispatcherServlet:前端控制器
- HandlerMapping:处理器映射器
- Handler:处理器
- HandlAdapter:处理器适配器
- View Resolver:视图解析器
- View:视图
2-4 <mvc:annotation-driven>
说明
<!-- 上面的标签相当于 如下配置-->
<!-- Begin -->
<!-- HandlerMapping -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
<!-- HandlerAdapter -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>
<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"></bean>
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
<!-- HadnlerExceptionResolvers -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver"></bean>
<bean class="org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver"></bean>
<!-- End -->
2-5 RequestMapping 注解
- RequestMapping可以放在类上,下面代码访问路径就为:项目名称/user/hello
@Controller
@RequestMapping(path = "/user")
public class HelloController
@RequestMapping(path = "/hello")
public String sayHello()
System.out.println("Spring配置成功");
return "success";
- RequestMapping的属性
3-1 基本类型参数
直接在controller类上加上参数即可,要求此参数与前端传过来的参数名称一致
@RequestMapping(path = "/hello")
public String getParam(String username)
System.out.println("用户名"+username);
return "success";
3-2 POJO 类型参数
直接写上实体类即可
@RequestMapping(path = "/form")
public String getParams(Account account)
System.out.println(account);
return "success";
3-3 解决POST提交乱码问题
在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>
3-4 给集合属性数据封装
JSP页面编写方式:list[0].属性
或者是map[key属性].value属性
3-5 自定义类型转换器
- 写一个自定义类型转换器实现Converter接口
public class StringToDate implements Converter<String, Date>
/**
* 自定义类型转换器
*
* @param source 传入的参数
* @return
*/
@Override
public Date convert(String source)
if (source == null)
throw new RuntimeException("参数不能为空");
try
DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); // 解析字符串
Date date = df.parse(source);
return date;
catch (Exception e)
throw new RuntimeException("类型转换错误");
- 注册自定义类型转换器,在springmvc.xml配置文件中编写配置
<!--配置自定义转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="cn.itcast.utils.StringToDateConverter"/>
</set>
</property>
</bean>
<!--Spring开启注解-->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
3-6 获取Servlet原生api
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request,
HttpServletResponse response,
HttpSession session)
System.out.println(request);
System.out.println(response);
System.out.println(session);
四、 常用注解
4-1 RequestParam
例:
//将前端的name值传给username
@RequestMapping("/useRequestParam")
public String useRequestParam(@RequestParam("name") String username)
4-2 RequestBody
例:
@RequestMapping("/useRequestBody")
public String useRequestBody(@RequestBody(required=false) String body)
4-3 PathVaribale
例:
@RequestMapping("/usePathVariable/id")
public String usePathVariable(@PathVariable("id") Integer id)
4-4 RequestHeader(不常用)
例:
@RequestMapping("/useRequestHeader")
public String useRequestHeader(@RequestHeader(value="Accept-Language",required=false)String requestHeader)
4-5 CookieValue(不常用)
@RequestMapping("/useCookieValue")
public String useCookieValue(@CookieValue(value="JSESSIONID",required=false) String cookieValue)
4-6 ModelAttribute
- 方式一:在方法名上加ModelAttribute
@RequestMapping(path = "/test2")
public String saveUser(User user)
System.out.println(user);
return "success";
@ModelAttribute
public User modelAttribute(String uname)
User user = new User();
user.setAge(99);
user.setBirthday(new Date());
user.setUname(uname);
return user;
- 方式二:不适用返回值
@RequestMapping(path = "/test3")
public String saveUser1(@ModelAttribute User user)
System.out.println(user);
return "success";
@ModelAttribute
public void modelAttribute(String uname, Map<String,User> map)
User user = new User();
user.setAge(99);
user.setBirthday(new Date());
user.setUname(uname);
map.put("abc",user);
4-7 SessionAttribute
例:
前端页面
<a href="user/setSessionAttribute">设置值</a>
<a href="user/getSessionAttribute">取出值</a>
<a href="user/delSessionAttribute">删除值</a>
后端
@SessionAttributes(value="abc",types = String.class)
public class HelloController
@RequestMapping("/setSessionAttribute")
public String setSessionAttribute(Model model)
model.addAttribute("abc","123e");
return "success";
@RequestMapping("/getSessionAttribute")
public String getSessionAttribute(ModelMap modelMap)
Object o = modelMap.get("abc");
System.out.println(o);
return "success";
@RequestMapping("/delSessionAttribute")
public String delSessionAttribute(SessionStatus status)
status.setComplete();
return "success";
以上是关于Spring MVC day01 请求参数问题及常用注解的主要内容,如果未能解决你的问题,请参考以下文章
Spring MVC - RequestParamException 参数不存在