SpringMVC入门

目录

 

一.SpringMVC与Struts2区别

二.入门案例

三.完成商品列表加载

四.SpringMVC架构

4.1 框架默认加载组件

4.1.1 处理器映射器

4.1.2 处理器适配器

4.1.4 注解驱动

4.1.5 视图解析器

4.2 总结-springMVC架构

五.SpringMVC与Mybatis整合

5.1 思路

5.2 整合案例

六.参数绑定

6.1 默认支持的参数类型

6.2 绑定简单参数

6.3 Model/ModelMap

6.4 绑定pojo对象

6.5 绑定包装的pojo


一.SpringMVC与Struts2区别

二.入门案例

① 编写TestController类

@Controller
public class HelloController {

	@RequestMapping("hello")
	public ModelAndView hello(){
		System.out.println("hello springmvc....");
		//创建ModelAndView对象
		ModelAndView mav = new ModelAndView();
		//设置模型数据
		mav.addObject("msg", "hello springmvc...");
		//设置视图名字
		mav.setViewName("/WEB-INF/jsp/hello.jsp");
		return mav;
	}
}

②创建hello.jsp页面

③创建与配置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>

④在web.xml中配置前端控制器

<!-- 配置前端控制器 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 加载springmvc核心配置文件 -->
    <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>

⑤总结

三.完成商品列表加载

①创建Item的pojo

public class Item {
	// 商品id
	private int id;
	// 商品名称
	private String name;
	// 商品价格
	private double price;
	// 商品创建时间
	private Date createtime;
	// 商品描述
	private String detail;

创建带参数的构造器
set/get。。。
}

②编写ItemController

@Controller
public class ItemController {
	
	@RequestMapping("itemList")
	public ModelAndView itemList(){
		
		ModelAndView mav = new ModelAndView();
		List<Items> itemList = new ArrayList<Items>();
		itemList.add(new Items(1, "冰箱", 1999.0, new Date(), "质量不错"));
		itemList.add(new Items(2, "冰箱2", 1999.0, new Date(), "质量不错2"));
		itemList.add(new Items(3, "冰箱3", 1999.0, new Date(), "质量不错3"));
		itemList.add(new Items(4, "冰箱4", 1999.0, new Date(), "质量不错4"));
		itemList.add(new Items(5, "冰箱5", 1999.0, new Date(), "质量不错5"));
		//设置商品数据
		mav.addObject("itemList", itemList);
		//设置视图名字
		mav.setViewName("/WEB-INF/jsp/itemList.jsp");
		return mav;
	}

}

③④同上个案例

四.SpringMVC架构

4.1 框架默认加载组件

4.1.1 处理器映射器

从spring3.1版本开始,废除了DefaultAnnotationHandlerMapping的使用,推荐使用RequestMappingHandlerMapping完成注解式处理器映射。

<!-- 配置处理器映射器 -->
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>

4.1.2 处理器适配器

从spring3.1版本开始,废除了AnnotationMethodHandlerAdapter的使用,推荐使用RequestMappingHandlerAdapter完成注解式处理器适配。

<!-- 处理器适配器 -->
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />

注意:

映射器与适配器必需配套使用,如果映射器使用了推荐的RequestMappingHandlerMapping,适配器也必需使用推荐的RequestMappingHandlerAdapter。

4.1.4 注解驱动

<!-- 注解驱动配置,代替映射器与适配器的单独配置,同时支持json响应(推荐使用) -->
	<mvc:annotation-driven />

 

4.1.5 视图解析器

<!-- 配置视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 配置视图响应的前缀 -->
		<property name="prefix" value="/WEB-INF/jsp/" />
		<!-- 配置视图响应的后缀 -->
		<property name="suffix" value=".jsp" />
	</bean>

使用:

4.2 总结-springMVC架构

五.SpringMVC与Mybatis整合

5.1 思路

Dao层:

  1. SqlMapConfig.xml,空文件即可。需要文件头。
  2. applicationContext-dao.xml。
    1. 数据库连接池
    2. SqlSessionFactory对象,需要spring和mybatis整合包下的。
    3. 配置mapper文件扫描器。

Service层:

  1. applicationContext-service.xml包扫描器,扫描@service注解的类。
  2. applicationContext-trans.xml配置事务。

Controller层:

Springmvc.xml

  1. 包扫描器,扫描@Controller注解的类。
  2. 配置注解驱动。
  3. 视图解析器

Web.xml

  1. 配置spring容量监听器
  2. 配置前端控制器

5.2 整合案例

需求:查询显示商品列表

①创建商品实体类

public class Item {
    private Integer id;

    private String name;

    private Float price;

    private String detail;

    private String pic;

    private Date createtime;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail == null ? null : detail.trim();
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic == null ? null : pic.trim();
    }

    public Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }

	@Override
	public String toString() {
		return "Item [id=" + id + ", name=" + name + ", price=" + price + ", detail=" + detail + ", pic=" + pic
				+ ", createtime=" + createtime + "]";
	}
}

②通过逆向工程生成Mapper接口及xml文件

public interface ItemMapper {
    int countByExample(ItemExample example);

    int deleteByExample(ItemExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(Item record);

    int insertSelective(Item record);

    List<Item> selectByExample(ItemExample example);

    Item selectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") Item record, @Param("example") ItemExample example);

    int updateByExample(@Param("record") Item record, @Param("example") ItemExample example);

    int updateByPrimaryKeySelective(Item record);

    int updateByPrimaryKey(Item record);
}

③创建业务层接口及实现类

public interface ItemService {

	/**
	 * 获取商品列表
	 * @return
	 */
	List<Item> getItemList();
	
	/**
	 * 跟据ID查询商品信息
	 * @param id
	 * @return
	 */
	Item getItemById(Integer id);
	
	/**
	 * 修改商品信息
	 * @param item
	 */
	void updateItem(Item item);
}
@Service
public class ItemServiceImpl implements ItemService {
	
	@Autowired
	private ItemMapper itemMapper;

	@Override
	public List<Item> getItemList() {
		return itemMapper.selectByExample(null);
	}

	@Override
	public Item getItemById(Integer id) {
		return itemMapper.selectByPrimaryKey(id);
	}

	@Override
	public void updateItem(Item item) {
		itemMapper.updateByPrimaryKeySelective(item);
	}

}

④实现Action

@Controller
public class ItemController {

	@Autowired
	private ItemService itemService;

	@RequestMapping("itemList")
	public ModelAndView itemList() {
		ModelAndView mav = new ModelAndView();

		List<Item> itemList = itemService.getItemList();

		mav.addObject("itemList", itemList);
		// mav.setViewName("/WEB-INF/jsp/itemList.jsp");
		mav.setViewName("itemList");
		return mav;
	}

}

⑤配置xml文件

applicationContext-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	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-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

   <!-- 加载配置文件 -->
   <context:property-placeholder location="classpath:jdbc.properties" />

	<!-- 数据库连接池 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<!-- 连接池的最大数据库连接数 -->
		<property name="maxActive" value="10" />
		<!-- 最大空闲数 -->
		<property name="maxIdle" value="5" />
	</bean>
	
	<!-- SqlSessionFactory配置 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 加载mybatis核心配置文件 -->
		<property name="configLocation" value="classpath:SqlMapConfig.xml" />
		<!-- 别名包扫描 -->
		<property name="typeAliasesPackage" value="com.itheima.springmvc.pojo" />
	</bean>
	
    <!-- 动态代理,第二种方式:包扫描(推荐): -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    	<!-- basePackage多个包用","分隔 -->
    	<property name="basePackage" value="com.itheima.springmvc.mapper" />
    </bean>
</beans>

applicationContext-service.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	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-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
	<!-- @Service包扫描器 -->
	<context:component-scan base-package="com.itheima.springmvc.service"/>
</beans>

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="com.itheima.springmvc.controller" />
	
	
	<!-- 配置注解驱动,相当于同时使用最新处理器映射跟处理器适配器,对json数据响应提供支持 -->
	<mvc:annotation-driven />
	
	<!-- 配置视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
</beans>

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>

六.参数绑定

6.1 默认支持的参数类型

基于完成需求:点击修改商品时,打开商品编辑页面,展示商品信息

/**
	 * 演示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 = itemServices.getItemById(new Integer(id));
		//设置商品数据返回页面
		mav.addObject("item", item);
		//设置视图名称
		mav.setViewName("itemEdit");
		return mav;
	}

6.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;
	}

6.3 Model/ModelMap

/**
	 * 演示返回String,通过Model/ModelMap返回数据模型
	 * 跳转修改商品信息页面
	 * @param id
	 * @return
	 */
	@RequestMapping("itemEdit")
	public String itemEdit(@RequestParam("id")Integer ids,Model m,ModelMap model){
		
		//查询商品信息
		Item item = itemServices.getItemById(ids);
		//通过Model把商品数据返回页面
		model.addAttribute("item", item);
		//返回String视图名字
		return "itemEdit";
	}

6.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";
	}

6.5 绑定包装的pojo

/**
	 * 演示包装pojo传递
	 * @param vo
	 * @return
	 */
	@RequestMapping("queryItem")
	public String queryItem(QueryVo vo){
		//打印传入参数
		System.out.println(vo);
		//返回视图
		return "itemList";
	}

6.6 数组类型的参数绑定

基于批量删除商品操作完成参数传递。

/**
	 * 包装pojo传递演示
	 * 第二天,演示数组参数的传递与List的传递
	 * @param vo
	 * @return
	 */
	@RequestMapping("queryItem")
	public String queryItem(QueryVo vo, Integer[] ids) {
		System.out.println(vo);
		//输出传入的数组
		if (ids != null && ids.length > 0) {
			for (Integer id : ids) {
				System.out.println("传入的商品列表分别为:" + id);
			}
		}

		return "itemList";
	}

6.7 List类型的绑定

基于批量修改商品操作完成参数传递

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值