一、学习过的mvc框架:Struts2
springMVC就是类似于Struts2的mvc框架,属于SpringFrameWork的后续产品。
二、为什么学SpringMVC?
SpringMVC与Struts2区别 | |||
---|---|---|---|
对比项目 | SrpingMVC | Struts2 | 优势 |
国内市场情况 | 有大量用户,一般新项目启动都会选用springmvc | 有部分老用户,老项目组,由于习惯了,一直在使用。 | 国内情况,springmvc的使用率已经超过Struts2 |
框架入口 | 基于servlet | 基于filter | 本质上没太大优势之分,只是配置方式不一样 |
框架设计思想 | 控制器基于方法级别的拦截,处理器设计为单实例 | 控制器基于类级别的拦截, 处理器设计为多实例 | 由于设计本身原因,造成了Struts2,通常来讲只能设计为多实例模式, 相比于springmvc设计为单实例模式,Struts2会消耗更多的服务器内存。 |
参数传递 | 参数通过方法入参传递 | 参数通过类的成员变量传递 | Struts2通过成员变量传递参数,导致了参数线程不安全,有可能引发并发的问题。 |
与spring整合 | 与spring同一家公司,可以与spring无缝整合 | 需要整合包 | Springmvc可以更轻松与spring整合 |
三、SpringMVC入门
3.1 开发环境
Jdk:jdk1.7
Eclipse:mars
Tomcat:apache-tomcat-7
spring:4.2.4
3.2 开发步骤
3.2.1 创建Dynamic web项目
3.2.2 导入jar包
3.2.3 编写TestController类
package springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloControl {
@RequestMapping("hello")
public ModelAndView hello() {
System.out.println("hello springmvc...");
ModelAndView mav = new ModelAndView();
// 设置数据模型,用于传递到jsp
mav.addObject("msg", "hello springmvc...");
// 设置视图名字,用于响应用户
mav.setViewName("/jsp/hello.jsp");
return mav;
}
}
3.2.4 创建hello.jsp页面
3.2.5 创建和配置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:p="http://www.springframework.org/schema/p"
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-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 配置controller扫描包 -->
<context:component-scan base-package="springmvc.controller" />
</beans>
3.2.6 在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"
id="WebApp_ID" version="2.5">
<display-name>01_springmvc</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!--核心控制器的配置 -->
<servlet>
<servlet-name>springmvc</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>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
3.2.7 启动项目通过浏览器测试
3.3 小结-springmvc代码执行流程
四、完成商品列表加载
4.1 创建Item的pojo
public class Item {
// 商品id
private int id;
// 商品名称
private String name;
// 商品价格
private double price;
// 商品创建时间
private Date createtime;
// 商品描述
private String detail;
创建带参数的构造器
set/get。。。
}
4.2 编写ItemController
package springmvc.controller;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import springmvc.pojo.Item;
@Controller
public class ItemController {
@RequestMapping("itemList")
public ModelAndView itemList() {
ModelAndView mav = new ModelAndView();
List<Item> list = Arrays.asList(new Item(1, "冰箱", 3000,
new Date(), "效果很好"),
new Item(2, "空调", 2000, new Date(), "制冷效果很差"),
new Item(3, "微波炉", 4000, new Date(), "很贵"),
new Item(4, "电吹风", 30, new Date(), "太小"));
mav.addObject("itemList", list);
mav.setViewName("/jsp/itemList.jsp");
return mav;
}
}
4.3 编写itemList.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>查询商品列表</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/queryItem.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="submit" value="查询"/></td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td>商品价格</td>
<td>生产日期</td>
<td>商品描述</td>
<td>操作</td>
</tr>
<c:forEach items="${itemList }" var="item">
<tr>
<td>${item.name }</td>
<td>${item.price }</td>
<td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
<td>${item.detail }</td>
<td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
4.4 启动项目通过浏览器测试
五、SpringMVC架构
5.1 框架默认加载组件
5.1.1 处理器映射器与处理器适配器
5.1.1.1 处理器映射器
从spring3.1版本开始,废除了DefaultAnnotationHandlerMapping的使用,推荐使用RequestMappingHandlerMapping完成注解式处理器映射。
<!-- 配置处理器映射器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
5.1.1.2 处理器适配器
从spring3.1版本开始,废除了AnnotationMethodHandlerAdapter的使用,推荐使用RequestMappingHandlerAdapter完成注解式处理器适配。
<!-- 处理器适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />
5.1.1.3 小结
映射器与适配器必需配套使用,如果映射器使用了推荐的RequestMappingHandlerMapping,适配器也必需使用推荐的RequestMappingHandlerAdapter。
5.1.1.4 注解驱动
<!-- 注解驱动配置,代替映射器与适配器的单独配置,同时支持json响应(推荐使用) -->
<mvc:annotation-driven />
5.1.2 视图解析器
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置视图响应的前缀 -->
<property name="prefix" value="/jsp/" />
<!-- 配置视图响应的后缀 -->
<property name="suffix" value=".jsp" />
</bean>
package springmvc.controller;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import springmvc.pojo.Item;
@Controller
public class ItemController {
@RequestMapping("itemList")
public ModelAndView itemList() {
ModelAndView mav = new ModelAndView();
List<Item> list = Arrays.asList(new Item(1, "冰箱", 3000,
new Date(), "效果很好"),
new Item(2, "空调", 2000, new Date(), "制冷效果很差"),
new Item(3, "微波炉", 4000, new Date(), "很贵"),
new Item(4, "电吹风", 30, new Date(), "太小"));
mav.addObject("itemList", list);
mav.setViewName("itemList");//这里可以直接缩写了
return mav;
}
}
5.2 总结-springMVC架构
六、SpringMVC与Mybatis整合
创建Web新工程:02_springmvc_mybatis
- 搭建新工程。
- 整合功能主要是把商品列表加载,从数据库中查出。
- Dao开发可以用Mybatis逆向工程。
6.1 思路
Dao层:
1、SqlMapConfig.xml,空文件即可。需要文件头。
2、applicationContext-dao.xml。
a) 数据库连接池
b) SqlSessionFactory对象,需要spring和mybatis整合包下的。
c) 配置mapper文件扫描器。
Service层:
1、applicationContext-service.xml包扫描器,扫描@service注解的类。
2、applicationContext-trans.xml配置事务。
Controller层:
Springmvc.xml
1、包扫描器,扫描@Controller注解的类。
2、配置注解驱动。
3、视图解析器
Web.xml
- 配置spring容量监听器
- 配置前端控制器
七、参数绑定
7.1 默认支持的参数类型
基于完成需求:点击修改商品时,打开商品编辑页面,展示商品信息
@Autowired
private ItemService itemService;
/**
* 演示默认支持的参数传递
*
* @return
*/
@RequestMapping("itemList")
public ModelAndView itemList() {
ModelAndView mav = new ModelAndView();
List<Item> list = itemService.getItemList();
mav.addObject("itemList", list);
mav.setViewName("itemList");
return mav;
}
/**
* 演示springmvc默认参数的传递
* 跳转修改商品信息页面
* @return
*/
@RequestMapping("itemEdit")
public ModelAndView itemEdit(HttpServletRequest request,
HttpServletResponse response,HttpSession session){
ModelAndView mav = new ModelAndView();
//request获取参数
String id = request.getParameter("id");
System.out.println("id为:" + id);
//其它对象输出
System.out.println("response对象:" + response);
System.out.println("session对象:" + session);
//查询商品信息
Item item = itemService.getItemById(new Integer(id));
//设置商品数据返回页面
mav.addObject("item", item);
//设置视图名称
mav.setViewName("itemEdit");
return mav;
}
7.2 绑定简单参数
/**
* 演示简单参数传递
* 跳转修改商品信息页面
* @RequestParam用法:入参名字与方法名参数名不一致时使用{
* value:传入的参数名,required:是否必填,defaultValue:默认值
* }
*
*/
@RequestMapping("itemEdit")
public ModelAndView itemEdit(@RequestParam(value="id",required=true,defaultValue="1")Integer ids){
ModelAndView mav = new ModelAndView();
//查询商品信息
Item item = itemServices.getItemById(ids);
//设置商品数据返回页面
mav.addObject("item", item);
//设置视图名称
mav.setViewName("itemEdit");
return mav;
}
// Integer后的id名字必须和页面传递过来的一样,或者用如下方法
/*
* public String itemEdit(Model model,@RequestParam("id") Integer ids) {
* Item item = itemService.getItemById(ids);
* }
*/
// 或者在修改商品信息的时候,必须得传递一个参数,否则就会报错,可以这么写
/*
* public String itemEdit(Model model,
* @RequestParam(value="id",required=true) Integer ids) {
* Item item = itemService.getItemById(ids);
*/
// 或者可以设置一个默认值,没有传递参数时,默认传递一个值
/*
* public String itemEdit(Model model,
* @RequestParam(value="id",required=true,defaultValue="1") Integer ids) {
* Item item = itemService.getItemById(ids);
*/
7.3 Model/ModelMap
/**
* 演示返回String,通过Model/ModelMap返回数据模型
* 跳转修改商品信息页面
* @param id
* @return
*/
@RequestMapping("itemEdit")
public String itemEdit(@RequestParam("id")Integer ids,Model m,ModelMap model){
// Model与ModelMap的区别:用法一样,但是前者为接口,后者为实现类,习惯用前者
//查询商品信息
Item item = itemServices.getItemById(ids);
//通过Model把商品数据返回页面
model.addAttribute("item", item);
//返回String视图名字
return "itemEdit";
}
7.4 绑定pojo对象
要点:表单提交的name属性必需与pojo的属性名称一致。
/**
* 演示传递pojo参数
* 更新商品信息
* @return
*/
@RequestMapping("updateItem")
public String updateItem(Item item,Model model){
//更新商品
itemServices.update(item);
//返回商品模型
model.addAttribute("item", item);
//返回担任提示
model.addAttribute("msg", "修改商品成功");
//返回修改商品页面
return "itemEdit";
}
7.5 绑定包装的pojo
要点:通过点(.)传递属性。
7.5.1 pojo
package springmvc.pojo;
/**
* 包装的pojo传递
*
* @author Administrator
*
*/
public class QueryVo {
private Item item;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
}
7.5.2 controller代码
/**
* 演示包装pojo传递
* @param vo
* @return
*/
@RequestMapping("queryItem")
public String queryItem(QueryVo vo,Model model){
if(vo.getItem()!=null){
System.out.println(vo.getItem());
}
//模拟搜索商品
List<Item> itemList=itemService.getItemByQueryVo(vo);
model.addAttribute("itemList", itemList);
return "itemList";
}
7.5.3 实现类
@Override
public List<Item> getItemByQueryVo(QueryVo vo) {
ItemExample example = new ItemExample();
ItemExample.Criteria criteria = example.createCriteria();
if (vo.getItem().getName() != null) {
criteria.andNameLike("%" + vo.getItem().getName() + "%");
}
if (vo.getItem().getPrice() != null) {
criteria.andPriceEqualTo(vo.getItem().getPrice());
}
return itemMapper.selectByExample(example);
}