springmvc整合mybatis以及參數綁定詳解
- 一、工程搭建
- 1.1 創建web工程
- 1.2 導入jar包
- 1.3 添加配置文件
- 1.3.1 sqlMapConfig.xml
- 1.3.2 applicationContext-dao.xml
- 1.3.3 db.properties
- 1.3.4 applicationContext-service.xml
- 1.3.5 applicationContext-trans.xml
- 1.3.6 springmvc.xml
- 1.3.7 web.xml
- 1.4 添加JSP頁面
- 二、功能開發
- 三、參數綁定
- 3.1 默認支持的參數類型
- 3.2 綁定簡單類型
- 3.3 綁定pojo類型
- 3.4 綁定包裝pojo
- 3.5 自定義參數綁定
- 四、高級參數綁定
一、工程搭建
1.1 創建web工程
1.2 導入jar包
1.3 添加配置文件
1.3.1 sqlMapConfig.xml
使用逆向工程來生成Mapper相關代碼,不需要配置別名。
在config/mybatis下創建SqlMapConfig.xml。
1.3.2 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: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" />
<!-- 加載mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
</bean>
<!-- 配置Mapper掃描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置Mapper掃描包 -->
<property name="basePackage" value="com.springmvc_mybatis.mapper" />
</bean>
</beans>
1.3.3 db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springmvc?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123
1.3.4 applicationContext-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 配置service掃描 -->
<context:component-scan base-package="com.springmvc_mybatis.service" />
</beans>
1.3.5 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>
<!-- 通知 -->
<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:method name="query*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.springmvc_mybatis.service.*.*(..))" />
</aop:config>
</beans>
1.3.6 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.springmvc_mybatis.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>
1.3.7 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-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>
<!-- 配置SrpingMVC的前端控制器 -->
<servlet>
<servlet-name>springmvc-mybatis</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-mybatis</servlet-name>
<!-- 配置所有以action結尾的請求進入SpringMVC -->
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
1.4 添加JSP頁面
二、功能開發
2.1 需求
實現商品查詢列表,從mysql數據庫查詢商品信息。
2.2 dao開發
採用逆向工程,生成mapper和pojo,dao層開發完畢
2.3 service開發
service接口
public interface ItemService {
//查詢商品列表
List<Items> queryItemList();
}
service實現類
@Service
public class ItemServiceImpl implements ItemService{
@Autowired
private ItemsMapper itemsMapper;
//查詢商品列表
public List<Items> queryItemList() {
List<Items> list = itemsMapper.selectByExample(null);
return list;
}
}
2.4 controller開發
@Controller
public class ItemController {
@Autowired
private ItemService itemService;
@RequestMapping("/itemList")
public ModelAndView queryItemList() {
// 獲取商品數據
List<Items> list = itemService.queryItemList();
ModelAndView modelAndView = new ModelAndView();
// 把商品數據放到模型中
modelAndView.addObject("itemList", list);
// 設置邏輯視圖
modelAndView.setViewName("itemList");
return modelAndView;
}
}
三、參數綁定
3.1 默認支持的參數類型
3.1.1 需求分析
編輯商品信息,首先要顯示商品詳情
需要根據商品id查詢商品信息,然後展示到頁面。
請求的url:/itemEdit.action
參數:id(商品id)
響應結果:商品編輯頁面,展示商品詳細信息。
3.1.2 service層開發
接口開發
實現類開發
public Items queryItemById(int id) {
Items item = itemsMapper.selectByPrimaryKey(id);
return item;
}
3.1.3 web層開發
頁面點擊修改按鈕,發起請求
http://127.0.0.1:8080/springmvc-mybatis/itemEdit.action?id=1
需要從請求的參數中把請求的id取出來。
Id包含在Request對象中。可以從Request對象中取id。
想獲得Request對象只需要在Controller方法的形參中添加一個參數即可。Springmvc框架會自動把Request對象傳遞給方法。
//根據id查詢商品
@RequestMapping("/itemEdit")
public ModelAndView queryItemById(HttpServletRequest request) {
// 從request中獲取請求參數
String strId = request.getParameter("id");
Integer id = Integer.valueOf(strId);
// 根據id查詢商品數據
Items item = this.itemService.queryItemById(id);
// 把結果傳遞給頁面
ModelAndView modelAndView = new ModelAndView();
// 把商品數據放在模型中
modelAndView.addObject("item", item);
// 設置邏輯視圖
modelAndView.setViewName("editItem");
return modelAndView;
}
3.1.4 支持的參數
處理器形參中添加如下類型的參數處理適配器會默認識別並進行賦值。
3.1.4.1 HttpServletRequest
通過request對象獲取請求信息
3.1.4.2 HttpServletResponse
通過response處理響應信息
3.1.4.3 HttpSession
通過session對象得到session中存放的對象
3.1.5 Model / ModelMap
3.1.5.1 Model
除了ModelAndView以外,還可以使用Model來向頁面傳遞數據,Model是一個接口,在參數裏直接聲明model即可。
如果使用Model則可以不使用ModelAndView對象,Model對象可以向頁面傳遞數據,View對象則可以使用String返回值替代。
不管是Model還是ModelAndView,其本質都是使用Request對象向jsp傳遞數據。
//根據id查詢商品,使用Model
@RequestMapping("/itemEdit")
public String queryItemById(HttpServletRequest request, Model model) {
// 從request中獲取請求參數
String strId = request.getParameter("id");
Integer id = Integer.valueOf(strId);
// 根據id查詢商品數據
Items item = this.itemService.queryItemById(id);
// 把結果傳遞給頁面
// ModelAndView modelAndView = new ModelAndView();
// 把商品數據放在模型中
// modelAndView.addObject("item", item);
// 設置邏輯視圖
// modelAndView.setViewName("itemEdit");
// 把商品數據放在模型中
model.addAttribute("item", item);
return "editItem";
}
3.1.5.2 ModelMap
ModelMap是Model接口的實現類,也可以通過ModelMap向頁面傳遞數據。
使用Model和ModelMap的效果一樣,如果直接使用Model,springmvc會實例化ModelMap。
3.2 綁定簡單類型
當請求的參數名稱和處理器形參名稱一致時會將請求參數與形參進行綁定。這樣,從Request取參數的方法就可以進一步簡化。
//根據id查詢商品,綁定簡單數據類型
@RequestMapping("/itemEdit")
public String queryItemById(int id, ModelMap model) {
// 根據id查詢商品數據
Items item = this.itemService.queryItemById(id);
// 把商品數據放在模型中
model.addAttribute("item", item);
return "editItem";
}
3.2.1 支持的數據類型
參數類型推薦使用包裝數據類型,因爲基礎數據類型不可以爲null
整形:Integer、int
字符串:String
單精度:Float、float
雙精度:Double、double
布爾型:Boolean、boolean
說明:對於布爾類型的參數,請求的參數值爲true或false。或者1或0
請求url:http://localhost:8080/xxx.action?id=2&status=false
處理器方法:
public String editItem(Model model,Integer id,Boolean status)
3.2.2 @RequestParam
使用@RequestParam常用於處理簡單類型的綁定。
value:參數名字,即入參的請求參數名字,如value=“itemId”表示請求的參數 區中的名字爲itemId的參數的值將傳入
required:是否必須,默認是true,表示請求中一定要有相應的參數,否則將報錯
TTP Status 400 - Required Integer parameter ‘XXXX’ is not present
defaultValue:默認值,表示如果請求中沒有同名參數時的默認值
@RequestMapping("/itemEdit")
public String queryItemById(@RequestParam(value = "itemId", required = true, defaultValue = "1") Integer id,
ModelMap modelMap) {
// 根據id查詢商品數據
Items item = this.itemService.queryItemById(id);
// 把商品數據放在模型中
modelMap.addAttribute("item", item);
return "editItem";
}
3.3 綁定pojo類型
3.3.1 需求分析
將頁面修改後的商品信息保存到數據庫中。
請求的url:/updateItem.action
參數:表單中的數據。
響應內容:更新成功頁面。
3.3.2 使用pojo接收表單數據
如果提交的參數很多,或者提交的表單中的內容很多的時候,可以使用簡單類型接受數據,也可以使用pojo接收數據。
要求:pojo對象中的屬性名和表單中input的name屬性一致。
pojo是逆向工程生成的
請求的參數名稱和pojo的屬性名稱一致,會自動將請求參數賦值給pojo的屬性。
3.3.3 service層開發
接口開發
//根據id更新商品
void updateItemById(Items item);
實現類開發
使用updateByPrimaryKeySelective(item)方法,忽略空參數。
public void updateItemById(Items item) {
itemsMapper.updateByPrimaryKeySelective(item);
}
3.3.4 web層開發
//更新商品,綁定pojo類型
@RequestMapping("/updateItem")
public String updateItem(Items item) {
// 調用服務更新商品
itemService.updateItemById(item);
// 返回邏輯視圖
return "success";
}
注意:
提交的表單中不要有日期類型的數據,否則會報400錯誤。如果想提交日期類型的數據需要用到後面的自定義參數綁定的內容。
3.3.5 解決post提交亂碼
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>
get亂碼解決
對於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-1是tomcat默認編碼,需要將tomcat編碼後的內容按utf-8編碼。
3.4 綁定包裝pojo
3.4.1 需求分析
使用包裝的pojo接收商品信息的查詢條件。
包裝對象如下:
public class QueryVo {
private Items items;
public Items getItems() {
return items;
}
public void setItems(Items items) {
this.items = items;
}
}
3.4.2 接收查詢條件
// 綁定包裝數據類型
@RequestMapping("/queryItem")
public String queryItem(QueryVo queryVo) {
System.out.println(queryVo.getItems().getId());
System.out.println(queryVo.getItems().getName());
return "success";
}
3.5 自定義參數綁定
3.5.1 需求分析
在商品修改頁面可以修改商品的生產日期,並且根據業務需求自定義日期格式。
由於日期數據有很多種格式,springmvc沒辦法把字符串轉換成日期類型。所以需要自定義參數綁定。
前端控制器接收到請求後,找到註解形式的處理器適配器,對RequestMapping標記的方法進行適配,並對方法中的形參進行參數綁定。可以在springmvc處理器適配器上自定義轉換器Converter進行參數綁定。
一般使用mvc:annotation-driven/註解驅動加載處理器適配器,可以在此標籤上進行配置。
3.5.2 自定義Converter
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.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;
}
}
3.5.3 配置Converter
<!-- 註解驅動 -->
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean" />
<!-- 配置Conveter轉換器 轉換工廠 (日期、去掉前後空格)。。 -->
<bean id="conversionServiceFactoryBean"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<!-- 配置 多個轉換器 -->
<property name="converters">
<list>
<bean class="com.springmvc_mybatis.converter.DateConverter" />
</list>
</property>
</bean>
四、高級參數綁定
4.1 綁定數組
4.1.1 需求分析
在商品列表頁面選中多個商品,然後刪除。
功能要求商品列表頁面中的每個商品前有一個checkbok,選中多個商品後點擊刪除按鈕把商品id傳遞給Controller,根據商品id刪除商品信息。
4.1.2 jsp修改
修改itemList.jsp頁面,增加多選框。
4.1.3 controller
Controller方法中可以用String[]接收,或者pojo的String[]屬性接收。兩種方式任選其一即可。
QueryVo中添加對應的屬性
4.2 將表單數據綁定到List
4.2.1 需求分析
實現商品數據的批量修改。
- 在商品列表頁面中可以對商品信息進行修改。
- 可以批量提交修改後的商品數據。
4.2.2 定義pojo
List中存放對象,並將定義的List放在包裝類QueryVo中。
4.2.3 修改jsp
${current} 當前這次迭代的(集合中的)項
${status.first} 判斷當前項是否爲集合中的第一項,返回值爲true或false
${status.last} 判斷當前項是否爲集合中的最
varStatus屬性常用參數總結下:
${status.index} 輸出行號,從0開始。
${status.count} 輸出行號,從1開始。
${status.後一項,返回值爲true或false
begin、end、step分別表示:起始序號,結束序號,跳躍步伐。