SpringMVC与Ibatis整合开发配置备忘
本文内容纲要:
SpringMVC与Ibatis框架整合所使用版本
Ibatis2.3.4
Spring3.0
web.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!--字符过滤_防止添加到数据库中的数据为乱码-->
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
springmvc-servlet.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scanbase-package="com.archie"/>
<mvc:annotation-driven/>
<!--视图解析器-->
<beanid="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<propertyname="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<propertyname="prefix"value="/WEB-INF/views/"></property>
<propertyname="suffix"value=".jsp"></property>
</bean>
<!--异常解析器-->
<beanid="simpleMappingExceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<propertyname="exceptionMappings">
<props>
<prop
key="org.springframework.web.multipart.MaxUploadSizeExceededException">common/fileerror</prop>
</props>
</property>
</bean>
</beans>
applicationContext.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"default-autowire="byName">
<!--自动扫描-->
<context:component-scanbase-package="com.archie"/>
<!--强制使用CGLIB代理-->
<aop:aspectj-autoproxyproxy-target-class="true"/>
<!--DataSource数据源-->
<beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<propertyname="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<propertyname="url">
<value>jdbc:mysql://localhost:3306/springweb_ibatis</value>
</property>
<propertyname="username">
<value>root</value>
</property>
<propertyname="password">
<value>root</value>
</property>
</bean>
<!--SpringiBatisSqlMapClient-->
<beanid="sqlMapClient"class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<propertyname="configLocation"value="classpath:sqlmap-config.xml"/>
<propertyname="dataSource"ref="dataSource"/>
</bean>
<!--事务管理DataSourceTransactionManager-->
<beanid="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<propertyname="dataSource"ref="dataSource"/>
</bean>
<!--启动spring注解功能-->
<tx:annotation-driventransaction-manager="txManager"/>
<aop:config>
<aop:pointcutid="baseServiceMethods"expression="execution(*com.archie.dao.*.*(..))"/>
<aop:advisoradvice-ref="txAdvice"pointcut-ref="baseServiceMethods"/>
</aop:config>
<aop:aspectj-autoproxy/>
<tx:adviceid="txAdvice"transaction-manager="txManager">
<tx:attributes>
<tx:methodname="select*"read-only="true"propagation="REQUIRED"/>
<tx:methodname="find*"read-only="true"propagation="REQUIRED"/>
<tx:methodname="save*"propagation="REQUIRED"isolation="REPEATABLE_READ"/>
<tx:methodname="update*"propagation="REQUIRED"isolation="REPEATABLE_READ"/>
<tx:methodname="add*"propagation="REQUIRED"isolation="REPEATABLE_READ"/>
<tx:methodname="delete*"propagation="REQUIRED"isolation="REPEATABLE_READ"/>
</tx:attributes>
</tx:advice>
</beans>
sqlmap-config.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEsqlMapConfig
PUBLIC"-//iBATIS.com//DTDSQLMapConfig2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<sqlMapresource="sqlMap/User.xml"/>
</sqlMapConfig>
BaseDao.java
packagecom.archie.dao;
importjavax.annotation.PostConstruct;
importjavax.annotation.Resource;
importorg.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
importcom.ibatis.sqlmap.client.SqlMapClient;
/**
*BaseDao,Dao需继承此Dao
*
*@authorarchie2010since2011-3-3下午10:52:36
*/
publicclassBaseDaoextendsSqlMapClientDaoSupport{
@Resource(name="sqlMapClient")
privateSqlMapClientsqlMapClient;
@PostConstruct
publicvoidinitSqlMapClient(){
super.setSqlMapClient(sqlMapClient);
}
}
UserDao.java
packagecom.archie.dao;
importjava.util.ArrayList;
importjava.util.List;
importorg.springframework.stereotype.Component;
importcom.archie.model.User;
importcom.archie.util.Pages;
/**
*UserDao
*
*@authorarchie2010
*
*since下午10:31:52
*/
@Component
publicclassUserDaoextendsBaseDao{
/**
*添加
*
*@paramuser
*@return
*/
publicbooleanaddUser(Useruser){
Useru=(User)getSqlMapClientTemplate().insert("insertUser",user);
returnu!=null?true:false;
}
/**
*删除
*
*@paramuid
*@return
*/
publicbooleandeleteUser(intuid){
intres=getSqlMapClientTemplate().delete("deleteUserByID",uid);
returnres>0?true:false;
}
/**
*查询
*
*@paramuid
*@return
*/
publicUsergetUserByUid(intuid){
return(User)getSqlMapClientTemplate().queryForObject("findUserByID",
uid);
}
/**
*查询所有
*
*@return
*/
@SuppressWarnings("unchecked")
publicList<User>getAllUsers(){
returngetSqlMapClientTemplate().queryForList("findAllUser");
}
/**
*修改
*
*@paramuser
*@return
*/
publicbooleanupdateUser(Useruser){
intres=getSqlMapClientTemplate().update("updateUserByUser",user);
returnres>0?true:false;
}
/**
*查询(根据用户名密码)
*
*@paramuser
*@return
*/
publicUsergetUserByUnameUpwd(Useruser){
return(User)getSqlMapClientTemplate().queryForObject(
"selectByUnameAndUpwd",user);
}
/**
*记录总数
*
*@return
*/
publicintgetAllUserCount(){
return(Integer)getSqlMapClientTemplate().queryForObject(
"findAllUserCount");
}
/**
*分页
*
*@parampageNo
*@return
*/
@SuppressWarnings("unchecked")
publicPages<User>getUserByPageNo(intpageNo){
Pages<User>pages=newPages<User>(getAllUserCount());
pages.setPageSize(5);
List<User>userList=newArrayList<User>();
userList=getSqlMapClientTemplate().queryForList("findPageUser",
pages.getStart(pageNo));
pages.setPageList(userList);
returnpages;
}
}
SpringMVC的Controller
UserController.java
packagecom.archie.web;
importjavax.annotation.Resource;
importjavax.servlet.http.HttpSession;
importjavax.validation.Valid;
importorg.springframework.stereotype.Controller;
importorg.springframework.validation.BindingResult;
importorg.springframework.web.bind.annotation.PathVariable;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.web.servlet.ModelAndView;
importcom.archie.model.User;
importcom.archie.service.UserService;
importcom.archie.util.Pages;
/**
*BaseDao,Dao需继承此Dao
*
*@authorarchie2010since2011-3-3下午10:52:36
*/
@Controller
@RequestMapping("/user/*")
publicclassUserController{
@Resource
privateUserServiceuserService;
privatefinalStringLIST="redirect:/user/list/1";
/**
*登录
*@paramuser
*@paramsession
*@return
*/
@RequestMapping("/login")
publicModelAndViewlogin(@ValidUseruser,BindingResultresult,HttpSessionsession){
if(!result.hasErrors()){
UserloginUser=userService.login(user);
if(loginUser!=null){
session.setAttribute("USER",loginUser);
returnnewModelAndView("redirect:/user/list/1");
}else{
returnnewModelAndView("redirect:/");
}
}else{
ModelAndViewview=newModelAndView();
view.setViewName("redirect:/");
view.addObject("error",result.getAllErrors());
returnview;
}
}
/**
*跳转至添加页
*@return
*/
@RequestMapping(value="/new",method=RequestMethod.GET)
publicModelAndViewtoAdd(){
returnnewModelAndView("user/add");
}
/**
*保存
*@paramuser
*@return
*/
@RequestMapping(value="/new",method=RequestMethod.POST)
publicModelAndViewadd(@ValidUseruser,BindingResultresult){
if(result.hasErrors()){
returnnewModelAndView("user/add","error",result.getAllErrors());
}else{
userService.addUser(user);
returnnewModelAndView(LIST);
}
}
/**
*根据ID删除
*@paramid
*@return
*/
@RequestMapping(value="/del/{id}")
publicModelAndViewdelete(@PathVariableintid){
userService.deleteUser(id);
returnnewModelAndView(LIST);
}
/**
*跳转至编辑页面
*@paramid
*@return
*/
@RequestMapping(value="/edit/{id}")
publicModelAndViewedit(@PathVariableintid){
Useruser=userService.getUserById(id);
returnnewModelAndView("user/edit","user",user);
}
/**
*编辑
*@paramuser
*@return
*/
@RequestMapping(value="/edit")
publicModelAndViewupdate(@ValidUseruser,BindingResultresult){
ModelAndViewview=newModelAndView();
if(result.hasErrors()){
view.addObject("error",result.getAllErrors());
view.setViewName("user/edit");
returnview;
}else{
userService.updateUser(user);
returnnewModelAndView(LIST);
}
}
/**
*分页
*@parampageNo
*@return
*/
@RequestMapping(value="/list/{pageNo}")
publicModelAndViewlist(@PathVariableintpageNo){
Pages<User>pages=userService.getUserByPageNo(pageNo);
returnnewModelAndView("user/main","pages",pages);
}
}
本文内容总结:
原文链接:https://www.cnblogs.com/archie2010/archive/2011/05/06/2038792.html