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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章