spring+springmvc+ibatis整合註解方式實例

需求說明html

實現用戶經過數據庫驗證登陸需求。採用 Myeclipse+Tomcat 6.0+Mysql 5.0+JDK 1.6java


2.數據庫表mysql

開發所用是Mysql數據庫,僅僅創建單張用戶表T_USER,表結構例如如下:web

   

字段名稱spring

數據類型sql

字段描寫敘述數據庫

IDexpress

intapache

用戶編號spring-mvc

USERNAME

VARCHAR

username

PASSWORD

VARCHAR

用戶登陸password

sql語句例如如下:   

    CREATE TABLE `t_user` (
    `ID` int(11) NOT NULL auto_increment,
    `USERNAME` varchar(255) default NULL,
    `PASSWORD` varchar(255) default NULL,
    PRIMARY KEY  (`ID`)
    );

3.構建源碼文件夾

5.各項Xml配置文件具體解釋

(1)web.xml文件(Tomcat使用)

server依據配置內容初始化 spring 框架。 springmvc 框架和 log4j 日誌框架  
<pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?>
<web-app version="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">
  
  <!-- 應用程序名稱 -->
  <display-name>ISS</display-name>
  
  <!-- 應用程序描寫敘述說明性文字 -->
  <description>Spring,SpringMvc,Ibatis</description>
  
  <!-- ServletContext初始化參數 -->
  <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>spring_springmvc_ibatis.root</param-value>
  </context-param>
  <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/classes/log4j.properties</param-value>
  </context-param>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
  </context-param>
        
  <!-- 字符過濾,防止加入到數據庫的數據爲亂碼 -->
  <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>
  
  <!-- web權限配置 -->
  <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- 配置監聽器,用於初始化 -->
  <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- Servlet初始化參數,配置springmvc模塊 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/classes/springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 配置session存在時間 -->
  <session-config>
    <session-timeout>60</session-timeout>
  </session-config>
  
  <!-- 默認起始頁面 -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 異常跳轉頁面 -->
  <error-page>
        <exception-type>java.lang.Exception</exception-type>
        <location>/WEB-INF/jsp/exception.jsp</location>
  </error-page>
</web-app>

 
 

(2)springmvc-servlet.xml(Springmvc框架配置文件)

該文件是springmvc框架配置文件,也是它的核心文件

<?

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: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"> <!-- 本身主動掃描,完畢bean建立和依賴注入 --> <context:component-scan base-package="com.archie"/> <!-- 啓動Spring MVC的註解功能,完畢請求和註解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <!-- 視圖解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 異常解析器 --> <bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">common/fileerror</prop> </props> </property> </bean> </beans>


(3)applicationContext.xml(Spring 框架配置文件 )

<?

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: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-scan base-package="com.archie"/> <!-- 啓動spring註解,當本身主動掃描啓動後,該配置可以去掉 <context:annotation-config /> --> <!-- 啓動spring註解,等同於 context:annotation-config <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <bean class="org.springframework.beans.factory.annotation.PersistenceAnnotationBeanPostProcessor"/> <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/> --> <!-- 配置數據源屬性文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>jdbc.properties</value> </list> </property> </bean> <!-- 配置數據源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </bean> <!-- 配置SqlMapClient對象 --> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation" value="sqlMapConfig.xml"/> <property name="dataSource" ref="dataSource"/> </bean> <!--依據sqlMapClien建立一個SqlMapClient模版類--> <bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate"> <property name="sqlMapClient" ref="sqlMapClient"/> </bean> <!-- 配置事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 啓動spring事務註解,事務註解盡在此 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 配置事務特性 <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="select*" read-only="true" propagation="REQUIRED"/> <tx:method name="find*" read-only="true" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED" isolation="REPEATABLE_READ"/> <tx:method name="update*" propagation="REQUIRED" isolation="REPEATABLE_READ"/> <tx:method name="add*" propagation="REQUIRED" isolation="REPEATABLE_READ"/> <tx:method name="delete*" propagation="REQUIRED" isolation="REPEATABLE_READ"/> <tx:method name="*" read-only="true"/> </tx:attributes> </tx:advice> --> <!-- 配置事務代理攔截器 <bean id="baseTransactionProxy" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"> <ref bean="transactionManager"/> </property> <property name="transactionAttributes"> <props> <prop key="insert*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="delete*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED,readOnly</prop> </props> </property> </bean> --> <!-- 配置哪些類的方法需要進行事務管理 <aop:config> <aop:pointcut id="baseServiceMethods" expression="execution(* com.archie.service.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="baseServiceMethods"/> </aop:config> <aop:aspectj-autoproxy /> --> <!-- 配置Dao實例 <bean id="userDao" class="com.archie.dao.UserDao"> <property name="sqlMapClient" ref="sqlMapClient"/> </bean> --> <!-- 配置Service實例 <bean id="userService" class="com.archie.service.UserService"> <property name="userDao" ref="userDao"/> </bean> --> <!-- 加入了事務的管理類 <bean id="userManager" parent="baseTransactionProxy"> <property name="target"> <bean class="com.archie.service.UserService"/> </property> </bean> --> </beans>


(4)jdbc.properties(數據源屬性文件)

數據源鏈接信息的源出處。眼下配置了三種數據庫OracleDB2Mysql

# Database Connectivity
# Oracle
#driver = oracle.jdbc.driver.OracleDriver
#url = jdbc:oracle:thin:@localhost:1521:oracl
#username = scott
#password = tiger
  
# DB2
#driver = com.ibm.db2.jcc.DB2Driver
#url = jdbc:db2://10.1.10.162:50000/mydb
#username = root
#password = root
  
# Mysql
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mydb?

useUnicode=true&characterEncoding=utf-8 username = root password = 1234 initialPoolSize = 1 minPoolSize = 1 maxPoolSize =10


(5)log4j.properties(log4j 框架屬性文件 )

log4j日誌屬性配置文件

# log4j.properties
log4j.rootLogger=warn,console
  
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%d] [%t] (%F:%L) %-5p %c - %m%n
log4j.appender.console.Encoding=GB18030
  
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=10240KB
log4j.appender.file.MaxBackupIndex=100
log4j.appender.file.Encoding=GB18030
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%d] [%t] (%F:%L) %-5p %c - %m%n
  
log4j.appender.ROLLING_FILE_CUSTOMER=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING_FILE_CUSTOMER.Threshold=debug
log4j.appender.ROLLING_FILE_CUSTOMER.Append=true
log4j.appender.ROLLING_FILE_CUSTOMER.MaxFileSize=1024KB
log4j.appender.ROLLING_FILE_CUSTOMER.MaxBackupIndex=30
log4j.appender.ROLLING_FILE_CUSTOMER.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING_FILE_CUSTOMER.layout.ConversionPattern=%d - %c:%L - %-5p %c %x - %m%n
  
log4j.appender.ROLLING_FILE_WORKMANAGER=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING_FILE_WORKMANAGER.Threshold=debug
log4j.appender.ROLLING_FILE_WORKMANAGER.Append=true
log4j.appender.ROLLING_FILE_WORKMANAGER.MaxFileSize=1024KB
log4j.appender.ROLLING_FILE_WORKMANAGER.MaxBackupIndex=30
log4j.appender.ROLLING_FILE_WORKMANAGER.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING_FILE_WORKMANAGER.layout.ConversionPattern=%d - %c:%L - %-5p %c %x - %m%n
  
log4j.appender.ROLLING_FILE_RSS=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING_FILE_RSS.Threshold=debug
log4j.appender.ROLLING_FILE_RSS.Append=true
log4j.appender.ROLLING_FILE_RSS.MaxFileSize=1024KB
log4j.appender.ROLLING_FILE_RSS.MaxBackupIndex=30
log4j.appender.ROLLING_FILE_RSS.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING_FILE_RSS.layout.ConversionPattern=%d - %c:%L - %-5p %c %x - %m%n

(6)sqlMapConfig.xml(Ibatis 框架配置文件 )

該文件主要負責指定sql映射文件,即與model層對象相應的映射文件

<?xml version="1.0" encoding="UTF-8" ?

> <!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <!-- 配置settings --> <settings lazyLoadingEnabled="true" useStatementNamespaces="false"/> <!-- 配置sql映射文件 --> <sqlMap resource="com/archie/model/User.xml"/> </sqlMapConfig>


6.Java 代碼編寫

依據包文件夾,可以看出分紅model,dao,service層和web,另外附加test,用於java環境測試

(1)model(User.java+User.xml)

   User.java代碼

package com.archie.model;
  
public class User {
  
    private int id; 
    private String username; 
    private String password;
    
    public User(){
        
    }
    
    public User(int id){
        this.id = id;
    }
    
    public User(int id, String username){
        this.id = id;
        this.username = username;
    }
    
    public User(String username, String password) {
               this.username = username;
               this.password = password;
        }
    
    public User(int id, String username, String password){
        this.id = id;
        this.username = username;
        this.password = password;
    }
      
    public int getId() { 
        return id; 
    } 
    public void setId(int id) { 
        this.id = id; 
    } 
    public String getUsername() { 
        return username; 
    } 
    public void setUsername(String username) { 
        this.username = username; 
    } 
    public String getPassword() { 
        return password; 
    } 
    public void setPassword(String password) { 
        this.password = password; 
    }
}
User.xml 代碼 (model 層對象的 sql 映射文件 , dao 層調用 , 本質是 sql 語句集合 , 所有相關的 sql 均於此 )

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" 
"http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="User">
  
        <typeAlias alias="User" type="com.archie.model.User"/>
        
        <select id="findAllUser" resultClass="User" > 
        select * from t_user
        </select>
        <select id="findUserByID" resultClass="User" parameterClass="int"> 
        select * from t_user where id=#id#
    </select>
    
    <select id="getTotalCount" resultClass="int">
        select count(*) from t_user
    </select>
    
    <select id="searchUsers" resultClass="User" parameterClass="User"> 
        select * from t_user 
        <dynamic prepend="where"> 
         <!-- 模糊查詢,用$表示文本替換,而用#表示替換PrepareStatement中的?號 --> 
         <isNotEmpty prepend="and" property="username"> 
                (username like '%$username$%') 
         </isNotEmpty> 
         <isNotEmpty prepend="and" property="password"> 
                (password like '%$password$%') 
         </isNotEmpty> 
        </dynamic> 
        </select>
        
        <select id="findUserByNameAndPassword" resultClass="User" parameterClass="User"> 
        select * from t_user where username=#username# and password=#password#
    </select>
        
        <insert id="insertUser" parameterClass="User"> 
        insert into t_user(id,username,password) values(null,#username#,#password#)
        </insert>
        
        <update id="updateUser" parameterClass="User"> 
        update t_user
        set username = #username#,
                password=#password#   
        where id=#id#
        </update>
  
        <delete id="deleteUser" parameterClass="int"> 
        delete from t_user where id=#id#
        </delete>
        
        <delete id="deleteUserByLike" parameterClass="User">
                delete from t_user
                <dynamic prepend="where"> 
         <!-- 模糊查詢,用$表示文本替換,而用#表示替換PrepareStatement中的?

號 --> <isNotEmpty prepend="and" property="username"> (username like '%$username$%') </isNotEmpty> <isNotEmpty prepend="and" property="password"> (password like '%$password$%') </isNotEmpty> </dynamic> </delete> </sqlMap> (2)dao層(數據服務層,BaseDao.java+UserDao.java) BaseDao.java(公共Dao,其它Dao均繼承它) package com.archie.dao; import javax.annotation.PostConstruct; import javax.annotation.Resource; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import com.ibatis.sqlmap.client.SqlMapClient; public class BaseDao extends SqlMapClientDaoSupport { @Resource(name="sqlMapClient") //經過bean名稱注入 private SqlMapClient sqlMapClient; @PostConstruct //完畢sqlMapClient初始化工做 public void initSqlMapClient(){ super.setSqlMapClient(sqlMapClient); } }


UserDao.java(user 數據服務層 )
package com.archie.dao;
  
import java.util.List;
  
import org.springframework.stereotype.Component;
import com.archie.model.User;
  
@Component  //將UserDao類注入到bean裏面
public class UserDao extends BaseDao {
  
        public boolean addUser(User user) throws Exception{
               User bean = (User)getSqlMapClientTemplate().insert("insertUser", user);
               return bean != null ? true : false;
        }
        
        public boolean deleteUser(int id) throws Exception{
               int result = getSqlMapClientTemplate().delete("deleteUser", id);
               return result > 0 ? true : false;
        }
        
        public User getUserById(int id) throws Exception{
               return (User)getSqlMapClientTemplate().queryForObject("findUserByID", id);
        }
        
        @SuppressWarnings("unchecked")
        public List getAllUsers() throws Exception{
               return getSqlMapClientTemplate().queryForList("findAllUser");
        }
        
        public boolean updateUser(User user) throws Exception{
               int result = getSqlMapClientTemplate().update("updateUser", user);
               return result > 0 ? true : false;
        }
        
        public User getUserByNameAndPassword(User user) throws Exception{
               return (User)getSqlMapClientTemplate().queryForObject("findUserByNameAndPassword", user);
        }
        
        public int getTotalCount() throws Exception{
               return (Integer)getSqlMapClientTemplate().queryForObject("getTotalCount");
        }
        
        @SuppressWarnings("unchecked")
        public List getUsersByLike(User user) throws Exception{
               return getSqlMapClientTemplate().queryForList("searchUsers", user);
        }
        
        public int deleteUserByLike(User user) throws Exception{
               int result = getSqlMapClientTemplate().delete("deleteUserByLike", user);
               if (result > 0) {
                       System.out.println("模糊刪除成功。");
               }else {
                       System.out.println("沒有匹配的記錄1");
               }
               return result;
        }
}

(3)service ( 業務服務層 ,UserService.java)

   UserService.java代碼例如如下

package com.archie.service;
  
import java.util.List;
  
import javax.annotation.Resource;
  
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
  
import com.archie.dao.UserDao;
import com.archie.model.User;
  
@Component  //將UserService類注入到bean裏面
@Transactional  //注入事務管理
public class UserService {
        
        @Resource(name="userDao")  // 經過名稱注入到bean裏面
        private UserDao userDao;
  
        public User login(User user) throws Exception{
               return userDao.getUserByNameAndPassword(user);
        }
        
        public void addUser(User user) throws Exception{
               userDao.addUser(user);
        }
        
        public void deleteUser(int id) throws Exception{
               boolean bool = userDao.deleteUser(id);
               if (!bool) {
                       System.out.println("刪除的記錄不存在!

"); throw new RuntimeException(); } } public User getUserById(int id) throws Exception{ User user = userDao.getUserById(id); if (user == null) { return null; } return userDao.getUserById(id); } public void updateUser(User user) throws Exception{ userDao.updateUser(user); } public int getTotalCount() throws Exception{ return userDao.getTotalCount(); } @SuppressWarnings("unchecked") public List getUsersByLike(User user) throws Exception{ return userDao.getUsersByLike(user); } public int deleteUserByLike(User user) throws Exception{ return userDao.deleteUserByLike(user); } public void insertUsers(List<User> list) throws Exception{ for (int i = 0; i < list.size(); i++) { if (i > 3) { System.out.println("列表太長,中斷事務"); throw new RuntimeException("中斷事務異常,當列表長度大於3的時候有益拋出。看看事務是否回滾"); } User user = list.get(i); userDao.addUser(user); } } }


(4)web ( 界面控制層 ,UserController.java)

   UserController.java

package com.archie.web;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.archie.model.User;
import com.archie.service.UserService;
@Controller
@RequestMapping("/user/*")
public class UserController {
  
 @Resource(name="userService")
 private UserService userService;
 private final String LIST="redirect:/detail";
  
  /**
     * 登陸
     * @param user
     * @param session
     * @return
     */
    @RequestMapping("/login")
    public ModelAndView login(@Valid User user,BindingResult result,HttpSession session) throws Exception{
      if(!result.hasErrors()){
        User loginUser=userService.login(user);
        if(loginUser!=null){
            session.setAttribute("USER", loginUser);
            return new ModelAndView(LIST);
        }else{
            return new ModelAndView("redirect:/");
        }
      }else{
          ModelAndView view=new ModelAndView();
          view.setViewName("redirect:/");
          view.addObject("error", result.getAllErrors());
          return view;
      }
    }
    
    /**
     * 跳轉至加入頁
     * @return
     */
    @RequestMapping(value="/toAdd",method=RequestMethod.GET)
    public ModelAndView toAdd(){
        return new ModelAndView("user/add");
    }
    /**
     * 保存
     * @param user
     * @return
     */
    @RequestMapping(value="/add",method=RequestMethod.POST)
    public ModelAndView add(@Valid User user,BindingResult result) throws Exception{
        if(result.hasErrors()){
            return new ModelAndView("user/add","error", result.getAllErrors());
        }else{
            userService.addUser(user);
            return new ModelAndView(LIST);   
        }
    }
    /**
     * 依據ID刪除
     * @param id
     * @return
     */
    @RequestMapping(value="/delete/{id}")
    public ModelAndView delete(@PathVariable int id) throws Exception{
        userService.deleteUser(id);
        return new ModelAndView(LIST);
    }
    /**
     * 跳轉至編輯頁面
     * @param id
     * @return
     */
    @RequestMapping(value="/edit/{id}")
    public ModelAndView edit(@PathVariable int id) throws Exception{
        User user=userService.getUserById(id);
        return new ModelAndView("user/edit","user",user);
    }
    /**
     * 編輯
     * @param user
     * @return
     */
    @RequestMapping(value="/edit")
    public ModelAndView update(@Valid User user,BindingResult result)throws Exception{
        ModelAndView view=new ModelAndView();
        if(result.hasErrors()){
            view.addObject("error", result.getAllErrors());
            view.setViewName("user/edit");
            return view;
        }else{
         userService.updateUser(user);
         return new ModelAndView(LIST);
        }
    }
}

(5)test(Java環境下測試)

   TestUserController.java


文章來自:http://www.osblog.net/blog/580.html

相關文章
相關標籤/搜索