SpringMVC

SpringMVC基础

一、入门案例

1.创建web项目

2. 导入jar包

在这里插入图片描述

3. 编辑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>SpringMVC-01</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>
  	
  	<!-- 加载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>
</web-app>

4. 创建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.lld.springmvc.controller" />
</beans>

5. 创建Controller

package com.lld.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

//注解开发(表示这是web层)
@Controller
public class HelloControll {
	
	//在地址栏上输入的地址
	@RequestMapping("hello")
	public ModelAndView hello(){
		System.out.println("hello spring....");
		ModelAndView mav = new ModelAndView();
		//设置模型数据,用于传递到jsp
		mav.addObject("msg", "hello SpringMVC...");
		//设置跳转的路径
		mav.setViewName("/WEB-INF/jsp/hello.jsp");
		return mav;
	}
}

6. 编写jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
${msg}
</body>
</html>

7. 测试

在这里插入图片描述

8. SpringMVC代码执行流程

在这里插入图片描述

二、完成商品列表加载

1. 复制刚才的项目

2. 引入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>

3. 编写model

package com.lld.springmvc.model;

import java.util.Date;

public class items {
	// 商品id
	private int id;
	// 商品名称
	private String name;
	// 商品价格
	private double price;
	// 商品创建时间
	private Date createtime;
	// 商品描述
	private String detail;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public Date getCreatetime() {
		return createtime;
	}
	public void setCreatetime(Date createtime) {
		this.createtime = createtime;
	}
	public String getDetail() {
		return detail;
	}
	public void setDetail(String detail) {
		this.detail = detail;
	}
	public items(int id, String name, double price, Date createtime, String detail) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.createtime = createtime;
		this.detail = detail;
	}
	public items() {
		super();
	}
}

4. 编写controller

package com.lld.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 com.lld.springmvc.model.items;

@Controller
public class itemsControll {

	@RequestMapping("itemsList")
	public ModelAndView itemsList(){
		
		//模拟数据
		List<items> list = Arrays.asList(new items(1, "段黑", 55, new Date(), "很黑"),
				new items(2, "曲秃", 66, new Date(), "很秃"),
				new items(3, "张渣", 35, new Date(), "很渣"),
				new items(4, "高莽夫", 45, new Date(), "很莽夫"));
		
		ModelAndView mav = new ModelAndView();
		
		//将数据转发
		mav.addObject("itemList", list);
		
		//设置跳转路径
		//mav.setViewName("/WEB-INF/jsp/itemList.jsp");
		mav.setViewName("itemList");
		
		return mav;
	}
}

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="com.lld.springmvc.controller" />
	
	<!-- 配置处理器映射器 -->
	<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> -->
	<!-- 配置处理器适配器-->
	<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->
	
	<!-- 配置注解驱动,相当于同时使用最新处理器映射跟处理器适配器,对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>

6. 测试

在这里插入图片描述

三、SpringMVC架构

1. 处理器映射器

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

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

2. 处理器适配器

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

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

3.小结

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

4. 注解驱动

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

5. 视图解析器

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

在这里插入图片描述

6. SpringMVC架构总结

在这里插入图片描述

四、SpringMVC和MyBatis整合

1. Dao层

  • 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>

  • applicationContext-dao.xml
    • 数据库连接池
    • SqlSessionFactory对象
    • 配置mapper文件扫描器
<?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.lld.springmvc.model" />
	</bean>
	
    <!-- 动态代理,第二种方式:包扫描(推荐): -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    	<!-- basePackage多个包用","分隔 -->
    	<property name="basePackage" value="com.lld.springmvc.mapper" />
    </bean>
</beans>

2. Service层

  • applicationContext-service.xml:配置包扫描(扫描@service注解的类)
<?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.lld.springmvc.service"/>
</beans>
  • applicationContext-trans.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">

	<!-- 事务管理器 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 数据源 -->
		<property name="dataSource" ref="dataSource" />
	</bean>

</beans>

3. Controller层

  • SpringMVC.xml
    • 配置包扫描器,扫描@Controller注解的类
    • 配置注解驱动
    • 视图解析器
<?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.lld.springmvc.controller" />
	
	<!-- 配置处理器映射器 -->
	<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> -->
	<!-- 配置处理器适配器-->
	<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->
	
	<!-- 配置注解驱动,相当于同时使用最新处理器映射跟处理器适配器,对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>

4. web.xml

  1. 配置spring容器监听器
  2. 配置前端控制器
<?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>SpringMVC-MyBatis</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>
  
  <!-- 配置spring -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring/applicationContext*.xml</param-value>
	</context-param>

	<!-- 使用监听器加载Spring配置文件 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!-- 解决post乱码问题 -->
	<filter>
		<filter-name>encoding</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<!-- 设置编码参是UTF8 -->
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	
	<!-- 前端控制器 -->
	<servlet>
		<servlet-name>springmvc-web</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring/springmvc.xml</param-value>
		</init-param>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc-web</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>
  
</web-app>

5. 其他

  • log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

  • jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://39.106.68.251:3306/springmvc?characterEncoding=utf-8
jdbc.username=root
jdbc.password=1

五、参数绑定

1. 默认支持参数类型

 /**
	 * 根据ID查询商品信息,跳转到编辑页面
	 * 默认支持参数传递
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	/*
	@RequestMapping("itemEdit")
	public ModelAndView itemEdit(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		String idstr = request.getParameter("id");
		
		Items items = itemService.getItemsById(new Integer(idstr));
		
		ModelAndView mav = new ModelAndView();
		
		mav.addObject("item", items);
		
		mav.setViewName("itemEdit");
		
		return mav;
	}*/

2. 绑定简单参数

/**
	 * 页面上传递的数据与入参的名称一致时,会自动匹配
	 * @param model
	 * @param id
	 * @return
	 */
	/*@RequestMapping("itemEdit")
	public String itemEdit(Model model,Integer id){
		
		Items items = itemService.getItemsById(id);
		
		model.addAttribute("item", items);
		
		return "itemEdit";
	}*/
	/**
	 * 页面上传递的数据是id,入参接受的数据是ids,这时使用@RequestParam(value="id")可以将ids和id进行匹配
	 * required=true:代表该值在传递的时候必须有
	 * defaultValue="1":代表在没有传递该值的时候,默认为1
	 * @param model
	 * @param ids
	 * @return
	 */
	@RequestMapping("itemEdit")
	public String itemEdit(Model model,@RequestParam(value="id",required=true,defaultValue="1")Integer ids){
		
		Items items = itemService.getItemsById(ids);
		
		model.addAttribute("item", items);
		
		return "itemEdit";
	}

3. 绑定model

	/**
	 * jsp页面数据与items属性一致时,会自动绑定
	 * 该方法用于更新商品
	 * 演示model参数的绑定
	 * @param items
	 * @param model
	 * @return
	 */
	
	@RequestMapping("updateItem")
	public String updateItem(Items items,Model model){
		//调用业务层更新方法,将items作为参数进行传递
		itemService.updateitems(items);
		//将更新后的商品信息返回,并显示更新成功提示
		model.addAttribute("item", items);
		model.addAttribute("msg", "商品更新完成");
		//进行页面跳转
		return "itemEdit";
	}

4. 绑定包装的model

  • jsp页面
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="submit" value="查询"/></td>
<td>商品名称<input type="text" name="items.name"></td>
<td>商品价格<input type="text" name="items.price"></td>
</tr>
</table>
  • controller
	@RequestMapping("queryItem")
	public String queryItem(QueryVo vo,Model model){
		
		if (vo.getItems() != null) {
			System.out.println(vo.getItems());
		}
		
		//进行查询
		List<Items> list = itemService.getItemsListByNameAndPrice(vo);
		
		model.addAttribute("itemList", list);
		
		return "itemList";
	}
  • QueryVo
package com.lld.springmvc.model;

public class QueryVo {

	private Items items;

	public Items getItems() {
		return items;
	}

	public void setItems(Items items) {
		this.items = items;
	}
	
}

5. 数组类型参数绑定

@RequestMapping("queryItem")
	public String queryItem(QueryVo vo,Model model, Integer[] ids){
		
		if (vo.getItems() != null) {
			System.out.println(vo.getItems());
		}
		
		if (ids != null && ids.length > 0) {
			for (Integer id : ids) {
				System.out.println(id);
			}
		}
		
		//进行查询
		//List<Items> list = itemService.getItemsListByNameAndPrice(vo);
		
		//model.addAttribute("itemList", list);
		
		return "itemList";
	}


在这里插入图片描述

6. List集合绑定

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

六、自定义类型转换器

  1. 编写类型转换器
package com.lld.springmvc.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.core.convert.converter.Converter;

/**
 * S:source:要转换的源类型
 * T:要转换的目标类型
 * @author Administrator
 *
 */

public class DateConvert implements Converter<String, Date> {

	@Override
	public Date convert(String source) {
		// TODO Auto-generated method stub
		Date result = null;
		try {
			//创建日期转换的工具类,将要日期格式传进去
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			//调用parse()方法,将源传进去,返回一个转换好的数据
			result = simpleDateFormat.parse(source);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

}

  1. 在SpringMVC.xml文件里注册
<!-- 配置注解驱动,相当于同时使用最新处理器映射跟处理器适配器,对json数据响应提供支持 -->
	<!-- 使用自定义转换器conversion-service="转换器的id" -->
	<mvc:annotation-driven conversion-service="formattingConversionServiceFactoryBean"/>
	
	<!-- 自定义转换器 -->
	<bean id="formattingConversionServiceFactoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
		<property name="converters">
			<set>
				<bean class="com.lld.springmvc.util.DateConvert" />
			</set>
		</property>
	</bean>

七、@RequestMapping注解使用

1. 配置多个请求地址

在这里插入图片描述

2. 放在类的头部,用来分目录管理

在这里插入图片描述

3. 请求方法的限定

在这里插入图片描述

七、方法的返回值

1. ModelAndView

在这里插入图片描述

2. String

  • 返回到jsp页面
    在这里插入图片描述
  • 进行页面转发
    在这里插入图片描述
  • 进行页面重定向
    在这里插入图片描述

3. Void

  • 使用request返回
    在这里插入图片描述
  • 使用response返回
    在这里插入图片描述

八、异常处理

  1. 首先实现HandlerExceptionResolver
  2. 创建自定义异常
  3. 在页面抛出
  4. 在springmvc.xml里注册
    在这里插入图片描述

九、图片上传

1.创建虚拟目录

在这里插入图片描述

2. 引入文件上传的jar包

在这里插入图片描述

3.修改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> 
	<span>
		${msg }
	</span>
	<!-- 上传图片是需要指定属性 enctype="multipart/form-data" -->
	<!-- <form id="itemForm" action="" method="post" enctype="multipart/form-data"> -->
	<form id="itemForm"	action="${pageContext.request.contextPath }/updateItem.action" method="post" enctype="multipart/form-data" >
		<input type="hidden" name="id" value="${item.id }" /> 修改商品信息:
		<table width="100%" border=1>
			<tr>
				<td>商品名称</td>
				<td><input type="text" name="name" value="${item.name }" /></td>
			</tr>
			<tr>
				<td>商品价格</td>
				<td><input type="text" name="price" value="${item.price }" /></td>
			</tr>
			<tr>
				<td>商品生产日期</td>
				<td><input type="text" name="createtime"
					value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>" /></td>
			</tr>
			<tr>
				<td>商品图片</td>
				<td>
					<c:if test="${item.pic !=null}">
						<img src="/pic/${item.pic}" width=100 height=100/>
						<br/>
					</c:if>
					<input type="file"  name="pictureFile"/> 
				</td>
			</tr>
			<tr>
				<td>商品简介</td>
				<td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea>
				</td>
			</tr>
			<tr>
				<td colspan="2" align="center"><input type="submit" value="提交" />
				</td>
			</tr>
		</table>

	</form>
</body>

</html>

4. 编写controller

在这里插入图片描述

	@RequestMapping("updateItem")
	public String updateItem(Items items,Model model,MultipartFile pictureFile) throws Exception{
		
		//获得一个随机生成的新文件名
		String newName = UUID.randomUUID().toString();
		
		//获取原文件名
		String oldName = pictureFile.getOriginalFilename();
		
		//获取上传文件的后缀
		String hz = oldName.substring(oldName.lastIndexOf("."));
		
		//创建一个File流,设置文件保存位置
		File file = new File("D:\\桌面\\pic\\"+newName+hz);
		
		//传入一个IO流,SpringMVC会自动将上传的文件保存到指定位置
		pictureFile.transferTo(file);
		
		items.setPic(newName+hz);
		
		//调用业务层更新方法,将items作为参数进行传递
		itemService.updateitems(items);
		//将更新后的商品信息返回,并显示更新成功提示
		model.addAttribute("item", items);
		model.addAttribute("msg", "商品更新完成");
		//进行页面跳转
		//return "itemEdit";
		
		//进行页面转发到action
		//return "forward:itemsList.action";
		
		//进行页面重定向
		return "redirect:itemsList.action";
	}

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="com.lld.springmvc.controller" />
	
	<!-- 配置处理器映射器 -->
	<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> -->
	<!-- 配置处理器适配器-->
	<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->
	
	<!-- 配置注解驱动,相当于同时使用最新处理器映射跟处理器适配器,对json数据响应提供支持 -->
	<!-- 使用自定义转换器conversion-service="转换器的id" -->
	<mvc:annotation-driven conversion-service="formattingConversionServiceFactoryBean"/>
	
	<!-- 自定义转换器 -->
	<bean id="formattingConversionServiceFactoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
		<property name="converters">
			<set>
				<bean class="com.lld.springmvc.util.DateConvert" />
			</set>
		</property>
	</bean>
	
	<!-- 配置视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 设置前缀 -->
		<property name="prefix" value="/WEB-INF/jsp/"/>
		<!-- 设置后缀 -->
		<property name="suffix" value=".jsp"/>
	</bean>
	
	<!-- 配置全局异常处理器 -->
	<bean class="com.lld.springmvc.exception.CustomerException"/>
	
	<!-- 配置多媒体处理器 -->
	<!-- 注意:这里id必须填写:multipartResolver -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 最大上传文件大小 -->
		<property name="maxUploadSize" value="8388608" />
	</bean>
</beans>

十、json交互

1.引入jar包

在这里插入图片描述

  • springMVC提供了两个注解来进行json的转换

2.json的返回

在这里插入图片描述

3. json的接收在这里插入图片描述

4. SpringMVC的配置(之前进行配置过)

在这里插入图片描述

十一、SpringMVC实现Restful

1. 编码

	/**
	 * RESTful风格演示
	 * 
	 * @param ids
	 * @param model
	 * @return
	 */
	//RESTful风格url上的参数通过{}点位符绑定
	//点位符参数名与方法参数名不一致时,通过@PathVariable绑定
	@RequestMapping("{id}")
	public String testRest(@PathVariable("id") Integer ids, Model model) {
		Items item = itemService.getItemsById(ids);
		model.addAttribute("item", item);
		return "itemEdit";
	}

2. 测试

在这里插入图片描述

十二、拦截器

  • 要实现HandlerInterceptor接口

1. 入门配置

  • 创建类,实现HandlerInterceptor接口
package com.lld.springmvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class MyInterceptor implements HandlerInterceptor {

	//在Controller方法执行后被执行
	//处理异常、记录日志
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		System.out.println("afterCompletion");
	}

	//在Controller方法执行后,返回ModelAndView之前被执行
	//设置或者清理页面共用参数等等
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		System.out.println("postHandle");
	}

	//在Controller方法执行前被执行
	//登录拦截、权限认证等等
	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		System.out.println("preHandle");
		//true表示放行
		//false表示不放行
		return true;
	}

}

  • 在SpringMVC中进行配置
	<!-- 自定义拦截器配置 -->
	<mvc:interceptors>
		<!-- 定义一个拦截器 -->
		<mvc:interceptor>
			<!-- path配置</**>拦截所有请求,包括二级以上目录,</*>拦截所有请求,不包括二级以上目录 -->
			<mvc:mapping path="/**"/>
			<bean class="com.lld.springmvc.interceptor.MyInterceptor" />
		</mvc:interceptor>
	</mvc:interceptors>

2.实现简易登录拦截器

  • 思路

      1. 编写user.jsp页面,页面提交到/user/login.action
      2. 密码正确,将用户名存储到session,跳转到列表页面
      3. 拦截器中获取session,获取用户名,如果为空,跳转到登录页面
    
  • login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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 }/user/login.action">
用户名:<input type="text" name="username" /><br>
密码:<input type="password" name="password" /><br>
<input type="submit">
</form>
</body>
</html>
  • userController.java
package com.lld.springmvc.controller;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping("user")
@Controller
public class userController {

	@RequestMapping("login")
	public String login(String username,String password,HttpSession session,Model model) {
		
		if (username.equals("admin") && password.equals("123")) {
			session.setAttribute("username", username);
			return "redirect:/itemsList.action";
		}else {
			return "login";
		}
	}
	
	@RequestMapping("tologin")
	public String loginUI(){
		 
		return "login";
	}	
}
  • userInterceptor.java
package com.lld.springmvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class userInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		
		//获取session,获取session中名为username的数据
		Object object2 = request.getSession().getAttribute("username");
		
		if (object2 == null) {
			//说明没有登陆,跳转到登录页面
			response.sendRedirect(request.getContextPath() + "/user/tologin.action");
		}else {
			return true;
		}
		
		return false;
	}
}
  • SpringMVC.xml
<!-- 自定义拦截器配置 -->
	<mvc:interceptors>
		<!-- 定义一个拦截器 -->
		<mvc:interceptor>
			<!-- path配置</**>拦截所有请求,包括二级以上目录,</*>拦截所有请求,不包括二级以上目录 -->
			<mvc:mapping path="/**"/>
			<bean class="com.lld.springmvc.interceptor.MyInterceptor" />
		</mvc:interceptor>
		
		<!-- 定义一个拦截器 -->
		<mvc:interceptor>
			<!-- 要拦截的部分 -->
			<mvc:mapping path="/**"/>
			<!-- 排除的拦截部分 -->
			<mvc:exclude-mapping path="/user/**"/>
			<!-- 拦截器地址 -->
			<bean class="com.lld.springmvc.interceptor.userInterceptor"/>
		</mvc:interceptor>
	</mvc:interceptors>

在这里插入图片描述

页面提交时间格式转换

页面提交上来一个String类型的数据,要往domain里的Date里面存储会出现格式不匹配的情况

  • 解决方法
    在这里插入图片描述
发布了48 篇原创文章 · 获赞 10 · 访问量 1216
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章