導(dǎo)入所需要的jar包
- spring的jar包
- mybatis的jar包
- mybatis-3.4.5.jar
- mybatis-spring-1.3.1.jar
- springmvc的jar包
- spring-webmvc-5.0.0.RELEASE.jar
配置mybatis: mybatis.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>
配置spring dao層: spring-dao.xml
db.properties:
jdbcUrl=jdbc:mysql://localhost:3306/test
driverClass=com.mysql.jdbc.Driver
user=root
password=root
minPoolSize=5
maxPoolSize=30
initialPoolSize=10
maxIdleTime=60
acquireIncrement=5
idleConnectionTestPeriod=60
acquireRetryAttempts=30
spring-dao.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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 加載配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置數(shù)據(jù)源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${driverClass}"/>
<property name="jdbcUrl" value="${jdbcUrl}"/>
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
<!--連接池中保留的最小連接數(shù)。-->
<property name="minPoolSize" value="${minPoolSize}"/>
<!--連接池中保留的最大連接數(shù)。Default: 15 -->
<property name="maxPoolSize" value="${maxPoolSize}"/>
<!--初始化時獲取的連接數(shù),取值應(yīng)在minPoolSize與maxPoolSize之間。Default: 3 -->
<property name="initialPoolSize" value="${initialPoolSize}"/>
<!--最大空閑時間,maxIdleTime秒內(nèi)未使用則連接被丟棄。若為0則永不丟棄。Default: 0 -->
<property name="maxIdleTime" value="${maxIdleTime}"/>
<!--當(dāng)連接池中的連接耗盡的時候c3p0一次同時獲取的連接數(shù)。Default: 3 -->
<property name="acquireIncrement" value="${acquireIncrement}"/>
<!--每60秒檢查所有連接池中的空閑連接。Default: 0 -->
<property name="idleConnectionTestPeriod" value="${idleConnectionTestPeriod}"/>
<!--定義在從數(shù)據(jù)庫獲取新連接失敗后重復(fù)嘗試的次數(shù)。Default: 30 -->
<property name="acquireRetryAttempts" value="${acquireRetryAttempts}"/>
</bean>
<!-- SQLSessionFactory的配置 -->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis/Configuration.xml"/>
<!-- 掃描domain包 使用別名 -->
<property name="typeAliasesPackage" value="com.gongxm.domain"/>
</bean>
<!-- mapper代理形式dao的配置 -->
<!-- 配置包掃描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.gongxm.mapper"/>
</bean>
</beans>
配置service層: spring-service.xml
spring-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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 配置包掃描器 -->
<context:component-scan base-package="com.gongxm.service"/>
</beans>
配置事務(wù)層: spring-tx.xml
spring-tx.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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 事務(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="update*" propagation="REQUIRED"/>
<tx:method name="delete*" 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.gongxm.service.*.*(..))"/>
</aop:config>
</beans>
配置springmvc: springmvc.xml
springmvc.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 配置包掃描器,掃描controller -->
<context:component-scan base-package="com.gongxm.controller"/>
<!-- 配置注解驅(qū)動, 配置了這個就不用配置處理器和適配器了 -->
<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>
配置web.xml
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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/spring-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoader</listener-class>
</listener>
<!-- 配置前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- 指定springmvc的配置文件位置 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
數(shù)據(jù)綁定
- springmvc默認支持的數(shù)據(jù)類型: 請求可以直接使用的對象, 以及返回的類型
@RequestMapping("/itemEdit") //方法中的這些參數(shù)都是由框架傳遞, 需要使用哪個就定義哪個
public String editItem(HttpServletRequest request,
HttpServletResponse response, HttpSession session, Model model) {
//從request中取參數(shù)
String strId = request.getParameter("id");
int id = new Integer(strId);
//調(diào)用服務(wù)
Items items = itemService.getItemById(id);
//把結(jié)果傳遞給頁面
//ModelAndView modelAndView = new ModelAndView();
//modelAndView.addObject("item", items);
//設(shè)置邏輯視圖
//modelAndView.setViewName("editItem");
//return modelAndView;
//設(shè)置返回結(jié)果
model.addAttribute("item", items);
//返回邏輯視圖
return "editItem";
}
- 簡單類型的數(shù)據(jù)綁定
// 直接寫Integer id就可以接收到客戶端發(fā)送過來的id參數(shù),
//不過方法上的參數(shù)名必須要與客戶端的參數(shù)名相同!
@RequestMapping("/itemEdit")
public String editItem(Integer id, Model model) {
Items items = itemService.getItemById(id);
//把數(shù)據(jù)傳遞給頁面
model.addAttribute("item", items);
//返回邏輯視圖
return "editItem";
}
- 當(dāng)請求參數(shù)名稱與方法參數(shù)名稱不一致時, 可以使用注解進行映射:
@RequestMapping("/itemEdit")
public String editItem(@RequestParam(value="id",defaultValue="1",required=true)Integer ids, Model model) {
Items items = itemService.getItemById(ids);
//把數(shù)據(jù)傳遞給頁面
model.addAttribute("item", items);
//返回邏輯視圖
return "editItem";
}
@RequestParam(value="id",defaultValue="1",required=true)Integer ids
意思是把請求參數(shù)中的id映射到ids上, 如果沒有該參數(shù), 可以使用默認值: defaultValue="1"
required=true的意思是該參數(shù)必須要有值
- 當(dāng)需要接收一個pojo類型的參數(shù)時, 要求表單中的name屬性與pojo的屬性名相同!
@RequestMapping("/updateitem")
public String updateItem(Items items) {
itemService.updateItem(items);
//返回成功頁面
return "success";
}
- 綁定包裝pojo
包裝對象定義如下:
Public class QueryVo {
private Items items;
}
頁面定義:
<input type="text" name="items.name" />
<input type="text" name="items.price" />
Controller方法定義如下:
@RequestMapping("/queryitem")
public String queryItem(QueryVo queryVo) {
//打印綁定結(jié)果
System.out.println(queryVo.getItems().getId());
System.out.println(queryVo.getItems().getName());
return "success";
}
- 自定義參數(shù)綁定
自定義Converter
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;
}
}
配置Converter
<!-- 加載注解驅(qū)動 -->
<mvc:annotation-driven conversion-service="conversionService"/>
<!-- 轉(zhuǎn)換器配置 -->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.gongxm.convert.DateConverter"/>
</set>
</property>
</bean>
配置方式2(了解)
<!-- 轉(zhuǎn)換器配置 -->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.gongxm.convert.DateConverter"/>
</set>
</property>
</bean>
<!-- 自定義webBinder -->
<bean id="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="conversionService" ref="conversionService" />
</bean>
<!--注解適配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer" ref="customBinder"></property>
</bean>
<!-- 注解處理器映射器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
解決POST亂碼的問題
在web.xml文件中加入以下內(nèi)容:
<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>