SpringMVC 課程第一天

SpringMVC第一天html

 

框架課程前端

 

1. 課程計劃

第一天java

一、SpringMVC介紹mysql

二、入門程序程序員

三、SpringMVC架構講解web

a) 框架結構spring

b) 組件說明sql

四、SpringMVC整合MyBatis數據庫

五、參數綁定apache

a) SpringMVC默認支持的參數類型

b) 簡單數據類型

c) Pojo類型

d) Pojo包裝類型

e) 自定義類型轉換器

六、SpringMVCStruts2的區別(瞭解)

 

次日

一、高級參數綁定

a) 數組類型的參數綁定

b) List類型的綁定

二、@RequestMapping註解的使用

三、Controller方法返回值

四、SpringMVC中異常處理

五、圖片上傳處理

六、Json數據交互

七、SpringMVC實現RESTful

8、攔截器

 

 

 

 

 

 

 

 

2. SpringMVC入門

2.1. SpringMVC是什麼?

Spring web MVCStruts2都屬於表現層的框架,它是Spring框架的一部分,咱們能夠從Spring的總體結構中看得出來

 

 

2.2. SpringMVC處理流程

 

 

2.3. 入門程序

需求:使用瀏覽器顯示商品列表

2.3.1. 建立Web工程

SpringMVC是表現層框架,須要搭建web工程開發。

新建maven工程

 

 

n 選擇工程位置

 

 

n 配置工程座標

 

 

生成web.xml文件

 

 

n 效果以下:

 

 

配置maven工程Java編譯版本

<!-- 設置編譯版本爲1.7 -->

<plugin>

   <groupId>org.apache.maven.plugins</groupId>

   <artifactId>maven-compiler-plugin</artifactId>

   <configuration>

   <source>1.7</source>

   <target>1.7</target>

   <encoding>UTF-8</encoding>

   </configuration>

</plugin>

2.3.2. 引入Jar座標

<dependencies>

<dependency>

 <groupId>org.springframework</groupId>

 <artifactId>spring-webmvc</artifactId>

 <version>4.1.3.RELEASE</version>

</dependency>

<dependency>

   <groupId>javax.servlet</groupId>

   <artifactId>servlet-api</artifactId>

   <version>2.5</version>

   <scope>provided</scope>

</dependency>

<dependency>

    <groupId>jstl</groupId>

    <artifactId>jstl</artifactId>

    <version>1.2</version>

</dependency>

</dependencies>

2.3.3. 加入配置文件

src/main/resources目錄下建立配置文件

2.3.3.1. 建立springmvc.xml

resources目錄下建立SpringMVC的核心配置文件springmvc.xmlSpringMVC自己就是Spring的一個子項目,對Spring兼容性很好,因此SpringMVCController掃描使用的就是Spring<context:component-scan/>標籤。

<?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.1.xsd

http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

<!-- 配置controller掃描包 -->

<context:component-scan

base-package="com.itheima.springmvc.controller"/>

</beans>

建立包com.itheima.springmvc.controller

 

 

 

2.3.3.2. 配置前端控制器

配置SpringMVC的前端控制器DispatcherServlet

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>springmvc01_quickstart</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>

 

<!-- 配置SpringMVC前端控制器 -->

<servlet>

<servlet-name>springmvc01-quickstart</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet

</servlet-class>

<!-- 指定SpringMVC配置文件 -->

<!-- SpringMVC的配置文件的默認路徑是/WEB-INF/${servlet-name}-servlet.xml -->

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:springmvc.xml</param-value>

</init-param>

</servlet>

 

<servlet-mapping>

<servlet-name>springmvc01-quickstart</servlet-name>

<!-- 設置全部以action結尾的請求進入SpringMVC -->

<url-pattern>*.action</url-pattern>

</servlet-mapping>

</web-app>

2.3.4. 加入Jsp頁面

把資料中的itemList.jsp複製到工程的/WEB-INF/jsp目錄下。

 

 

 

2.3.5. 實現顯示商品列表頁

2.3.5.1. 建立Pojo

分析頁面,查看頁面須要的數據

 

 

建立商品Pojo

public class Item {

// 構造器

// 商品id

private int id;

// 商品名稱

private String name;

// 商品價格

private double price;

// 商品建立時間

private Date createtime;

// 商品描述

private String detail;

 

建立帶參數的構造器

set/get。。。

}

 

2.3.5.2. 建立ItemController

ItemController是一個普通的java類,不須要實現任何接口。

須要在類上添加@Controller註解,把Controller交由Spring管理

在方法上面添加@RequestMapping註解,裏面指定請求的url。其中「.action」能夠加也能夠不加。

@Controller

public class ItemController {

 

// @RequestMapping:裏面放的是請求的url,和用戶請求的url進行匹配

// action能夠寫也能夠不寫

@RequestMapping("/itemList.action")

public ModelAndView queryItemList() {

// 建立頁面須要顯示的商品數據

List<Item> list = new ArrayList<>();

list.add(new Item(1, "1華爲 榮耀8", 2399, new Date(), "質量好!1"));

list.add(new Item(2, "2華爲 榮耀8", 2399, new Date(), "質量好!2"));

list.add(new Item(3, "3華爲 榮耀8", 2399, new Date(), "質量好!3"));

list.add(new Item(4, "4華爲 榮耀8", 2399, new Date(), "質量好!4"));

list.add(new Item(5, "5華爲 榮耀8", 2399, new Date(), "質量好!5"));

list.add(new Item(6, "6華爲 榮耀8", 2399, new Date(), "質量好!6"));

 

// 建立ModelAndView,用來存放數據和視圖

ModelAndView modelAndView = new ModelAndView();

// 設置數據到模型中

modelAndView.addObject("itemList", list);

// 設置視圖jsp,須要設置視圖的物理地址

modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");

 

return modelAndView;

}

}

2.3.6. 啓動項目測試

添加Tomcat

 

 

 

 

 

 

點擊Finish結束

n 發佈項目

 

 

 

 

點擊Finish結束後,在新建立的server上右鍵,選擇Add and Remove,以下:

 

 

把工程springmvc01_quickstart移動到右側Configured中,點擊Finish結束

 

 

選中server,而後啓動server

 

 

 

瀏覽器訪問地址

http://127.0.0.1:8080/springmvc01_quickstart/itemList.action

 

 

爲何能夠用呢?咱們須要分析一下SpringMVC的架構圖。

3. SpringMVC架構

3.1. 框架結構

 

 

3.2. 架構流程

第一步:用戶發送請求至前端控制器DispatcherServlet

第二步:DispatcherServlet收到請求調用HandlerMapping處理器映射器 HandlerMapping是map結構 key是url value是對應的controller或者說是handler

第三步:處理器映射器根據請求Url找到具體的Handler(後端控制器),生成處理器對象及處理器攔截器(若是有則生成)一併返回DispatcherServlet

第四步:DispatcherServlet調用HandlerAdapter處理器適配器去調用Handler

第五步:處理器適配器執行Handler

第六步:Handler執行完成給處理器適配器返回ModelAndView

第七步:處理器適配器向前端控制器返回 ModelAndView,ModelAndView 是SpringMVC 框架的一個底層對象,包括 Model 和 View 經過addObject("list",list) 封裝模型, 和setviewName("視圖路徑") 視圖

第八步:前端控制器請求視圖解析器去進行視圖解析

    根據邏輯視圖名來解析真正的視圖。   視圖解析器在web.xml中提早配置好前綴和後綴. 無需加上視圖的絕對路徑.  只須要相對就能夠

第九步:視圖解析器向前端控制器返回View

第十步:前端控制器進行視圖渲染

    就是將模型數據(在 ModelAndView 對象中)填充到 request 域

第十一步:前端控制器向用戶響應結果

3.3. 組件說明

DispatcherServlet:前端控制器

接收用戶請求,響應結果,至關於中央處理器,DispatcherServlet是整個流程控制的中心,由它調用其它組件完成用戶請求的處理DispatcherServlet的存在下降了組件之間的耦合性。

HandlerMapping:處理器映射器

HandlerMapping負責根據用戶請求的Url找到Handler即處理器,SpringMVC提供了不一樣的映射器來實現不一樣的映射方式,例如:實現接口方式,註解方式等

n Handler:處理器

Handler相對於前端控制器DispatcherServlet來講是後端控制器,執行具體業務處理的,它在DispatcherServlet的控制下處理用戶的具體請求

因爲Handler涉及到具體的用戶業務請求,因此通常狀況須要程序員根據業務需求開發Handler。

n HandlAdapter:處理器適配器

經過HandlerAdapter對Handler處理器進行執行這是適配器模式的應用。 不論你是啥樣是數據通通轉成modelAndView

       

 

n ViewResolver:視圖解析器

ViewResolver進行視圖解析首先根據邏輯視圖名解析成物理視圖名即具體的頁面地址,再生成View視圖對象

n View:視圖

SpringMVC框架提供了不少的View視圖類型的支持,包括:jsp、freemarkerView等。咱們最經常使用的視圖就是jsp。

通常狀況下須要經過頁面標籤或頁面模版技術將模型數據經過頁面展現給用戶,須要由程序員根據業務需求開發具體的頁面。

說明:在SpringMVC的各個組件中,處理器映射器、處理器適配器、視圖解析器稱爲SpringMVC的三大組件。

須要用戶開發的組件有handlerview

 

3.4. 框架默認加載組件

咱們沒有作任何配置,就可使用這些組件

由於框架已經默認加載這些組件了

 

 

 

# Default implementation classes for DispatcherServlet's strategy interfaces.

# Used as fallback when no matching beans are found in the DispatcherServlet context.

# Not meant to be customized by application developers.

 

org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver

 

org.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolver

 

org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\

org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping

 

org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\

org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\

org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter

 

org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver,\

org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\

org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver

 

org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator

 

org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver

 

org.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManager

 

3.5. 註解映射器和註解適配器

3.5.1. 配置註解映射器

註解式處理器映射器,對類中標記了@ResquestMapping的方法進行映射。根@ResquestMapping定義的url匹配@ResquestMapping標記的方法,匹配成功返回HandlerMethod對象給前端控制器。

HandlerMethod對象中封裝url對應的方法Method

 

Spring3.2版本開始,推薦使用RequestMappingHandlerMapping完成註解式處理器映射

 

springmvc.xml配置文件中配置以下:

<!-- 配置處理器映射器 -->

<bean

class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />

 

註解描述:

@RequestMapping:定義請求url處處理器的映射

3.5.2. 配置註解適配器

註解式處理器適配器,對標記@ResquestMapping的方法進行適配。

spring3.2版本開始,推薦使用RequestMappingHandlerAdapter完成註解式處理器適配。

 

springmvc.xml配置文件中配置以下:

<!-- 配置處理器適配器 -->

<bean

class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />

 

3.5.3. 註解驅動

直接配置處理器映射器和處理器適配器比較麻煩,可使用註解驅動來加載。

SpringMVC使用<mvc:annotation-driven>自動加載RequestMappingHandlerMapping和RequestMappingHandlerAdapter

能夠在springmvc.xml配置文件中使用<mvc:annotation-driven>替代註解處理器和適配器的配置。

<!-- 註解驅動 -->

<mvc:annotation-driven />

3.6. 視圖解析器

視圖解析器使用SpringMVC框架默認的InternalResourceViewResolver,這個視圖解析器支持JSP視圖解析

springmvc.xml配置文件中配置以下:

<!-- Example: prefix="/WEB-INF/jsp/", suffix=".jsp", viewname="test" ->

"/WEB-INF/jsp/test.jsp" -->

<!-- 配置視圖解析器 -->

<bean

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<!-- 配置邏輯視圖的前綴 -->

<property name="prefix" value="/WEB-INF/jsp/" />

<!-- 配置邏輯視圖的後綴 -->

<property name="suffix" value=".jsp" />

</bean>

邏輯視圖名須要在Controller中返回ModelAndView指定,好比邏輯視圖名爲itemList,則最終返回的jsp視圖地址:WEB-INF/jsp/itemList.jsp

最終jsp物理地址:前綴+邏輯視圖名+後綴

3.6.1. 修改ItemController

修改ItemController中設置視圖的代碼

// @RequestMapping:裏面放的是請求的url,和用戶請求的url進行匹配

// action能夠寫也能夠不寫

@RequestMapping("/itemList.action")

public ModelAndView queryItemList() {

// 建立頁面須要顯示的商品數據

List<Item> list = new ArrayList<>();

list.add(new Item(1, "1華爲 榮耀8", 2399, new Date(), "質量好!1"));

list.add(new Item(2, "2華爲 榮耀8", 2399, new Date(), "質量好!2"));

list.add(new Item(3, "3華爲 榮耀8", 2399, new Date(), "質量好!3"));

list.add(new Item(4, "4華爲 榮耀8", 2399, new Date(), "質量好!4"));

list.add(new Item(5, "5華爲 榮耀8", 2399, new Date(), "質量好!5"));

list.add(new Item(6, "6華爲 榮耀8", 2399, new Date(), "質量好!6"));

 

// 建立ModelAndView,用來存放數據和視圖

ModelAndView modelAndView = new ModelAndView();

// 設置數據到模型中

modelAndView.addObject("itemList", list);

// 設置視圖jsp,須要設置視圖的物理地址

// modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");

// 配置好視圖解析器前綴和後綴,這裏只須要設置邏輯視圖就能夠了。

// 視圖解析器根據前綴+邏輯視圖名+後綴拼接出來物理路徑

modelAndView.setViewName("itemList");

 

return modelAndView;

}

 

3.6.2. 效果

效果和以前同樣:

 

 

4. 整合MyBatis

爲了更好的學習 SpringMVC和MyBatis整合開發的方法,須要將SpringMVC和MyBatis進行整合。

整合目標:控制層採用SpringMVC、持久層使用MyBatis實現。

4.1. 建立數據庫表

Sql腳本:

 

 

 

建立數據庫springmvc,導入到數據庫中:

 

 

 

4.2. 整合引入的Jar

n Log4j日誌jar

n Mysql的數據庫驅動jar

n Mybatisjar

n Junit測試jar

n Springjar包(包括SpringMVC

n Spring+Mybatis的整合包

數據庫鏈接池jar

4.3. 整合思路

Dao層:

一、SqlMapConfig.xml(和Spring整合以後SqlMapConfig.xml不是必需的)

二、applicationContext-dao.xml

a) 數據庫鏈接池

b) SqlSessionFactory對象,須要springmybatis整合包下的。

c) 配置mapper文件掃描器。

 

Service層:

一、applicationContext-service.xml包掃描器,掃描添加了@service註解的類。

二、applicationContext-trans.xml配置事務。

 

Controller層:

一、Springmvc.xml

a) 包掃描器,掃描添加了@Controller註解的類。

b) 配置註解驅動

c) 配置視圖解析器

 

Web.xml文件:

一、配置spring

二、配置SpringMVC前端控制器。

4.4. 建立工程

新建maven工程,打包方式爲war

 

 

 

 

配置Maven工程Java編譯版本

<!-- 設置編譯版本爲1.7 -->

<plugin>

   <groupId>org.apache.maven.plugins</groupId>

   <artifactId>maven-compiler-plugin</artifactId>

   <configuration>

   <source>1.7</source>

   <target>1.7</target>

   <encoding>UTF-8</encoding>

   </configuration>

</plugin>

4.5. 引入Jar座標

<properties>

<junit.version>4.12</junit.version>

<log4j.version>1.2.17</log4j.version>

<mysql.version>5.1.46</mysql.version>

<mybatis.version>3.2.7</mybatis.version>

    <dbcp.version>1.4</dbcp.version>

<mybatis.spring.version>1.2.2</mybatis.spring.version>

<spring.version>4.1.3.RELEASE</spring.version>

<jstl.version>1.2</jstl.version>

<aspectjweaver.version>1.6.8_2</aspectjweaver.version>

</properties>

 

<dependencies>

<!-- junit測試包 -->

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>${junit.version}</version>

<scope>test</scope>

</dependency>

<!-- log4j日誌包 -->

<dependency>

<groupId>log4j</groupId>

<artifactId>log4j</artifactId>

<version>${log4j.version}</version>

</dependency>

 

<!--mysql依賴包 -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>${mysql.version}</version>

</dependency>

<!--mybatis依賴包 -->

<dependency>

<groupId>org.mybatis</groupId>

<artifactId>mybatis</artifactId>

<version>${mybatis.version}</version>

</dependency>

<!--Mybatis+Spring整合 -->

<dependency>

<groupId>org.mybatis</groupId>

<artifactId>mybatis-spring</artifactId>

<version>${mybatis.spring.version}</version>

</dependency>

 

<!-- 數據庫鏈接池 -->

<dependency>

<groupId>commons-dbcp</groupId>

<artifactId>commons-dbcp</artifactId>

<version>${dbcp.version}</version>

</dependency>

 

<!-- Spring:依賴注入IoC與DI的最基本實現 -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-core</artifactId>

<version>${spring.version}</version>

</dependency>

<!-- Spring:Bean工廠與bean的裝配 -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-beans</artifactId>

<version>${spring.version}</version>

</dependency>

<!-- Spring:spring的context上下文即IoC容器 -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>${spring.version}</version>

</dependency>

 

<!-- Spring:jdbc的支持 -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-jdbc</artifactId>

<version>${spring.version}</version>

</dependency>

<!-- Spring:test的支持 -->

<dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-test</artifactId>

<version>${spring.version}</version>

    <scope>test</scope>

</dependency>

 

<dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-webmvc</artifactId>

    <version>${spring.version}</version>

</dependency>

<dependency>

    <groupId>jstl</groupId>

    <artifactId>jstl</artifactId>

    <version>${jstl.version}</version>

</dependency>

<dependency>  

   <groupId>org.apache.geronimo.bundles</groupId>  

   <artifactId>aspectjweaver</artifactId>  

   <version>${aspectjweaver.version}</version>  

</dependency>  

</dependencies>

4.6. 加入配置文件

src/main/resources文件夾下添加配置文件

4.6.1. log4j.properties

src/main/resources下建立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

4.6.2. SqlMapConfig.xml(非必需,此處略)

4.6.3. applicationContext-dao.xml

src/main/resources文件夾下新建spring文件夾,並在spring文件夾下建立

applicationContext-dao.xml文件配置數據源、配置SqlSessionFactorymapper掃描器

<?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.1.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">

 

<!-- 加載配置文件 -->

<context:property-placeholder location="classpath:db.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" />

<property name="typeAliasesPackage" value="com.itheima.ssm.pojo" />

</bean>

 

<!-- 配置Mapper掃描 -->

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

<!-- 配置Mapper掃描包 -->

<property name="basePackage" value="com.itheima.ssm.mapper" />

</bean>

 

</beans>

 

4.6.4. db.properties

src/main/resources目錄下建立db.properties文件,配置數據庫鏈接信息

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://127.0.0.1:3306/springmvc?characterEncoding=utf-8

jdbc.username=root

jdbc.password=root

 

4.6.5. applicationContext-service.xml

spring文件夾下建立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.1.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">

 

<!-- 配置service掃描 -->

<context:component-scan base-package="com.itheima.ssm.service" />

 

</beans>

 

4.6.6. applicationContext-trans.xml

spring文件夾下建立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.1.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">

 

<!-- 事務管理器 -->

<bean id="transactionManager"

class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<!-- 數據源 -->

<property name="dataSource" ref="dataSource" />

</bean>

<!-- 事務註解驅動 -->

<tx:annotation-driven transaction-manager="transactionManager"/>  

</beans>

4.6.7. springmvc.xml

spring文件夾下建立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.1.xsd

        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd

        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

 

<!-- 配置controller掃描包 -->

<context:component-scan base-package="com.itheima.ssm.controller" />

 

<!-- 註解驅動 -->

<mvc:annotation-driven />

 

<!-- Example: prefix="/WEB-INF/jsp/", suffix=".jsp", viewname="test" ->

"/WEB-INF/jsp/test.jsp" -->

<bean

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<!-- 配置邏輯視圖的前綴 -->

<property name="prefix" value="/WEB-INF/jsp/" />

<!-- 配置邏輯視圖的後綴 -->

<property name="suffix" value=".jsp" />

</bean>

 

</beans>

 

4.6.8. 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>springmvc01_ssm</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>

<!-- 配置SrpingMVC的前端控制器 -->

<servlet>

<servlet-name>springmvc01_ssm</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>springmvc01_ssm</servlet-name>

<!-- 配置全部以action結尾的請求進入SpringMVC -->

<url-pattern>*.action</url-pattern>

</servlet-mapping>

</web-app>

5. 實現商品列表顯示

5.1. 需求

實現商品查詢列表,從mysql數據庫查詢全部商品信息。

5.2. 加入Jsp頁面

複製資料的itemList.jspitemEdit.jsp到工程中

 

 

5.3. Dao層開發

使用逆向工程,生成代碼

注意修改逆向工程的配置文件,參考MyBatis次日

 

 

5.4. ItemService接口

public interface ItemService {

 

/**

 * 查詢商品列表

 *

 * @return

 */

List<Item> queryItemList();

 

}

 

5.5. ItemServiceImpl實現類

@Service

public class ItemServiceImpl implements ItemService {

 

@Autowired

private ItemMapper itemMapper;

 

@Override

public List<Item> queryItemList() {

// 從數據庫查詢商品數據

List<Item> list = this.itemMapper.selectByExample(null);

 

return list;

}

}

 

5.6. ItemController

@Controller

public class ItemController {

 

@Autowired

private ItemService itemService;

 

/**

 * 顯示商品列表

 *

 * @return

 */

@RequestMapping("/itemList")

public ModelAndView queryItemList() {

// 獲取商品數據

List<Item> list = this.itemService.queryItemList();

 

ModelAndView modelAndView = new ModelAndView();

// 把商品數據放到模型中

modelAndView.addObject("itemList", list);

// 設置邏輯視圖

modelAndView.setViewName("itemList");

 

return modelAndView;

}

 

}

 

5.7. 測試

 

 

訪問urlhttp://127.0.0.1:8080/springmvc01_ssm/itemList.action

 

 

5.8. Model/ModelMap

5.8.1. Model

除了ModelAndView之外,還可使用Model來向頁面傳遞數據,Model是一個接口,在參數裏直接聲明model便可

 

若是使用Model則能夠不使用ModelAndView對象,Model對象能夠向頁面傳遞數據,View對象則可使用String返回值替代。

不論是Model仍是ModelAndView,其本質都是使用Request對象向jsp傳遞數據

代碼實現:

/**

 * 根據id查詢商品,使用Model

 *

 * @param request

 * @param model

 * @return

 */

@RequestMapping("/itemEdit")

public String queryItemById(HttpServletRequest request, Model model) {

// 從request中獲取請求參數

String strId = request.getParameter("id");

Integer id = Integer.valueOf(strId);

 

// 根據id查詢商品數據

Item item = this.itemService.queryItemById(id);

 

// 把結果傳遞給頁面

// ModelAndView modelAndView = new ModelAndView();

// 把商品數據放在模型中

// modelAndView.addObject("item", item);

// 設置邏輯視圖

// modelAndView.setViewName("itemEdit");

 

// 把商品數據放在模型中

model.addAttribute("item", item);

 

return "itemEdit";

}

 

5.8.2. ModelMap

ModelMapModel接口的實現類,也能夠經過ModelMap向頁面傳遞數據

 

使用ModelModelMap的效果同樣,若是直接使用ModelSpringMVC會實例化ModelMap

 

代碼實現:

/**

 * 根據id查詢商品,使用ModelMap

 *

 * @param request

 * @param model

 * @return

 */

@RequestMapping("/itemEdit")

public String queryItemById(HttpServletRequest request, ModelMap model) {

// 從request中獲取請求參數

String strId = request.getParameter("id");

Integer id = Integer.valueOf(strId);

 

// 根據id查詢商品數據

Item item = this.itemService.queryItemById(id);

 

// 把結果傳遞給頁面

// ModelAndView modelAndView = new ModelAndView();

// 把商品數據放在模型中

// modelAndView.addObject("item", item);

// 設置邏輯視圖

// modelAndView.setViewName("itemEdit");

 

// 把商品數據放在模型中

model.addAttribute("item", item);

 

return "itemEdit";

}

6. 參數綁定

6.1. 默認支持的參數類型

6.1.1. 需求

打開商品編輯頁面,展現商品信息。

6.1.2. 需求分析

編輯商品信息,首先要顯示商品詳情

須要根據商品id查詢商品信息,而後展現到頁面。

請求的url/itemEdit.action

參數:id(商品id

響應結果:商品編輯頁面,展現商品詳細信息。

6.1.3. ItemService接口

 

 

 

6.1.4. ItemServiceImpl實現類

@Override

public Item queryItemById(int id) {

Item item = this.itemMapper.selectByPrimaryKey(id);

 

return item;

}

6.1.5. ItemController

頁面點擊修改按鈕,發起請求

http://127.0.0.1:8080/springmvc-web/itemEdit.action?id=1

須要從請求的參數中把請求的id取出來。

Id包含在Request對象中。能夠從Request對象中取id

 

想得到Request對象只須要在Controller方法的形參中添加一個參數便可。Springmvc框架會自動把Request對象傳遞給方法。

 

代碼實現

/**

 * 根據id查詢商品

 *

 * @param request

 * @return

 */

@RequestMapping("/itemEdit")

public ModelAndView queryItemById(HttpServletRequest request) {

// 從request中獲取請求參數

String strId = request.getParameter("id");

Integer id = Integer.valueOf(strId);

 

// 根據id查詢商品數據

Item item = this.itemService.queryItemById(id);

 

// 把結果傳遞給頁面

ModelAndView modelAndView = new ModelAndView();

// 把商品數據放在模型中

modelAndView.addObject("item", item);

// 設置邏輯視圖

modelAndView.setViewName("itemEdit");

 

return modelAndView;

}

 

6.1.6. 默認支持的參數類型

處理器形參中添加以下類型的參數處理適配器會默認識別並進行賦值。

6.1.6.1. HttpServletRequest

經過request對象獲取請求信息

6.1.6.2. HttpServletResponse

經過response處理響應信息

6.1.6.3. HttpSession

經過session對象獲得session中存放的對象

6.2. 綁定簡單類型

請求的參數名稱和處理器形參名稱一致時會將請求參數與形參進行綁定。

這樣,從Request取參數的方法就能夠進一步簡化

/**

 * 根據id查詢商品,綁定簡單數據類型

 *

 * @param id

 * @param model

 * @return

 */

@RequestMapping("/itemEdit")

public String queryItemById(int id, ModelMap model) {

// 根據id查詢商品數據

Item item = this.itemService.queryItemById(id);

 

// 把商品數據放在模型中

model.addAttribute("item", item);

 

return "itemEdit";

}

 

6.2.1. 支持的數據類型

參數類型推薦使用包裝數據類型,由於基礎數據類型不能夠爲null

整型:Integer、int

字符串:String

單精度:Float、float

雙精度:Double、double

布爾型:Boolean、boolean

說明:對於布爾類型的參數,請求的參數值爲truefalse。或者10

請求url:

http://127.0.0.1:8080/xxx.action?id=2&status=false

 

處理器方法:

public String editItem(Model model,Integer id,Boolean status)

6.2.2. @RequestParam

使用@RequestParam經常使用於處理簡單類型的綁定

value:實際請求的參數名字,如value=「itemId」表示把請求中的參數itemId取出來賦值給形參

required:是否必須,默認是true,表示請求中必定要有相應的參數,不然將報錯

TTP Status 400 - Required Integer parameter 'XXXX' is not present,通常狀況下,既然使用了@RequestParam註解,那就保持required爲true

defaultValue:默認值,表示請求中沒有同名參數時的默認值,當定義了defaultValue時,requiredtrue仍是false無所謂了,由於都會有值且不會報400錯誤  通常分頁的時候 page當前頁須要默認值爲1

定義以下:

@RequestMapping("/itemEdit")

public String queryItemById(@RequestParam(value = "itemId", required = true, defaultValue = "1") Integer id,

ModelMap modelMap) {

// 根據id查詢商品數據

Item item = this.itemService.queryItemById(id);

 

// 把商品數據放在模型中

modelMap.addAttribute("item", item);

 

return "itemEdit";

}

6.3. 綁定Pojo類型

6.3.1. 需求

將頁面修改後的商品信息保存到數據庫中。

6.3.2. 需求分析

請求的url/updateItem.action

參數:表單中的數據。

響應內容:更新成功頁面

 

6.3.3. 使用pojo接收表單數據

若是提交的參數不少,或者提交的表單中的內容不少的時候,可使用簡單類型接受數據,也可使用pojo接收數據。

要求:pojo對象中的屬性名和表單中input的name屬性一致

 

頁面定義以下:

 

 

Pojo(逆向工程已生成):

 

 

請求的參數名稱和pojo的屬性名稱一致,會自動將請求參數賦值給pojo的屬性。

 

6.3.4. ItemService接口

ItemService裏編寫接口方法

/**

 * 根據id更新商品

 *

 * @param item

 */

void updateItemById(Item item);

 

6.3.5. ItemServiceImpl實現類

ItemServiceImpl實現接口方法

使用updateByPrimaryKeySelective(item)方法,忽略空參數

@Override

public void updateItemById(Item item) {

this.itemMapper.updateByPrimaryKeySelective(item);

}

6.3.6. ItemController

/**

 * 更新商品,綁定pojo類型

 *

 * @param item

 * @param model

 * @return

 */

@RequestMapping("/updateItem")

public String updateItem(Item item) {

// 調用服務更新商品

this.itemService.updateItemById(item);

 

// 返回邏輯視圖

return "success";

}

注意:

提交的表單中不要有日期類型的數據,不然會報400錯誤。若是想提交日期類型的數據須要用到後面的自定義參數綁定的內容。

 

6.3.7. 編寫success頁面

WEB-INF/jsp下建立success.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>Insert title here</title>

</head>

<body>

 

<h1>商品修改爲功!</h1>

 

</body>

</html>

 

6.3.8. 解決post亂碼問題

提交發現,保存成功,可是保存的是亂碼

web.xml中加入:

<!-- 解決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>

以上能夠解決post請求亂碼問題。

 

對於get請求中文參數出現亂碼解決方法有兩個:

修改tomcat配置文件添加編碼與工程編碼一致,以下:

<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

 

另一種方法對參數進行從新編碼:

String userName

= new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")

ISO8859-1tomcat默認編碼,須要將tomcat編碼後的內容按utf-8編碼

6.4. 綁定Pojo包裝對象

6.4.1. 需求

使用Pojo包裝對象接收商品信息的查詢條件。

6.4.2. 需求分析

包裝對象定義以下:

public class QueryVo {

private Item item;

set/get。。。

}

 

頁面定義:

 

 

6.4.3. 接收查詢條件

// 綁定包裝數據類型

@RequestMapping("/queryItem")

public String queryItem(QueryVo queryVo) {

System.out.println(queryVo.getItem().getId());

System.out.println(queryVo.getItem().getName());

 

return "success";

}

6.5. 自定義類型轉換器

6.5.1. 需求

在商品修改頁面能夠修改商品的生產日期,而且根據業務需求自定義日期格式。

6.5.2. 需求分析

因爲日期數據有不少種格式,SpringMVC沒辦法把字符串轉換成日期類型。因此在綁定日期類型時須要作類型轉換。

 

前端控制器接收到請求後,找到註解形式的處理器適配器,對RequestMapping標記的方法進行適配,並對方法中的形參進行參數綁定。能夠在SpringMVC處理器適配器上自定義Converter(類型轉換器)進行類型轉換。

 

通常使用<mvc:annotation-driven/>註解驅動加載處理器適配器,能夠在此標籤上進行配置。

 

6.5.3. 修改jsp頁面

修改itemEdit.jsp頁面,顯示時間

 

 

 

6.5.4. 自定義Converter

//Converter<S, T>

//S:source,須要轉換的源的類型

//T:target,須要轉換的目標類型

public class DateConverter implements Converter<String, Date> {

 

@Override

public Date convert(String source) {

try {

// 把字符串轉換爲日期類型

SimpleDateFormat simpleDateFormat 

= new SimpleDateFormat("yyy-MM-dd HH:mm:ss");

Date date = simpleDateFormat.parse(source);

 

return date;

} catch (ParseException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

// 若是轉換異常則返回空

return null;

}

}

 

6.5.5. 配置Converter

<!-- 配置註解驅動 -->

<mvc:annotation-driven conversion-service="conversionService" />

 

<!-- 轉換器配置 -->

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">

<property name="converters">

<set>

<bean class="com.itheima.ssm.converter.DateConverter"/>

</set>

</property>

</bean>

 

6.5.6. 配置方式2(瞭解)

<!-- 配置處理器映射器 -->

<bean

class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />

 

<!--註解適配器 -->

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">

<property name="webBindingInitializer" ref="customBinder">

</property>

</bean>

 

<!-- 自定義webBinder -->

<bean id="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">

<property name="conversionService" ref="conversionService" />

</bean>

 

<!-- 轉換器配置 -->

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">

<property name="converters">

<set>

<bean class="com.itheima.ssm.converter.DateConverter"/>

</set>

</property>

</bean>

注意:此方法須要獨立配置處理器映射器、適配器,

再也不使用<mvc:annotation-driven/>

7. SpringMVCStruts2的區別(瞭解)

一、 SpringMVC的入口是一個Servlet即前端控制器,而Struts2入口是一個Filter過濾器。

二、 SpringMVC直接將請求參數傳遞給方法的形參,能夠設計爲單例或多例(建議單例)Struts2經過類的屬性(成員變量)傳參,有線程安全問題,只能設計爲多例。

三、 Struts2採用值棧存儲請求和響應的數據;SpringMVCRequest請求內容解析,給方法形參賦值,將數據和視圖封裝成ModelAndView對象,最後又將ModelAndView中的模型數據經過Request域傳輸到頁面。

相關文章
相關標籤/搜索