以用戶管理系統的開發爲例,詳細介紹SpringMVC+Spring+Mybatis的整合,並在編寫controller的過程當中記錄SpringMVC中的一些高級應用(會特別標示)html
1. 項目需求:主要實現簡單的用戶登陸註冊,以及修改自身信息功能,額外擴展一個用戶管理系統,能夠查看全部用戶以及刪除用戶前端
2. 搭建工程:建立Maven工程java
mybatis和spring整合,經過spring管理mapper接口。mysql
使用mapper的掃描器自動掃描mapper接口在spring中進行註冊。git
第二步:整合service層github
經過spring管理 service接口。web
使用配置方式將service接口配置在spring配置文件中。spring
實現事務控制。sql
第三步:整合springmvc因爲springmvc是spring的模塊,不須要整合。數據庫
整合dao層
編寫mybatis的配置文件,sqlmapconfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-config.dtd"> <configuration> <!-- 配置分頁插件,dialect指定使用的數據庫類型 --> <plugins> <plugin interceptor="com.github.pagehelper.PageHelper"> <property name="dialect" value="mysql"/> </plugin> </plugins> </configuration>
<?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:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <!-- mybatis配置 --> <context:property-placeholder location="classpath:db.properties"/> <bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="password" value="${jdbc.password}"></property> <property name="username" value="${jdbc.name}"></property> </bean> <bean id="ssf" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="datasource"></property> <property name="configLocation" value="classpath:conf/SqlMapConfig.xml"></property> </bean> <bean id="mfc" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="user_manage.mapper"></property> <property name="sqlSessionFactoryBeanName" value="ssf"></property> </bean> </beans>
import java.util.List; import org.apache.ibatis.annotations.Param; import user_manage.pojo.User; import user_manage.pojo.UserExample; public interface UserMapper { long countByExample(UserExample example); int deleteByExample(UserExample example); int deleteByPrimaryKey(Integer userAccount); int insert(User record); int insertSelective(User record); List<User> selectByExample(UserExample example); User selectByPrimaryKey(Integer userAccount); int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example); int updateByExample(@Param("record") User record, @Param("example") UserExample example); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); }
import java.util.List; import user_manage.pojo.User; public interface UserService { public void insertUser(User user); public void deleteUser(int user_account); public List<User> findUserList(int pageNumber,int rows); public void updateUser(User user); }
<?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:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <context:component-scan base-package="user_manage.service"></context:component-scan> </beans>
配置開啓事務管理:編寫applicationContext_tx.xml,對service層中的全部方法開啓事務管理
<?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:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="datasource"></property> </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="add*" 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="select*" propagation="SUPPORTS" read-only="true"/> <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <!-- AOP配置 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* user_manage.service.*.*(..))"/> </aop:config> </beans>
<?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:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <context:component-scan base-package="user_manage.controller"></context:component-scan> <mvc:annotation-driven></mvc:annotation-driven> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--該配置用於接收上傳的文件--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize"> <value>1048576</value> </property> <property name="defaultEncoding"> <value>utf-8</value> </property> </bean> <!--該配置用於處理RESTful風格路徑所引發的訪問靜態資源路徑錯誤問題--> <mvc:resources location="/WEB-INF/js/" mapping="/js/**"/> <mvc:resources location="/WEB-INF/html/" mapping="/html/**"/> </beans>
編寫Controller類
編寫jsp
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>user_manage</display-name> <!-- 經過 controller、service、dao三層的配置文件加載spring容器,這裏是spring應用上下文--> <context-param> <param-name>contextConfigLocation</param-name> <!-- *表示通配符,以通配符的方式匹配加載配置文件--> <param-value>classpath:conf/applicationContext_*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- RESTful風格的路徑配置 --> <servlet> <servlet-name>RESTful</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--SpringMVC加載的配置文件,這裏是springweb應用上下文 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:conf/springMVC.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>RESTful</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 以.do結尾的路徑也會接收 --> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置SpringMVC加載的配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:conf/springMVC.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- post請求編碼過濾器,將post中的請求參數統一轉爲utf-8編碼,/*表示攔截全部路徑請求 --> <filter> <filter-name>postEncode</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>postEncode</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
1. 操做流程:首先進入註冊頁面,而後填寫註冊所需的數據,而後點擊註冊,發送請求
2. 開發Mapper:
<insert id="insertSelective" parameterType="user_manage.pojo.User"> <!-- 將自增主鍵生成的結果回寫到傳入的user_manage.pojo.User對象中 --> <selectKey keyProperty="userAccount" keyColumn="user_account" order="AFTER" resultType="int"> select last_insert_id() </selectKey> insert into user <trim prefix="(" suffix=")" suffixOverrides=","> <if test="userAccount != null">user_account,</if> <if test="userName != null">user_name,</if> <if test="userPassword != null">user_password,</if> <if test="userAge != null">user_age,</if> <if test="userAddress != null">user_address,</if> <if test="userTelephone != null">user_telephone,</if> <if test="userImage != null">user_image,</if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="userAccount != null">#{userAccount,jdbcType=INTEGER},</if> <if test="userName != null">#{userName,jdbcType=VARCHAR},</if> <if test="userPassword != null">#{userPassword,jdbcType=VARCHAR},</if> <if test="userAge != null">#{userAge,jdbcType=INTEGER},</if> <if test="userAddress != null">#{userAddress,jdbcType=VARCHAR}, </if> <if test="userTelephone != null">#{userTelephone,jdbcType=CHAR},</if> <if test="userImage != null">#{userImage,jdbcType=VARCHAR},</if> </trim> </insert>
3. 開發service:實現insertUser方法
public void insertUser(User user) { userMapper.insertSelective(user); }
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /** * @ClassName:PageController * @Description:頁面跳轉,主要請求路徑爲/page/regist.do,不寫.do是由於在前端控制器中配置掃描以.do結尾的請求路徑 * 因此在RequestMapping中就不須要寫.do */ @Controller @RequestMapping("/page") public class PageController { @RequestMapping("/regist") public ModelAndView toRegist(){ ModelAndView mv=new ModelAndView(); mv.setViewName("regist"); return mv; } }
//限制只接受post和get方式的請求 @RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST})
@RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST}) public ModelAndView toRegist(){ ModelAndView mv=new ModelAndView(); mv.setViewName("regist"); return mv; }
//若是返回的String表示邏輯視圖名,那麼,只須要在方法的形參中添加一個Model類型的參數, //就會自動將Model對象和邏輯視圖名錶明的邏輯視圖傳給前端控制器進行處理,至關於返回ModelAndView @RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST}) public String toRegist(Model model){ model.addAttribute("key", "value"); return "regist"; }
redirect重定向:redirect重定向特色就是瀏覽器地址欄中的url會變化。修改提交的request數據沒法傳到重定向的地址。由於重定向後從新進行request(request沒法共享)
@Controller @RequestMapping("/page") public class PageController { //若是請求路徑爲/page,那麼主動重定向跳轉至註冊頁面 @RequestMapping("/") public String toPage(){ return "redirect:regist.do"; } @RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST}) public String toRegist(Model model){ model.addAttribute("key", "value"); return "regist"; } }
forward頁面轉發:經過forward進行頁面轉發,瀏覽器地址欄url不變,request能夠共享。
@Controller @RequestMapping("/page") public class PageController { //若是請求路徑爲/page,那麼主動重定向跳轉至註冊頁面 @RequestMapping("/") public String toPage(){ return "forward:regist.do"; } @RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST}) public String toRegist(Model model){ model.addAttribute("key", "value"); return "regist"; } }
@RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST}) public void toRegist(HttpServletRequest req,HttpServletResponse res){ req.setAttribute("key", "value"); try { req.getRequestDispatcher("path").forward(req, res); } catch (ServletException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
也能夠經過response指定響應結果,例如html等,響應json數據以下:
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("json串");
@RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST}) public String toRegist(Model model,@RequestParam(value="id",required=true,defaultValue="1") int id){ model.addAttribute("key", "value"); return "regist"; }
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.core.convert.converter.Converter; //自定義轉換器必須實現org.springframework.core.convert.converter.Converter接口 public class DateConvertor implements Converter<String,Date>{ @Override public Date convert(String source) { SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd HH:mm:ss"); Date date=null; try { date = sdf.parse(source); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return date; } }
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="user_manage.convertor.DateConvertor"></bean> </list> </property> </bean>