SpringMVC框架筆記01_SpringMVC的使用案例和架構(gòu)組件_SpringMVC和Mybatis整合_接收參數(shù)

第1章:SpringMVC簡介

1.1 什么是SpringMVC

  • SpringMVC和Struts2都屬于表現(xiàn)層的框架,它是Spring框架的一個組件。

1.2 SpringMVC的處理流程

SpringMVC的處理流程

第2章:SpringMVC入門程序

2.1 場景描述

  • 在瀏覽器地址欄中輸入list.action 跳轉(zhuǎn)到一個商品列表的頁面。

2.2 步驟分析

  1. 創(chuàng)建web工程
  2. 添加jar:springMVC、spring、junit
  3. web.xml中添加一個DispatcherServlet[前端控制器]。
  4. DispatcherServlet需要初始化一個springMVC容器,所以需要添加springmvc.xml
  5. 創(chuàng)建一個商品pojo
  6. 創(chuàng)建一個jsp頁面
  7. 創(chuàng)建一個商品的Controller
    傳統(tǒng)方式:實現(xiàn)一個Controller接口
    注解方式:添加一個@Controller標(biāo)簽
  8. 把Controller配置到springmvc.xml中(傳統(tǒng)方式)
    開啟包掃描(注解方式)
  9. tomcat測試

2.3 步驟一:創(chuàng)建Web項目

2.4 步驟二:導(dǎo)入jar包

相關(guān)jar包

2.5 步驟三:在web.xml中配置DispatcherServlet前端控制器

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 
        從源碼中可以看到前端控制器DispatcherServlet默認(rèn)會加載/WEB-INF/{servlet-name}-servlet.xml 
        配置文件,如果需要修改這個路徑需要配置以下參數(shù)
    -->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <!-- /* : 過濾所有請求,包含jsp -->
    <!-- /  : 過濾所有請求,不包含jsp  -->
    <!-- *.action : 過濾以.action結(jié)尾的請求 -->
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>

2.6 步驟四:創(chuàng)建springmvc.xml配置文件

  • 在工程下新建一個Source Folder文件夾,在此新建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.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
            
</beans>

2.7 步驟五:新建一個商品POJO

  • package com.itzhouq.springmvc.pojo
public class Items {
    private Integer id;
    private String name;
    private Float price;
    private String pic;
    private Date createtime;
    private String detail;
    //set/get方法
}

2.8 步驟六:創(chuàng)建一個jsp頁面

  • /SpringMVC_01/WebContent/jsp/itemList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>查詢商品列表</title>
</head>
<body> 
<form action="${pageContext.request.contextPath }/item/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>生產(chǎn)日期</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>

2.9 步驟七:創(chuàng)建商品的Controller

2.9.1 傳統(tǒng)方式:實現(xiàn)一個Controller接口

  • com.itzhouq.springmvc.controller.ItemsController
package com.itzhouq.springmvc.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.itzhouq.springmvc.pojo.Items;

public class ItemsController implements Controller {

    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
//      模擬商品數(shù)據(jù)
        List<Items> list =new ArrayList<Items>();
        
        for (int i = 0; i < 10; i++) {
            Items items = new Items();
            items.setId(i);
            items.setCreatetime(new Date());
            items.setName("小米手機"+i);
            items.setDetail("國產(chǎn)");
            items.setPrice((float) (1000*i));
            list.add(items);
        }
        
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList",list); // 相當(dāng)于把數(shù)據(jù)放入了request域中
        
        // ViewName邏輯視圖:就是jsp路徑
        modelAndView.setViewName("/jsp/itemList.jsp");
        
        return modelAndView;
    }
}

2.9.2 注解方式:添加一個@Controller注解

  • 傳統(tǒng)開發(fā)方式,Controller類中只能有一個方法。這顯然不符合實際開發(fā)的需要。所以實際開發(fā)采用注解方式。
  • com.itzhouq.springmvc.controller.ItemsController2
package com.itzhouq.springmvc.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

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

import com.itzhouq.springmvc.pojo.Items;

@Controller
public class ItemsController2{
    
    @RequestMapping("/list")
    public ModelAndView list(HttpServletRequest request, HttpServletResponse response) throws Exception {
//      模擬商品數(shù)據(jù)
        List<Items> list =new ArrayList<Items>();
        
        for (int i = 0; i < 10; i++) {
            Items items = new Items();
            items.setId(i);
            items.setCreatetime(new Date());
            items.setName("華為手機"+i);
            items.setDetail("也是國產(chǎn)");
            items.setPrice((float) (1000*i));
            list.add(items);
        }
        
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList",list); // 相當(dāng)于把數(shù)據(jù)放入了request域中
        
        // ViewName邏輯視圖:就是jsp路徑
        modelAndView.setViewName("/jsp/itemList.jsp");
        
        return modelAndView;
    }
}

2.10 把Controller配置到springmvc.xml

2.10.1 傳統(tǒng)方式:實現(xiàn)一個Controller接口的方式的配置

  • springmvc.xml中添加以下配置
 <bean name="/list.action" class="com.itzhouq.springmvc.controller.ItemsController">
    
</bean> 
傳統(tǒng)方式的效果
  • 流程描述:當(dāng)在瀏覽器中輸入http://localhost/SpringMVC_01/list.action的時候,請求會首先經(jīng)過入口web.xml。該文件中有一個前端控制器DispatcherServlet,里面有配置<url-pattern>*.action</url-pattern>。請求符合*.action,所以請求會進入前端控制器中。前端控制器會初始化一個springMVC容器。根據(jù)springMVC容器的配置文件spring.xml的配置。
<bean name="/list.action" class="com.itzhouq.springmvc.controller.ItemsController">

</bean>
  • 可以看到請求list.actionname的值相同,所以請求進入到對應(yīng)的類ItemsController。執(zhí)行類中的方法,跳轉(zhuǎn)到類中寫明的jsp頁面。

2.10.2 注解方式:添加一個@Controller注解

  • 要使用注解開發(fā),必須在springmvc.xml中開啟注解掃描器。無需配置<bean>
<!-- 開啟注解掃描器 -->
     <context:component-scan base-package="com.itzhouq.springmvc.controller">
     
     </context:component-scan>
注解方式的效果
  • 注解方式的優(yōu)勢:可以使用注解@RequestMapping("/list")定位ItemsController類中的不同方法,解決傳統(tǒng)開發(fā)方式的問題。

第3章:SpringMVC的完整架構(gòu)

3.1 框架結(jié)構(gòu)

框架結(jié)構(gòu)

3.2 架構(gòu)流程

  • 流程圖
流程圖
  • 流程描述
1、 用戶發(fā)送請求至前端控制器DispatcherServlet

2、 DispatcherServlet收到請求調(diào)用HandlerMapping處理器映射器。

3、 處理器映射器根據(jù)請求url找到具體的處理器,生成處理器對象及處理器攔截器
    (如果有則生成)一并返回給DispatcherServlet。

4、 DispatcherServlet通過HandlerAdapter處理器適配器調(diào)用處理器

5、 執(zhí)行處理器(Controller,也叫后端控制器)。

6、 Controller執(zhí)行完成返回ModelAndView

7、 HandlerAdapter將controller執(zhí)行結(jié)果ModelAndView返回給DispatcherServlet

8、 DispatcherServlet將ModelAndView傳給ViewReslover視圖解析器

9、 ViewReslover解析后返回具體View

10、 DispatcherServlet對View進行渲染視圖(即將模型數(shù)據(jù)填充至視圖中)。

11、 DispatcherServlet響應(yīng)用戶

3.3 組件說明

組件源碼
  • DispatcherServlet:前端控制器

    用戶請求到達(dá)前端控制器,它就相當(dāng)于mvc模式中的c,dispatcherServlet是整個流程控制的中心,由它調(diào)用其它組件處理用戶的請求,dispatcherServlet的存在降低了組件之間的耦合性。dispatcherServlet有三大組件。

  1. HandlerMapping:處理器映射器

    HandlerMapping負(fù)責(zé)根據(jù)用戶請求找到Handler即處理器,springmvc提供了不同的映射器實現(xiàn)不同的映射方式,例如:配置文件方式,實現(xiàn)接口方式,注解方式等。

    Handler:處理器

    Handler是繼DispatcherServlet前端控制器的后端控制器,在DispatcherServlet的控制下Handler對具體的用戶請求進行處理。由于Handler涉及到具體的用戶業(yè)務(wù)請求,所以一般情況需要程序員根據(jù)業(yè)務(wù)需求開發(fā)Handler

處理器映射器
  • 配置注解開發(fā)方式新版本的處理器映射器的方式:在springmvc.xml文件中
<!--    配置最注解開發(fā)方式新版本的處理器映射器 -->
 <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
</bean>
  1. HandlAdapter`:處理器適配器

通過HandlerAdapter對處理器進行執(zhí)行,這是適配器模式的應(yīng)用,通過擴展適配器可以對更多類型的處理器進行執(zhí)行。

處理器適配器
  • 配置最注解開發(fā)方式新版本的處理器適配器方式:在springmvc.xml文件中
<!--配置最注解開發(fā)方式新版本的處理器適配器 -->
 <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
</bean>
  • 配置最注解開發(fā)方式新版本的處理器映射器和處理器適配器的方式可以簡化:
<!--    配置最注解開發(fā)方式新版本的處理器映射器 
 <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
     配置最注解開發(fā)方式新版本的處理器適配器 
 <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
 -->
<!--  注解驅(qū)動 目的:加載新版本的處理器映射器、處理器適配器-->
 <mvc:annotation-driven/>
  1. View Resolver:視圖解析器

    View Resolver負(fù)責(zé)將處理結(jié)果生成View視圖,View Resolver首先根據(jù)邏輯視圖名解析成物理視圖名即具體的頁面地址,再生成View視圖對象,最后對View進行渲染將處理結(jié)果通過頁面展示給用戶。

    View:視圖

    springmvc框架提供了很多的View視圖類型的支持,包括:jstlViewfreemarkerView、pdfView等。我們最常用的視圖就是jsp。一般情況下需要通過頁面標(biāo)簽或頁面模版技術(shù)將模型數(shù)據(jù)通過頁面展示給用戶,需要由程序員根據(jù)業(yè)務(wù)需求開發(fā)具體的頁面。

    • springmvc.xml文件配置如下:
    <!--  配置視圖解析器的前綴和后綴 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    

第4章:SpringMVC和Mybatis整合

  • 需求分析:整合SpringMVCMybatis,展示商品的列表。

4.1 整合的思路

  • Dao層:
    • sqlMapConfig.xml:可以為空,可以不需要
    • applicationContext-dao.xml
      1. 數(shù)據(jù)庫連接池
      2. SqlSessionFactory對象,需要在Springmybatis整合包下的。
      3. 配置mapper文件掃描器,用來生成代理對象。
  • Service層:
    • application-service.xml:事務(wù)管理、包掃描器【掃描@Service注解】
  • 表現(xiàn)層:
    • 包掃描器,掃描@Controller注解的類
    • 配置注解驅(qū)動
    • 視圖解析器:前綴和后綴
  • web.xml
    • 前端控制器
    • 監(jiān)聽器
    • 亂碼問題解決

4.2 整合的步驟

  1. 創(chuàng)建數(shù)據(jù)庫
  2. 創(chuàng)建web工程
  3. 添加jar包:mybatis、mybatis擴展包、spring、springmybatis整合包、junit、springmvc。
  4. 添加配置文件:
    • applicationContext-dao.xml
    • applicationContext-service.xml
    • jdbc.properties
    • log4j.properties
    • springmvc.xml
  5. 持久層開發(fā)
  6. 業(yè)務(wù)層開發(fā):接口+實現(xiàn)類
  7. 表現(xiàn)層開發(fā):注解開發(fā)方式

4.3 開始整合

4.3.1 創(chuàng)建數(shù)據(jù)庫和表

  • 新建數(shù)據(jù)庫springmvc,新建查詢springmvc.sql。
SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for items
-- ----------------------------
DROP TABLE IF EXISTS `items`;
CREATE TABLE `items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL COMMENT '商品名稱',
  `price` float(10,1) NOT NULL COMMENT '商品定價',
  `detail` text COMMENT '商品描述',
  `pic` varchar(64) DEFAULT NULL COMMENT '商品圖片',
  `createtime` datetime  NOT NULL COMMENT '生產(chǎn)日期',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of items
-- ----------------------------
INSERT INTO `items` VALUES ('1', '臺式機', '3000.0', '該電腦質(zhì)量非常好!?。。?, null, '2016-02-03 13:22:53');
INSERT INTO `items` VALUES ('2', '筆記本', '6000.0', '筆記本性能好,質(zhì)量好?。。。?!', null, '2015-02-09 13:22:57');
INSERT INTO `items` VALUES ('3', '背包', '200.0', '名牌背包,容量大質(zhì)量好!?。?!', null, '2015-02-06 13:23:02');

4.3.2 創(chuàng)建工程

  • 創(chuàng)建工程,導(dǎo)入jar包。
工程目錄
整合的jar包

4.3.3 配置文件

  • web.xml:加載applicationContext-*.xml的監(jiān)聽器和解決亂碼問題的監(jiān)聽器以及前端控制器
<?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>
  
  <!-- 過濾器:解決post方式請求的亂碼問題 -->
  <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  
<!--   前端控制器 -->
 <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:springmvc.xml</param-value>
  </init-param>
 </servlet>
 <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>*.action</url-pattern>
 </servlet-mapping>
  
<!--   監(jiān)聽器 -->
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:applicationContext-*.xml</param-value>
 </context-param>
  
</web-app>
  • applicationContext-dao.xml:加載數(shù)據(jù)庫配置文件,將映射文件交給Spring容器管理,配置映射器掃描器
<?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" />
    <!-- 數(shù)據(jù)庫連接池 -->
    <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>
    <!-- mapper配置 -->
    <!-- 讓spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 數(shù)據(jù)庫連接池 -->
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.itzhouq.ssm.pojo"></property>
    </bean>

<!-- mapper掃描器 :用來產(chǎn)生代理對象-->
     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="basePackage" value="com.itzhouq.ssm.mapper"></property>
     </bean>
</beans>
  • applicationContext-service.xml:配置事務(wù)管理和使用注解需要的包掃描器
<?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:component-scan base-package="com.itzhouq.ssm.service"/>
    
    <!-- 聲明式的事務(wù)管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 數(shù)據(jù)源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 傳播行為 -->
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>
    <!-- 切面 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice"
            pointcut="execution(* com.itzhouq.ssm.service.impl.*.*(..))" />
    </aop:config
</beans>
  • springmvc.xml:配置注解需要的包掃描器、注解驅(qū)動、視圖解析器的前綴和后綴
<?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.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
  
  <context:component-scan base-package="com.itzhouq.ssm.controller">
  
  </context:component-scan>
<!--  注解驅(qū)動 目的:加載新版本的處理器映射器、處理器適配器-->
 <mvc:annotation-driven/>
 
<!--  配置視圖解析器的前綴和后綴 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="prefix" value="/jsp/"></property>
 <property name="suffix" value=".jsp"></property>
</bean>
</beans>
  • jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springmvc?characterEncoding=utf-8
jdbc.username=root
jdbc.password=2626
  • 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.3.4 持久層

  • com.itzhouq.ssm.mapper.ItemsMapper:持久層的接口
package com.itzhouq.ssm.mapper;
import java.util.List;
import com.itzhouq.ssm.pojo.Items;
public interface ItemsMapper {
    List<Items> findAll();
    Items findById(int itemId);
}
  • com/itzhouq/ssm/mapper/ItemsMapper.xml:持久層的映射器
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.itzhouq.ssm.mapper.ItemsMapper" >
  <resultMap id="ItemsMap" type="com.itzhouq.ssm.pojo.Items" >
    <id column="id" property="id"  />
    <result column="name" property="name"/>
    <result column="price" property="price"/>
    <result column="pic" property="pic"  />
    <result column="createtime" property="createtime"/>
  </resultMap>
  
  <select id="findAll" resultMap="ItemsMap">
    select * from items
  </select>
  
  <select id="findById" parameterType="int" resultType="com.itzhouq.ssm.pojo.Items">
    select * from items where id = #{id}
  </select>
</mapper>

4.3.4 實體類

  • com.itzhouq.ssm.pojo.Items
package com.itzhouq.ssm.pojo;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
public class Items {
    private Integer id;
    private String name;
    private Float price;
    private String pic;
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date createtime;
    private String detail;
    //set/get方法
}

4.3.5 業(yè)務(wù)層

  • com.itzhouq.ssm.service.ItemService:業(yè)務(wù)層的接口
package com.itzhouq.ssm.service;
import java.util.List;
import com.itzhouq.ssm.pojo.Items;
public interface ItemService {
    public List<Items> findAll();
    public Items findById(int itemId);
}
  • com.itzhouq.ssm.service.impl.ItemServiceImpl:業(yè)務(wù)層的實現(xiàn)類
package com.itzhouq.ssm.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.itzhouq.ssm.mapper.ItemsMapper;
import com.itzhouq.ssm.pojo.Items;
import com.itzhouq.ssm.service.ItemService;
@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ItemsMapper itemsMapper;    
    public List<Items> findAll() {
        List<Items> list = itemsMapper.findAll();
        return list;
    }
    @Override
    public Items findById(int itemId) {
        Items item = itemsMapper.findById(itemId);
        return item;
    }
}

4.3.6 表現(xiàn)層

  • com.itzhouq.ssm.controller.ItemsController
package com.itzhouq.ssm.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.itzhouq.ssm.pojo.Items;
import com.itzhouq.ssm.service.ItemService;

@Controller
public class ItemsController {

    @Autowired
    private ItemService itemService ;
    
    @RequestMapping("/list")
    public String showAllList(Model model){
        List<Items> itemList = itemService.findAll();
        model.addAttribute("itemList",itemList);
        return "itemList";
    }

//  itemEdit.action?id=1
//  展示修改頁面
    @RequestMapping("/itemEdit")
    public String itemEdit(@RequestParam(value="id",required=false,defaultValue="1")int itemId,HttpServletRequest request, HttpServletResponse response,Model model){
        Items items = itemService.findById(itemId);
        model.addAttribute("item", items);
//      邏輯視圖:jsp的路徑
        return "editItem";
    }
}

4.3.7 頁面

  • WebContent/jsp/itemList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>查詢商品列表</title>
</head>
<body> 
<form action="${pageContext.request.contextPath }/item/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>生產(chǎn)日期</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>
  • WebContent/jsp/editItem.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> 
    <!-- 上傳圖片是需要指定屬性 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">
        <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>商品生產(chǎn)日期</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.3.8 測試

展示商品效果
  • 修改商品:點擊上圖修改按鈕進入修改頁面
修改商品效果

第5章:SpringMVC接收參數(shù)

5.1 @RequestParam綁定參數(shù)

  • 需求分析:比如在一個商品的編輯頁面,需要展示商品的信息。那么在編輯商品信息之前,需要提前根據(jù)商品的id查詢商品信息,然后展示到頁面。這時候的請求是/itemEdit.action?id=5。這里假設(shè)id為5。
參數(shù)綁定1
  • 如果請求中的參數(shù)名稱和處理器中的形參的名稱不一致的時候,就不能自動綁定。需要借助@RequestParam注解來綁定。
參數(shù)綁定2

5.2 默認(rèn)支持的參數(shù)類型

處理器形參中添加如下類型的參數(shù)處理適配器會默認(rèn)識別并進行賦值。

  • HttpServletRequest request
  • HttpServletResponse response
  • HttpSession session
  • Model model

5.3 綁定POJO類型

  • 需求分析:將頁面修改后的商品信息保存到數(shù)據(jù)庫中。這時候請求的url/updateitem.action。參數(shù)是表單中的數(shù)據(jù)。更新成功后需要跳轉(zhuǎn)頁面。如果提交的參數(shù)很多,或者表單中的內(nèi)容很多的時候可以使用pojo接收數(shù)據(jù)。要求是pojo對象中的屬性和表單中inputname屬性一致。
  • 頁面定義如下:
<input type="text" name="name"/>
<input type="text" name="price"/>
  • pojo定義:
pojo的屬性
  • 請求的參數(shù)和pojo的屬性名稱一致,會自動請求參數(shù)賦值給pojo屬性。
image
  • 注意:此時提交的表單中不要有日期類型的數(shù)據(jù),否則會報400錯誤。如果想提交日期類型的數(shù)據(jù)需要用到后面的自定義參數(shù)綁定的內(nèi)容。
  • 在數(shù)據(jù)綁定pojo類型的的過程中有可能會出現(xiàn)亂碼問題。

5.4 解決亂碼問題

  • 如果請求的方式是POST請求,需要使用過濾器。在web.xml中添加以下配置:
<filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  • 如果請求方式是GET請求,有兩種解決辦法。
  1. 方式一:修改tomcat服務(wù)器配置文件server.xml第64行。
修改tomcat服務(wù)器編碼
  1. 方式二:對參數(shù)進行重新編碼
String userName = new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")

5.5 綁定包裝POJO

  • 需求分析:使用包裝的pojo接收商品信息的查詢條件。
  • 包裝對象定義如下:
包裝對象的定義
  • 頁面定義:
頁面定義
  • Controller方法定義如下:
public String useraddsubmit(Model model,QueryVo queryVo)throws Exception{
System.out.println(queryVo.getItems());
}
  • 接收查詢條件:
@RequestMapping("/queryitem")
    public String queryItem(QueryVo queryVo) {
        System.out.println(queryVo.getItems().getName());
        System.out.println(queryVo.getItems().getPrice());
        return null;
    }

5.6 自定義參數(shù)綁定

  • 需求分析:在商品修改頁面可以修改商品的生產(chǎn)日期,并且根據(jù)業(yè)務(wù)需求自定義日期格式。
需求描述
  • 自定義Converter轉(zhuǎn)化器
public class DateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String source) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return simpleDateFormat.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}
  • 定義好轉(zhuǎn)化器之后需要配置轉(zhuǎn)化器,這里有兩種配置方式。第二種更簡單。

    • 方式一:在springmvc.xml配置文件中添加如下配置:
    <!-- 加載注解驅(qū)動 -->
      <mvc:annotation-driven conversion-service="conversionService"/>
      <!-- 轉(zhuǎn)換器配置 -->
      <bean id="conversionService"
          class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
          <property name="converters">
              <set>
                  <bean class="cn.itcast.springmvc.convert.DateConverter"/>
              </set>
          </property>
      </bean>
    
    • 方式二:在pojo類的日期屬性上添加如下注解:
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
        private Date createtime;
    
  • 由于日期數(shù)據(jù)有很多種格式,所以springmvc沒辦法把字符串轉(zhuǎn)換成日期類型。所以需要自定義參數(shù)綁定。前端控制器接收到請求后,找到注解形式的處理器適配器,對RequestMapping標(biāo)記的方法進行適配,并對方法中的形參進行參數(shù)綁定。在springmvc這可以在處理器適配器上自定義Converter進行參數(shù)綁定。如果使用<mvc:annotation-driven/>可以在此標(biāo)簽上進行擴展。

第6章:SpringMVC和Struts2的區(qū)別

  1. springmvc的入口是一個servlet即前端控制器,而struts2入口是一個filter過慮器。
  2. springmvc是基于方法開發(fā)(一個url對應(yīng)一個方法),請求參數(shù)傳遞到方法的形參,可以設(shè)計為單例或多例(建議單例),struts2是基于類開發(fā),傳遞參數(shù)是通過類的屬性,只能設(shè)計為多例
  3. Struts采用值棧存儲請求和響應(yīng)的數(shù)據(jù),通過OGNL存取數(shù)據(jù), springmvc通過參數(shù)解析器是將request請求內(nèi)容解析,并給方法形參賦值,將數(shù)據(jù)和視圖封裝成ModelAndView對象,最后又將ModelAndView中的模型數(shù)據(jù)通過request域傳輸?shù)巾撁妗?code>Jsp視圖解析器默認(rèn)使用jstl
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 對于java中的思考的方向,1必須要看前端的頁面,對于前端的頁面基本的邏輯,如果能理解最好,不理解也要知道幾點。 ...
    神尤魯?shù)婪?/span>閱讀 901評論 0 0
  • 1.Spring web mvc介紹 Spring web mvc和Struts2都屬于表現(xiàn)層的框架,它是Spri...
    七弦桐語閱讀 11,982評論 2 38
  • SpringMVC介紹 Spring web mvc 和Struts2都屬于表現(xiàn)層的框架,它是Spring框架的一...
    day_Sunny閱讀 899評論 0 0
  • 1、用戶發(fā)送請求至前端控制器DispatcherServlet 2、DispatcherServlet收到請求調(diào)用...
    Spring框架9420閱讀 433評論 0 1
  • 初到博中,我就在博中迷了路。我詢問學(xué)姐20班在哪兒,她手一指,給了我一句在那,四樓最邊,就又在忙自己的工作了。我明...
    梁一瓶閱讀 421評論 0 0

友情鏈接更多精彩內(nèi)容