SpringMVC01:入门、请求参数绑定、自定义类型转换器、常见注解
一、介绍--三层架构和MVC
1、三层架构介绍和MVC设计模型介绍
开发架构一般都是基于两种形式,一种是 C/S 架构,也就是客户端/服务器,另一种是 B/S 架构,也就是浏览器/服务器。在 JavaEE 开发中,几乎全都是基于 B/S 架构的开发。
2、SpringMVC框架的介绍
是一种基于 Java 的实现 MVC 设计模型的请求驱动类型的轻量级 Web 框架,属于 Spring FrameWork 的后续产品,已经融合在 Spring Web Flow 里面。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。
- 易于整合其他框架
- 无须实现任何接口
- 支持RESTful 编程风格
优势
- 清晰的角色划分
二、入门程序案例
1、需求分析
2、搭建开发环境
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<!--任何请求都会经过servlet-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3、入门代码编写
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>入门程序</h3>
<a href="hello">入门程序</a>
</body>
</html>
<?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">
<!--开启注解的扫描,需要有context支持注解-->
<context:component-scan base-package="cn.itcast"></context:component-scan>
<!--配置视图解析器对象,访问WEB-INF下的文件-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置访问路径的前缀和后缀-->
<property name="prefix" value="/WEB-INF/pages"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--开启SpringMVC框架注解的支持-->
<mvc:annotation-driven/>
</beans>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocationn</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<!--任何请求都会经过servlet-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
package cn.itcast.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 控制器类
*/
@Controller
public class HelloController {
@RequestMapping(path="hello")
public String sayHello(){
System.out.println("hello SpringMVC");
return "success";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>入门成功</h3>
</body>
</html>
4、入门案例的流程总结
5、入门案例中使用的组件介绍
在 SpringMVC 的各个组件中,处理器映射器、处理器适配器、视图解析器称为 SpringMVC 的三大组件。
使 用 <mvc:annotation-driven> 自动加载 RequestMappingHandlerMapping (处理映射器) 和
RequestMappingHandlerAdapter ( 处 理 适 配 器 ) , 可 用 在 SpringMVC.xml 配 置 文 件 中 使 用
<mvc:annotation-driven>替代注解处理器和适配器的配置。
6、RequestMapping注解
用于建立请求 URL 和处理请求方法之间的对应关系。
属性
- path和value相同,value可以省略
- method[]表示可以请求的方式,GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
- 用于指定限制请求参数的条件。它支持简单的表达式。要求请求参数的 key 和 value 必须和配置的一模一样。= 和 !分别表示等于或不等于
- headers:用于指定限制请求消息头的条件。
package cn.itcast.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* 控制器类
* /user/hello:放在类上或方法上代表一级/二级目录
*/
@Controller
@RequestMapping(path = "/user")
public class HelloController {
@RequestMapping(path="/hello")
public String sayHello(){
System.out.println("hello SpringMVC");
return "success";
}
/**
* 测试RequestMapping注解
* @return
*/
@RequestMapping(path = "/testRequestMapping",method = {RequestMethod.GET,RequestMethod.POST}
,params = {"username=heihei"},headers = {"Accept"})
public String testRequestMapping(){
System.out.println("测试RequestMapping...");
return "success";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>入门程序</h3>
<%--<a href="hello">入门程序</a>--%>
<a href="/user/testRequestMapping?username=heihei">RequestMapping注解</a>
</body>
</html>
三、请求参数绑定※
1、请求参数绑定入门
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--请求参数的绑定(写相对路径)
请求参数多时,可以使用JavaBean进行封装
--%>
<a href="param/testParam?username=liujinhui&password=qaz123">请求参数绑定</a>
</body>
</html>
package cn.itcast.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 请求参数的绑定
*/
@Controller
@RequestMapping("/param")
public class ParamController {
/**
* 请求参数绑定的入门
* @return
*/
@RequestMapping("/testParam")
public String testParam(String username,String password){
System.out.println("执行了..."+username+password);
return "success";
}
}
2、请求参数绑定实体类型
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--请求参数的绑定(写相对路径)
请求参数多时,可以使用JavaBean进行封装
--%>
<%--<a href="param/testParam?username=liujinhui&password=qaz123">请求参数绑定</a>--%>
<form action="/param/saveAccount" method="post">
姓名:<input type="text" name="username" /><br>
密码:<input type="text" name="password" /><br>
金额:<input type="text" name="money" /><br>
用户姓名:<input type="text" name="user.uname" /><br>
用户年龄:<input type="text" name="user.age" /><br>
<input type="submit" value="提交now" /><br>
</form>
</body>
</html>
package cn.itcast.controller;
import cn.itcast.domain.Account;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 请求参数的绑定
*/
@Controller
@RequestMapping("/param")
public class ParamController {
/**
* 请求参数绑定的入门
* @return
*/
@RequestMapping("/testParam")
public String testParam(String username,String password){
System.out.println("执行了..."+username+password);
return "success";
}
/**
* 把请求参数绑定,将数据封装到Java Bean的类中
* @param username
* @param password
* @return
*/
@RequestMapping("/saveAccount")
public String saveAccount(Account account){
System.out.println(account);
return "success";
}
}
3、配置解决中文乱码的过滤器
过滤器解决中文乱码
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--配置前端控制器-->
<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就会创建dispatcherServlet对象-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<!--任何请求都会经过servlet-->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--配置解决中文乱码的过滤器-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
4、请求参数绑定集合类型
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--把数据封装到Account类中,类中存在List和Map的集合--%>
<form action="/param/saveAccount" method="post">
姓名:<input type="text" name="username" /><br>
密码:<input type="text" name="password" /><br>
金额:<input type="text" name="money" /><br>
用户姓名:<input type="text" name="list[0].uname" /><br>
用户年龄:<input type="text" name="list[0].age" /><br>
用户姓名:<input type="text" name="map['one'].uname" /><br>
用户年龄:<input type="text" name="map['one'].age" /><br>
<input type="submit" value="提交now" /><br>
</form>
</body>
</html>
public class Account implements Serializable {
private String username;
private String password;
private Double money;
private List<User> list;
private Map<String,User> map;
public List<User> getList() {
return list;
}
public void setList(List<User> list) {
this.list = list;
}
public Map<String, User> getMap() {
return map;
}
public void setMap(Map<String, User> map) {
this.map = map;
}
四、自定义类型转换器
1、自定义类型转换器演示异常
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--自定义类型转换器--%>
<form action="/param/saveUser" method="post">
用户姓名:<input type="text" name="uname" /><br>
用户年龄:<input type="text" name="age" /><br>
用户生日:<input type="text" name="date" /><br>
<input type="submit" value="提交now" /><br>
</form>
</body>
</html>
2、自定义类型转换器代码编写
<?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">
<!--开启注解的扫描,需要有context支持注解-->
<context:component-scan base-package="cn.itcast"></context:component-scan>
<!--配置视图解析器对象,访问WEB-INF下的文件-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置访问路径的前缀和后缀-->
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置自定义类型转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="cn.itcast.utils.StringToDataConverter"/>
</set>
</property>
</bean>
<!--开启SpringMVC框架注解的支持-->
<mvc:annotation-driven conversion-service="conversionService"/>
</beans>
package cn.itcast.utils;
import org.springframework.core.convert.converter.Converter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 把字符串转换成日期
*/
public class StringToDataConverter 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");
//把字符串转换为日期
return df.parse(source);
} catch (Exception e) {
throw new RuntimeException("数据类型转换出现错误");
}
}
}
3、获取Servlet原生的API
package cn.itcast.controller;
import cn.itcast.domain.Account;
import cn.itcast.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 请求参数的绑定
*/
@Controller
@RequestMapping("/param")
public class ParamController {
/**
* 原生的api
* @return
*/
@RequestMapping("/testServlet")
public String testServlet(HttpServletRequest request, HttpServletResponse response){
System.out.println(request);
HttpSession session = request.getSession();
System.out.println(session);
ServletContext servletContext = session.getServletContext();
System.out.println(servletContext);
System.out.println(response);
return "success";
}
}
五、其他常用注解
1、RequestParam注解
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--常用的注解--%>
<a href="anno/testRequestParam?name=哈哈">RequestParam</a>
</body>
</html>
package cn.itcast.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* 常用的注解
*/
@Controller
@RequestMapping("/anno")
public class AnnoController {
@RequestMapping("/testRequestParam")
//表示不一定required(默认)
public String testRequestParam(@RequestParam(name="name",required=false) String username){
System.out.println("testRequestParam执行了");
System.out.println(username);
return "success";
}
}
2、RequestBody注解
获取请求体内容
post有请求体,get在地址栏
package cn.itcast.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* 常用的注解
*/
@Controller
@RequestMapping("/anno")
public class AnnoController {
/**
* 获取到请求体的内容
* @param username
* @return
*/
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String body){
System.out.println("testRequestParam执行了");
System.out.println(body);
return "success";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/anno/testRequestBody" method="post">
用户姓名:<input type="text" name="username" /><br>
用户年龄:<input type="text" name="age" /><br>
<input type="submit" value="提交now" /><br>
</form>
</body>
</html>
3、PathVariable注解
REST 风格 URL
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--常用的注解--%>
<a href="anno/testPathVariable/10">RequestParam</a>
</body>
</html>
package cn.itcast.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* 常用的注解
*/
@Controller
@RequestMapping("/anno")
public class AnnoController {
/**
* PathVariable注解
* @return
*/
@RequestMapping("/testPathVariable/{sid}")
public String testPathVariable(@PathVariable(name="sid") String id){
System.out.println("testPathVariable执行了");
System.out.println(id);
return "success";
}
}
4、HiddentHttpMethodFilter过滤器(了解)
5、RequestHeader注解
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--常用的注解--%>
<a href="anno/testRequestHeader">RequestParam</a>
</body>
</html>
/**
* 获取请求头的值
* @param header
* @return
*/
@RequestMapping(value = "/testRequestHeader")
public String testRequestHeader(@RequestHeader(value="Accept") String header){
System.out.println("testPathVariable执行了");
System.out.println(header);
return "success";
}
6、CookieValue注解
@RequestMapping(value = "/testCookieValue")
public String testCookieValue(@CookieValue(value = "JSESSIONID") String cookieValue){
System.out.println("testPathVariable执行了");
System.out.println(cookieValue);
return "success";
}
7、ModelAttribute注解
放在方法上优先执行,保证字段中存在数据库原有的数据
有返回值
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--常用的注解--%>
<a href="anno/testCookieValue">RequestParam</a>
<form action="/anno/testModelAttribute" method="post">
用户姓名:<input type="text" name="uname" /><br>
用户年龄:<input type="text" name="age" /><br>
<input type="submit" value="提交now" /><br>
</form>
</body>
</html>
/**
* ModelAttribute注解
* @return
*/
@RequestMapping(value = "/testModelAttribute")
public String testModelAttribute(User user){//直接拿到
//此时就能拿到User的日期
System.out.println("testModelAttribute执行了");
System.out.println(user);
return "success";
}
/**
* 有返回值
* 该方法会先执行
* 操作:
*/
@ModelAttribute
public User showUser(String uname){
System.out.println("showUser方法执行了");
//通过用户名查询数据库(模拟)
User user = new User();
user.setUname(uname);
user.setAge(20);
user.setDate(new Date());
//将全部数据封装上
return user;
}
没有返回值
/**
* ModelAttribute注解
* @return
*/
@RequestMapping(value = "/testModelAttribute")
//方法内需要借助ModelAttribute注解
public String testModelAttribute(@ModelAttribute(value="abc") User user){
//此时就能拿到User的日期
System.out.println("testModelAttribute执行了");
System.out.println(user);
return "success";
}
/**
* 没有返回值
* @param uname
* @return
*/
@ModelAttribute
public void showUser(String uname, Map<String,User> map){
System.out.println("showUser方法执行了");
//通过用户名查询数据库(模拟)
User user = new User();
user.setUname(uname);
user.setAge(20);
user.setDate(new Date());
map.put("abc",user);
//将全部数据封装上
}
8、SessionAttributes注解
session会话域对象,多次存取可以正常使用
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--常用的注解--%>
<a href="anno/testCookieValue">RequestParam</a>
<form action="/anno/testModelAttribute" method="post">
用户姓名:<input type="text" name="uname" /><br>
用户年龄:<input type="text" name="age" /><br>
<input type="submit" value="提交now" /><br>
</form>
<br>
<a href="anno/testSessionAttributes">RequestParam</a><br>
<a href="anno/getSessionAttributes">从session域中取值</a><br>
<a href="anno/delSessionAttributes">删除</a>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>入门成功</h3>
${ msg }
${ requestScope.msg }
${ sessionScope }
</body>
</html>
package cn.itcast.controller;
import cn.itcast.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
/**
* 常用的注解
*/
@Controller
@RequestMapping("/anno")
@SessionAttributes(value={"msg"}) //相当于把msg=美美存入到session域中
public class AnnoController {
/**
* SessionAttributes的注解
* @return
*/
@RequestMapping(value = "/testSessionAttributes")
public String testSessionAttributes(Model model){
//HttpServletRequest request作为参数
//此时就能拿到User的日期
System.out.println("testModelAttribute执行了");
//希望向request存一个值,从成功页面中把值取出来
//request.setAttribute("aaa","123");耦合性过高
//底层会存储到request对象中
model.addAttribute("msg","美美");
return "success";
}
/**
* 从session域中取值
* @param modelMap
* @return
*/
@RequestMapping(value = "/getSessionAttributes")
public String getSessionAttributes(ModelMap modelMap){
String msg = (String) modelMap.get("msg");
System.out.println(msg);
return "success";
}
/**
* 清除
* @param status
* @return
*/
@RequestMapping(value = "/delSessionAttributes")
public String delSessionAttributes(SessionStatus status){
status.setComplete();//清除
return "success";
}
}
本文来自博客园,作者:哥们要飞,转载请注明原文链接:https://www.cnblogs.com/liujinhui/p/b9ebab7ee7dabc2aadb91915e5f1fbc1.html