springmvc
Spring mvc属于表现层的框架,它是Spring框架的一部分
》接收请求,获取参数
》处理参数
》将结果响应给浏览器 如 重定向或者请求转发或者返回json
springmvc就是对servlet的封装
springmvc的核心是前端控制器,处理业务的是Handler
spring入门小程序
- 创建实体类
public class User{
private int id;
private String username;
private String password;
private String city;
- 创建一个假数据DB
public class DB {
public static List<User> findAll(){
List<User> list = new ArrayList<User>();
list.add(new User(1,"tom","123456","北京"));
list.add(new User(2,"rose","123456","北京"));
list.add(new User(3,"tony","123456","北京"));
return list;
}
}
- 导入依赖pom.xml
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.9.RELEASE</version>
</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>
<!--让前端控制器去读 正整数,值越小,优先级越高-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
- 创建springmvc.xml
<?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: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/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--进行包扫描,创建controller层的对象 只要是指定的包与子包下面有@Controller的类
都要被创建对象,且加入ioc容器中-->
<context:component-scan base-package="com.dsf.controller"/>
</beans>
- controller层
@Controller
public class UserController {
@RequestMapping("list.action")
public ModelAndView listUser(){
List<User> list = DB.findAll();
ModelAndView mv = new ModelAndView();
mv.addObject("list",list);
mv.setViewName("jsp/list.jsp");
return mv;
}
}
- jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<table border="1px" width="100%">
<tr>
<td>编号 </td>
<td>用户名 </td>
<td>密码 </td>
<td>城市 </td>
<td>操作 </td>
</tr>
<c:forEach items="${list}" var="item" >
<tr>
<td>${item.id}</td>
<td>${item.username}</td>
<td>${item.password}</td>
<td>${item.city}</td>
<td><a href="#">修改</a> </td>
</tr>
</c:forEach>
</table>
</body>
</html>
springmvc.xml配置以及执行过程
-
三个重要对象
》HandlerMapping处理器映射器:建立地址与方法的映射
》HandlerAdapter处理器适配器:根据地址调用方法
》ViewResolver 视图解析器:处理ModelAndView -
执行过程
1、用户发送请求至前端控制器DispatcherServlet
2、DispatcherServlet收到请求调用HandlerMapping处理器映射器。
3、处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。
4、DispatcherServlet通过HandlerAdapter处理器适配器调用处理器
5、执行处理器(Controller,也叫后端控制器)。
6、Controller执行完成返回ModelAndView
7、HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet
8、DispatcherServlet将ModelAndView传给ViewReslover视图解析器
9、ViewReslover解析后返回具体View
10、DispatcherServlet对View进行渲染视图(即将模型数据填充至视图中)。
11、DispatcherServlet响应用户
- springmvc.xml配置处理器映射器和处理器适配器
<!--处理器映射器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<!--处理器适配器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
- 配置视图解析器
<mvc:annotation-driven/>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--定义页面路径的前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--定义页面路径的后缀-->
<property name="suffix" value=".jsp"/>
</bean>
- 头部
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
springmvc参数绑定
- 基本参数绑定
参数绑定是用户请求服务器的时候会给后台传递参数, 如何来快速的接收到用户传递的参数
传入的参数的名字和本方法形参的名字一致
,不管前后端代码,都要保持一致
springmvc的内部有默认的类型转换器: String ---->int,只能转换基本类型和字符串
controller层
@RequestMapping("login.action")
public ModelAndView test01(String username,String password){
System.out.println(username);
System.out.println(password);
ModelAndView mv= new ModelAndView();
mv.setViewName("main");
return mv;
}
- @RequestParam 注解
如果你的形参的名字和页面传入的参数名字不一致,则可以使用@RequestParam
就是说使用@RequestParam 注解,前后端参数可以不一致
只要注解中value的值和页面传入的参数名字一致即可
required = true : 表示该参数必须给值 ,如果没有给这个值,则出现400页面
defaultValue = “123” :如果给了参数,就获取,如果没有给参数,则默认为123
controller层
@RequestMapping("login2.action")
public ModelAndView test02(@RequestParam(value="username",required = true,defaultValue = "tom") String username1, String password){
System.out.println(username1);
System.out.println(password);
ModelAndView mv= new ModelAndView();
mv.setViewName("main");
return mv;
}
- pojo类绑定
普通的java实体类
当页面需要传递多个参数时(注册),我们可以将多个参数封装到一个JavaBean类,将这个JavaBean作为方法形参,SpringMVC可以直接将页面的数据赋值给JavaBean
JavaBean类中成员变量的名字和必须和表单中name属性的值一样
实体类pojo
public class pojo {
private String username;
private String password;
}
controller层
@RequestMapping("login3.action")
public ModelAndView test03(pojo pojo ){
System.out.println(pojo .getUsername());
System.out.println(pojo .getPassword());
ModelAndView mv= new ModelAndView();
mv.setViewName("main");
return mv;
}
- queryVo绑定
queryVo是一个包装类,可以封装多个不同类型的成员变量
当前的javaBean类的成员变量有复杂类型 如:类中有另外一个类
controller层
@RequestMapping("add.action")
public ModelAndView test04(User user){
//springMVC可以将表单的数据赋值给 一个javaBean对象
System.out.println(user.getUsername());
System.out.println(user.getPassword());
System.out.println(user.getBirthday().getYear());
System.out.println(user.getBirthday().getMonth());
System.out.println(user.getBirthday().getDay());
ModelAndView mv= new ModelAndView();
mv.setViewName("main");
return mv;
}
jsp
<form method="post" action="${pageContext.request.contextPath}/add.action">
用户名: <input type="text" name="username" /><br/>
用户密码: <input type="text" name="password"/><br/>
城市: <input type="text" name="city"/><br/>
年 <input type="text" name="birthday.year"/><br/>
月<input type="text" name="birthday.month"/><br/>
日<input type="text" name="birthday.day"/><br/>
<input type="submit" value="添加"/><br/>
</form>
User类
public class User{
private int id;
private String username;
private String password;
private String city;
private Birthday birthday;
Birthday 类
public class Birthday {
private int year;
private int month;
private int day;
springmvc参数绑定乱码问题
使用过滤器
<filter>
<filter-name>UTF8Filter</filter-name>
<filter-class>com.dsf.filter.UTF8Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>UTF8Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
public class UTF8Filter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
}
springmvc参数绑定–日期格式转换
- 第一种方式
在变量上面加@DateTimeFormat(pattern =“yyyy-MM-dd”)
public class User {
private int id;
private String username;
private String password;
private String city;
private Birthday birthday;
@DateTimeFormat(pattern ="yyyy-MM-dd")
private Date birthday2;
}
- 第二种方式(不推荐)
编写日期类型转换器
转换类
//将页面上提交的日期字符串,转成Date对象
public class DateTimeFormatConvert implements Converter<String, Date> {
public Date convert(String s) {
System.out.println("convert "+s);
//转换器
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
在springmvc.xml中配置
<bean id="formattingConversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean id="dateTimeFormatConverter" class="com.dsf.convert.DateTimeFormatConvert"></bean>
</set>
</property>
</bean>
将转换工厂对象挂载到处理器适配器上(挂载到注解驱动)
<mvc:annotation-driven conversion-service="formattingConversionService"/>
可以在jsp中使用日期格式化标签
导入标签
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
调用他的标签
<fmt:formatDate value="${item.birthday2}" pattern="yyyy年MM月dd日"/>
springmvc数据回显 --》修改页面时
为了修改数据方便,可以将被修改的数据,放到ModelAndView中,传给页面,页面使用el表达式,逐个设置给表单
jsp
<td><a href="${pageContext.request.contextPath}/update.action?id=${item.id}">修改</a> </td>
controller层
@RequestMapping("update.action")
public ModelAndView updateUser(int id){//id=1
User user= DB.findById(id);
ModelAndView mv = new ModelAndView();
mv.addObject("user",user);
mv.setViewName("update");
return mv;
}
update.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${user}
<form method="post" action="${pageContext.request.contextPath}/update2.action">
用户名: <input type="text" name="username" value="${user.username}"/><br/>
用户密码: <input type="text" name="password" value="${user.password}"/><br/>
城市: <input type="text" name="city" value="${user.city}"/><br/>
年 <input type="text" name="birthday.year" value="${user.birthday.year}"/><br/>
月<input type="text" name="birthday.month" value="${user.birthday.month}"/><br/>
日<input type="text" name="birthday.day" value="${user.birthday.day}"/><br/>
出生日期<input type="text" name="birthday2"value="${user.birthday2}" /><br/>
<input type="submit" value="更新"/><br/>
</form>
</body>
</html