zoukankan      html  css  js  c++  java
  • springMVC 注解版

    http://blog.csdn.net/liuxiit/article/details/5756115
    http://blog.csdn.net/hantiannan/article/category/711713

    关于Spring MVC注解 @Transactional 事务标签 @InitBinder 标签

    分类: Java开发 源代码分享 7721人阅读 评论(2) 收藏 举报
    主要用到了spring-aop-2.5.6.jar的AOP支持包! 

    之前我们在AccountService中加入了注解@Transactional标签,但是要想要真正发挥事务作用,还需要一些配置。 
    主要需要调整dao.xml文件 
    dao.xml-事务管理
    Xml代码 复制代码
    1. <bean  
    2.     id="transactionManager"  
    3.     class="org.springframework.jdbc.datasource.DataSourceTransactionManager"  
    4.     p:dataSource-ref="dataSource" />  
    5. <tx:annotation-driven  
    6.     transaction-manager="transactionManager" />  
    [xml] view plaincopy
     
    1. <bean  
    2.     id="transactionManager"  
    3.     class="org.springframework.jdbc.datasource.DataSourceTransactionManager"  
    4.     p:dataSource-ref="dataSource" />  
    5. <tx:annotation-driven  
    6.     transaction-manager="transactionManager" />  
    [xml] view plaincopy
     
    1. <bean  
    2.     id="transactionManager"  
    3.     class="org.springframework.jdbc.datasource.DataSourceTransactionManager"  
    4.     p:dataSource-ref="dataSource" />  
    5. <tx:annotation-driven  
    6.     transaction-manager="transactionManager" />  


    细化一下AccountService接口方法 
    AccountService.java

    Java代码 复制代码
    1. /**  
    2.  * 2010-1-23  
    3.  */  
    4. package org.zlex.spring.service;   
    5.   
    6. import org.springframework.dao.DataAccessException;   
    7. import org.springframework.transaction.annotation.Transactional;   
    8. import org.zlex.spring.domain.Account;   
    9.   
    10. /**  
    11.  * 账户业务接口  
    12.  *   
    13.  * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a>  
    14.  * @version 1.0  
    15.  * @since 1.0  
    16.  */  
    17. public interface AccountService {   
    18.   
    19.     /**  
    20.      * 获得账户  
    21.      *   
    22.      * @param username  
    23.      * @param password  
    24.      * @return  
    25.      */  
    26.     @Transactional(readOnly = true)   
    27.     Account read(String username, String password);   
    28.   
    29.     /**  
    30.      * 获得账户  
    31.      *   
    32.      * @param id  
    33.      * @return  
    34.      */  
    35.     @Transactional(readOnly = true)   
    36.     Account read(int id);   
    37.   
    38.     /**  
    39.      * 注册用户  
    40.      *   
    41.      * @param account  
    42.      * @return  
    43.      */  
    44.     @Transactional(readOnly = false, rollbackFor = DataAccessException.class)   
    45.     Account register(Account account);   
    46. }  
    [java] view plaincopy
     
    1. /** 
    2.  * 2010-1-23 
    3.  */  
    4. package org.zlex.spring.service;  
    5.   
    6. import org.springframework.dao.DataAccessException;  
    7. import org.springframework.transaction.annotation.Transactional;  
    8. import org.zlex.spring.domain.Account;  
    9.   
    10. /** 
    11.  * 账户业务接口 
    12.  *  
    13.  * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a> 
    14.  * @version 1.0 
    15.  * @since 1.0 
    16.  */  
    17. public interface AccountService {  
    18.   
    19.     /** 
    20.      * 获得账户 
    21.      *  
    22.      * @param username 
    23.      * @param password 
    24.      * @return 
    25.      */  
    26.     @Transactional(readOnly = true)  
    27.     Account read(String username, String password);  
    28.   
    29.     /** 
    30.      * 获得账户 
    31.      *  
    32.      * @param id 
    33.      * @return 
    34.      */  
    35.     @Transactional(readOnly = true)  
    36.     Account read(int id);  
    37.   
    38.     /** 
    39.      * 注册用户 
    40.      *  
    41.      * @param account 
    42.      * @return 
    43.      */  
    44.     @Transactional(readOnly = false, rollbackFor = DataAccessException.class)  
    45.     Account register(Account account);  
    46. }  
    [java] view plaincopy
     
    1. /** 
    2.  * 2010-1-23 
    3.  */  
    4. package org.zlex.spring.service;  
    5.   
    6. import org.springframework.dao.DataAccessException;  
    7. import org.springframework.transaction.annotation.Transactional;  
    8. import org.zlex.spring.domain.Account;  
    9.   
    10. /** 
    11.  * 账户业务接口 
    12.  *  
    13.  * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a> 
    14.  * @version 1.0 
    15.  * @since 1.0 
    16.  */  
    17. public interface AccountService {  
    18.   
    19.     /** 
    20.      * 获得账户 
    21.      *  
    22.      * @param username 
    23.      * @param password 
    24.      * @return 
    25.      */  
    26.     @Transactional(readOnly = true)  
    27.     Account read(String username, String password);  
    28.   
    29.     /** 
    30.      * 获得账户 
    31.      *  
    32.      * @param id 
    33.      * @return 
    34.      */  
    35.     @Transactional(readOnly = true)  
    36.     Account read(int id);  
    37.   
    38.     /** 
    39.      * 注册用户 
    40.      *  
    41.      * @param account 
    42.      * @return 
    43.      */  
    44.     @Transactional(readOnly = false, rollbackFor = DataAccessException.class)  
    45.     Account register(Account account);  
    46. }  


    这里我把注解@Transactional调整到了具体的方法上,也就是说这样写的话,凡是加入注解的标注的方法都属于事务配置! 
    Account register(Account account);用做用户注册作用! 
    @Transactional(readOnly = true)只读属性 
    @Transactional(readOnly = false, rollbackFor = DataAccessException.class)只读关闭,遇到DataAccessException异常回滚!如果不对异常进行处理,该异常将一直向上层抛出,直至抛出到页面! 
    如果你的Eclipse集成了SpringIDE,你可以观察一下这时的xml配置文件和AccoutServiceImpl.java的变化! 
     
     
    这次,来个用户注册功能演示,故意在某个位置制造一个异常,看看是否正常回滚! 
    先看注册控制器 
    RegisterController.java

    Java代码 复制代码
    1. /**  
    2.  * 2010-2-4  
    3.  */  
    4. package org.zlex.spring.controller;   
    5.   
    6. import java.text.DateFormat;   
    7. import java.text.SimpleDateFormat;   
    8. import java.util.Date;   
    9.   
    10. import org.springframework.beans.factory.annotation.Autowired;   
    11. import org.springframework.beans.propertyeditors.CustomDateEditor;   
    12. import org.springframework.stereotype.Controller;   
    13. import org.springframework.ui.ModelMap;   
    14. import org.springframework.web.bind.WebDataBinder;   
    15. import org.springframework.web.bind.annotation.InitBinder;   
    16. import org.springframework.web.bind.annotation.ModelAttribute;   
    17. import org.springframework.web.bind.annotation.RequestMapping;   
    18. import org.springframework.web.bind.annotation.RequestMethod;   
    19. import org.zlex.spring.domain.Account;   
    20. import org.zlex.spring.service.AccountService;   
    21.   
    22. /**  
    23.  * 用户注册控制器  
    24.  *   
    25.  * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a>  
    26.  * @version 1.0  
    27.  * @since 1.0  
    28.  */  
    29. @Controller  
    30. @RequestMapping(value = "/register.do")   
    31. public class RegisterController {   
    32.   
    33.     @Autowired  
    34.     private AccountService accountService;   
    35.   
    36.     @InitBinder  
    37.     public void initBinder(WebDataBinder binder) {   
    38.         // 忽略字段绑定异常   
    39.         // binder.setIgnoreInvalidFields(true);   
    40.   
    41.         DateFormat format = new SimpleDateFormat("yyyy-MM-dd");   
    42.         binder.registerCustomEditor(Date.class"birthday",   
    43.                 new CustomDateEditor(format, true));   
    44.     }   
    45.   
    46.     @RequestMapping(method = RequestMethod.GET)   
    47.     public String initForm(ModelMap model) {   
    48.         Account account = new Account();   
    49.         model.addAttribute("account", account);   
    50.         // 直接跳转到登录页面   
    51.         return "account/register";   
    52.     }   
    53.   
    54.     @RequestMapping(method = RequestMethod.POST)   
    55.     protected String submit(@ModelAttribute("account") Account account) {   
    56.         int id = accountService.register(account).getId();   
    57.         // 跳转到用户信息页面   
    58.         return "redirect:profile.do?id=" + id;   
    59.     }   
    60. }  
    [java] view plaincopy
     
    1. /** 
    2.  * 2010-2-4 
    3.  */  
    4. package org.zlex.spring.controller;  
    5.   
    6. import java.text.DateFormat;  
    7. import java.text.SimpleDateFormat;  
    8. import java.util.Date;  
    9.   
    10. import org.springframework.beans.factory.annotation.Autowired;  
    11. import org.springframework.beans.propertyeditors.CustomDateEditor;  
    12. import org.springframework.stereotype.Controller;  
    13. import org.springframework.ui.ModelMap;  
    14. import org.springframework.web.bind.WebDataBinder;  
    15. import org.springframework.web.bind.annotation.InitBinder;  
    16. import org.springframework.web.bind.annotation.ModelAttribute;  
    17. import org.springframework.web.bind.annotation.RequestMapping;  
    18. import org.springframework.web.bind.annotation.RequestMethod;  
    19. import org.zlex.spring.domain.Account;  
    20. import org.zlex.spring.service.AccountService;  
    21.   
    22. /** 
    23.  * 用户注册控制器 
    24.  *  
    25.  * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a> 
    26.  * @version 1.0 
    27.  * @since 1.0 
    28.  */  
    29. @Controller  
    30. @RequestMapping(value = "/register.do")  
    31. public class RegisterController {  
    32.   
    33.     @Autowired  
    34.     private AccountService accountService;  
    35.   
    36.     @InitBinder  
    37.     public void initBinder(WebDataBinder binder) {  
    38.         // 忽略字段绑定异常   
    39.         // binder.setIgnoreInvalidFields(true);   
    40.   
    41.         DateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
    42.         binder.registerCustomEditor(Date.class"birthday",  
    43.                 new CustomDateEditor(format, true));  
    44.     }  
    45.   
    46.     @RequestMapping(method = RequestMethod.GET)  
    47.     public String initForm(ModelMap model) {  
    48.         Account account = new Account();  
    49.         model.addAttribute("account", account);  
    50.         // 直接跳转到登录页面   
    51.         return "account/register";  
    52.     }  
    53.   
    54.     @RequestMapping(method = RequestMethod.POST)  
    55.     protected String submit(@ModelAttribute("account") Account account) {  
    56.         int id = accountService.register(account).getId();  
    57.         // 跳转到用户信息页面   
    58.         return "redirect:profile.do?id=" + id;  
    59.     }  
    60. }  
    [java] view plaincopy
     
    1. /** 
    2.  * 2010-2-4 
    3.  */  
    4. package org.zlex.spring.controller;  
    5.   
    6. import java.text.DateFormat;  
    7. import java.text.SimpleDateFormat;  
    8. import java.util.Date;  
    9.   
    10. import org.springframework.beans.factory.annotation.Autowired;  
    11. import org.springframework.beans.propertyeditors.CustomDateEditor;  
    12. import org.springframework.stereotype.Controller;  
    13. import org.springframework.ui.ModelMap;  
    14. import org.springframework.web.bind.WebDataBinder;  
    15. import org.springframework.web.bind.annotation.InitBinder;  
    16. import org.springframework.web.bind.annotation.ModelAttribute;  
    17. import org.springframework.web.bind.annotation.RequestMapping;  
    18. import org.springframework.web.bind.annotation.RequestMethod;  
    19. import org.zlex.spring.domain.Account;  
    20. import org.zlex.spring.service.AccountService;  
    21.   
    22. /** 
    23.  * 用户注册控制器 
    24.  *  
    25.  * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a> 
    26.  * @version 1.0 
    27.  * @since 1.0 
    28.  */  
    29. @Controller  
    30. @RequestMapping(value = "/register.do")  
    31. public class RegisterController {  
    32.   
    33.     @Autowired  
    34.     private AccountService accountService;  
    35.   
    36.     @InitBinder  
    37.     public void initBinder(WebDataBinder binder) {  
    38.         // 忽略字段绑定异常  
    39.         // binder.setIgnoreInvalidFields(true);  
    40.   
    41.         DateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
    42.         binder.registerCustomEditor(Date.class"birthday",  
    43.                 new CustomDateEditor(format, true));  
    44.     }  
    45.   
    46.     @RequestMapping(method = RequestMethod.GET)  
    47.     public String initForm(ModelMap model) {  
    48.         Account account = new Account();  
    49.         model.addAttribute("account", account);  
    50.         // 直接跳转到登录页面  
    51.         return "account/register";  
    52.     }  
    53.   
    54.     @RequestMapping(method = RequestMethod.POST)  
    55.     protected String submit(@ModelAttribute("account") Account account) {  
    56.         int id = accountService.register(account).getId();  
    57.         // 跳转到用户信息页面  
    58.         return "redirect:profile.do?id=" + id;  
    59.     }  
    60. }  


    @InitBinder用于表单自定义属性绑定。这里我们要求输入一个日期格式的生日。 
    @RequestMapping(method = RequestMethod.GET)用于初始化页面。 
    @RequestMapping(method = RequestMethod.POST)用于提交页面。 
    再看注册页面 
    register.jsp

    Jsp代码 复制代码
    1. <html>   
    2. <head>   
    3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">   
    4. <title>注册</title>   
    5. <link rel="stylesheet" type="text/css" href="css/style.css" />   
    6. <script type="text/javascript" src="js/calendar.js"></script>   
    7. </head>   
    8. <body>   
    9. <fieldset><legend>用户注册</legend><form:form   
    10.     commandName="account">   
    11.     <ul>   
    12.         <li><form:label path="username">用户名:</form:label><form:input   
    13.             path="username" /></li>   
    14.         <li><form:label path="password">密码:</form:label><form:password   
    15.             path="password" /></li>   
    16.         <li><form:label path="birthday">生日:</form:label><form:input   
    17.             path="birthday" onfocus="showDate(this);" /></li>   
    18.         <li><form:label path="email">Email:</form:label><form:input   
    19.             path="email" /></li>   
    20.         <li>   
    21.         <button type="submit">注册</button>   
    22.         <button type="reset">重置</button>   
    23.         </li>   
    24.     </ul>   
    25. </form:form></fieldset>   
    26. </body>   
    27. </html>  


    这里我用了一个JavaScript日期控制标签:

    Html代码 复制代码
    1. <script type="text/javascript" src="js/calendar.js"></script>  
    [html] view plaincopy
     
    1. <script type="text/javascript" src="js/calendar.js"></script>  
    [html] view plaincopy
     
    1. <script type="text/javascript" src="js/calendar.js"></script>  


    使用起来就像是这样: 
     
    非常好用!!! 当然,你完全可以使用JE上的那个JS控件! 
    接下来稍微调整一下AccountService接口及其实现AccountServiceImpl 
    AccountService.java

    Java代码 复制代码
    1. public interface AccountService {   
    2.     // 省略   
    3.     /**  
    4.      * 注册用户  
    5.      *   
    6.      * @param account  
    7.      * @return  
    8.      */  
    9.     @Transactional(readOnly = false, rollbackFor = DataAccessException.class)   
    10.     Account register(Account account);   
    11.     // 省略   
    12. }  
    [java] view plaincopy
     
    1. public interface AccountService {  
    2.     // 省略   
    3.     /** 
    4.      * 注册用户 
    5.      *  
    6.      * @param account 
    7.      * @return 
    8.      */  
    9.     @Transactional(readOnly = false, rollbackFor = DataAccessException.class)  
    10.     Account register(Account account);  
    11.     // 省略   
    12. }  
    [java] view plaincopy
     
    1. public interface AccountService {  
    2.     // 省略  
    3.     /** 
    4.      * 注册用户 
    5.      *  
    6.      * @param account 
    7.      * @return 
    8.      */  
    9.     @Transactional(readOnly = false, rollbackFor = DataAccessException.class)  
    10.     Account register(Account account);  
    11.     // 省略  
    12. }  
    Java代码 复制代码
    1. @Service  
    2. public class AccountServiceImpl implements AccountService {   
    3.   
    4.     @Autowired  
    5.     private AccountDao accountDao;   
    6.   
    7.     // 省略   
    8.   
    9.     @Override  
    10.     public Account register(Account account) {   
    11.         accountDao.create(account);   
    12.         return accountDao.read(account.getUsername());   
    13.     }   
    14. }  
    [java] view plaincopy
     
    1. @Service  
    2. public class AccountServiceImpl implements AccountService {  
    3.   
    4.     @Autowired  
    5.     private AccountDao accountDao;  
    6.   
    7.     // 省略   
    8.   
    9.     @Override  
    10.     public Account register(Account account) {  
    11.         accountDao.create(account);  
    12.         return accountDao.read(account.getUsername());  
    13.     }  
    14. }  
    [java] view plaincopy
     
    1. @Service  
    2. public class AccountServiceImpl implements AccountService {  
    3.   
    4.     @Autowired  
    5.     private AccountDao accountDao;  
    6.   
    7.     // 省略  
    8.   
    9.     @Override  
    10.     public Account register(Account account) {  
    11.         accountDao.create(account);  
    12.         return accountDao.read(account.getUsername());  
    13.     }  
    14. }  


    为了在插入一条记录后获得当前用户的主键,我们还得这么玩! 的确有点雷人~ 
    从架构考虑,这是符合业务要求的实现!如果用iBatis或者Hibernate,这个问题就有数据库一次IO处理完成了! 
    再看看AccountDao接口及其实现AccountDaoImpl 
    AccountDao.java

    Java代码 复制代码
    1. public interface AccountDao {   
    2.         // 省略   
    3.     /**  
    4.      * 构建用户记录  
    5.      *   
    6.      * @param account  
    7.      * @return  
    8.      */  
    9.     void create(Account account);   
    10. }  
    [java] view plaincopy
     
    1. public interface AccountDao {  
    2.         // 省略   
    3.     /** 
    4.      * 构建用户记录 
    5.      *  
    6.      * @param account 
    7.      * @return 
    8.      */  
    9.     void create(Account account);  
    10. }  
    [java] view plaincopy
     
    1. public interface AccountDao {  
    2.         // 省略  
    3.     /** 
    4.      * 构建用户记录 
    5.      *  
    6.      * @param account 
    7.      * @return 
    8.      */  
    9.     void create(Account account);  
    10. }  



    AccountDaoImpl.java

    Java代码 复制代码
    1. @Repository  
    2. public class AccountDaoImpl implements AccountDao {   
    3.         // 省略   
    4.   
    5.     @Override  
    6.     public void create(Account account) {   
    7.         String sql = "INSERT INTO account(username, password, birthday, email) VALUES(?,?,?,?)";   
    8.   
    9.         jdbcTemplate.update(sql, new Object[] { account.getUsername(),   
    10.                 account.getPassword(), account.getBirthday(),   
    11.                 account.getEmail() });   
    12.     }   
    13. }  
    [java] view plaincopy
     
    1. @Repository  
    2. public class AccountDaoImpl implements AccountDao {  
    3.         // 省略   
    4.   
    5.     @Override  
    6.     public void create(Account account) {  
    7.         String sql = "INSERT INTO account(username, password, birthday, email) VALUES(?,?,?,?)";  
    8.   
    9.         jdbcTemplate.update(sql, new Object[] { account.getUsername(),  
    10.                 account.getPassword(), account.getBirthday(),  
    11.                 account.getEmail() });  
    12.     }  
    13. }  
    [java] view plaincopy
     
    1. @Repository  
    2. public class AccountDaoImpl implements AccountDao {  
    3.         // 省略  
    4.   
    5.     @Override  
    6.     public void create(Account account) {  
    7.         String sql = "INSERT INTO account(username, password, birthday, email) VALUES(?,?,?,?)";  
    8.   
    9.         jdbcTemplate.update(sql, new Object[] { account.getUsername(),  
    10.                 account.getPassword(), account.getBirthday(),  
    11.                 account.getEmail() });  
    12.     }  
    13. }  


    来个注册演示! 
    注册: 
     
    信息展示: 
     
    来制造一起事故! 
    先看看数据库目前的状况! 
     
    在AccountDaoImpl中来个破坏!

    Java代码 复制代码
    1. @Override  
    2.     public void create(Account account) {   
    3.         String sql = "INSERT INTO account(username, password, birthday, email) VALUES(?,?,?,?)";   
    4.   
    5.         jdbcTemplate.update(sql, new Object[] { account.getUsername(),   
    6.                 account.getPassword(), account.getBirthday(),   
    7.                 account.getEmail() });   
    8.   
    9.         throw new RecoverableDataAccessException("TEST");   
    10.     }  
    [java] view plaincopy
     
    1. @Override  
    2.     public void create(Account account) {  
    3.         String sql = "INSERT INTO account(username, password, birthday, email) VALUES(?,?,?,?)";  
    4.   
    5.         jdbcTemplate.update(sql, new Object[] { account.getUsername(),  
    6.                 account.getPassword(), account.getBirthday(),  
    7.                 account.getEmail() });  
    8.   
    9.         throw new RecoverableDataAccessException("TEST");  
    10.     }  
    [java] view plaincopy
     
    1. @Override  
    2.     public void create(Account account) {  
    3.         String sql = "INSERT INTO account(username, password, birthday, email) VALUES(?,?,?,?)";  
    4.   
    5.         jdbcTemplate.update(sql, new Object[] { account.getUsername(),  
    6.                 account.getPassword(), account.getBirthday(),  
    7.                 account.getEmail() });  
    8.   
    9.         throw new RecoverableDataAccessException("TEST");  
    10.     }  


    我们强行在执行完Insert语句后抛出DataAccessException异常(RecoverableDataAccessException)! 
    来个注册试试! 
     

    Spring 注解学习手札(五) 业务层事务处理

    博客分类:
    控制器层、持久层都有了一些介绍,剩下的就是业务层了! 
    业务层中的关键问题在于事务控制!Spring的注解式事务处理其实很简单! 

    相关参考: 
    Spring 注解学习手札(一) 构建简单Web应用 
    Spring 注解学习手札(二) 控制层梳理 
    Spring 注解学习手札(三) 表单页面处理 
    Spring 注解学习手札(四) 持久层浅析 
    Spring 注解学习手札(五) 业务层事务处理 
    Spring 注解学习手札(六) 测试 
    Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable 
    Spring 注解学习手札(八) 补遗——@ExceptionHandler 


    这里将用到以下几个包: 
    引用

    aopalliance-1.0.jar 
    commons-collections.jar 
    commons-dbcp.jar 
    commons-logging-1.1.1.jar 
    commons-pool.jar 
    jstl.jar 
    log4j-1.2.15.jar 
    mysql-connector-java-5.1.6-bin.jar 
    spring-aop-2.5.6.jar 
    spring-beans-2.5.6.jar 
    spring-context-2.5.6.jar 
    spring-context-support-2.5.6.jar 
    spring-core-2.5.6.jar 
    spring-jdbc-2.5.6.jar 
    spring-tx-2.5.6.jar 
    spring-web-2.5.6.jar 
    spring-webmvc-2.5.6.jar 
    standard.jar 

    主要增加了spring-aop-2.5.6.jar的AOP支持包! 

    之前我们在AccountService中加入了注解@Transactional标签,但是要想要真正发挥事务作用,还需要一些配置。 
    主要需要调整dao.xml文件 
    dao.xml-事务管理 
    Xml代码  收藏代码
    1. <bean  
    2.     id="transactionManager"  
    3.     class="org.springframework.jdbc.datasource.DataSourceTransactionManager"  
    4.     p:dataSource-ref="dataSource" />  
    5. <tx:annotation-driven  
    6.     transaction-manager="transactionManager" />  

    细化一下AccountService接口方法 
    AccountService.java 
    Java代码  收藏代码
    1. /** 
    2.  * 2010-1-23 
    3.  */  
    4. package org.zlex.spring.service;  
    5.   
    6. import org.springframework.dao.DataAccessException;  
    7. import org.springframework.transaction.annotation.Transactional;  
    8. import org.zlex.spring.domain.Account;  
    9.   
    10. /** 
    11.  * 账户业务接口 
    12.  *  
    13.  * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a> 
    14.  * @version 1.0 
    15.  * @since 1.0 
    16.  */  
    17. public interface AccountService {  
    18.   
    19.     /** 
    20.      * 获得账户 
    21.      *  
    22.      * @param username 
    23.      * @param password 
    24.      * @return 
    25.      */  
    26.     @Transactional(readOnly = true)  
    27.     Account read(String username, String password);  
    28.   
    29.     /** 
    30.      * 获得账户 
    31.      *  
    32.      * @param id 
    33.      * @return 
    34.      */  
    35.     @Transactional(readOnly = true)  
    36.     Account read(int id);  
    37.   
    38.     /** 
    39.      * 注册用户 
    40.      *  
    41.      * @param account 
    42.      * @return 
    43.      */  
    44.     @Transactional(readOnly = false, rollbackFor = DataAccessException.class)  
    45.     Account register(Account account);  
    46. }  

    这里我把注解@Transactional调整到了具体的方法上,也就是说这样写的话,凡是加入注解的标注的方法都属于事务配置! 
    Account register(Account account);用做用户注册作用! 
    @Transactional(readOnly = true)只读属性 
    @Transactional(readOnly = false, rollbackFor = DataAccessException.class)只读关闭,遇到DataAccessException异常回滚!如果不对异常进行处理,该异常将一直向上层抛出,直至抛出到页面! 
    如果你的Eclipse集成了SpringIDE,你可以观察一下这时的xml配置文件和AccoutServiceImpl.java的变化! 
     
     
    这次,来个用户注册功能演示,故意在某个位置制造一个异常,看看是否正常回滚! 
    先看注册控制器 
    RegisterController.java 
    Java代码  收藏代码
    1. /** 
    2.  * 2010-2-4 
    3.  */  
    4. package org.zlex.spring.controller;  
    5.   
    6. import java.text.DateFormat;  
    7. import java.text.SimpleDateFormat;  
    8. import java.util.Date;  
    9.   
    10. import org.springframework.beans.factory.annotation.Autowired;  
    11. import org.springframework.beans.propertyeditors.CustomDateEditor;  
    12. import org.springframework.stereotype.Controller;  
    13. import org.springframework.ui.ModelMap;  
    14. import org.springframework.web.bind.WebDataBinder;  
    15. import org.springframework.web.bind.annotation.InitBinder;  
    16. import org.springframework.web.bind.annotation.ModelAttribute;  
    17. import org.springframework.web.bind.annotation.RequestMapping;  
    18. import org.springframework.web.bind.annotation.RequestMethod;  
    19. import org.zlex.spring.domain.Account;  
    20. import org.zlex.spring.service.AccountService;  
    21.   
    22. /** 
    23.  * 用户注册控制器 
    24.  *  
    25.  * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a> 
    26.  * @version 1.0 
    27.  * @since 1.0 
    28.  */  
    29. @Controller  
    30. @RequestMapping(value = "/register.do")  
    31. public class RegisterController {  
    32.   
    33.     @Autowired  
    34.     private AccountService accountService;  
    35.   
    36.     @InitBinder  
    37.     public void initBinder(WebDataBinder binder) {  
    38.         // 忽略字段绑定异常  
    39.         // binder.setIgnoreInvalidFields(true);  
    40.   
    41.         DateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
    42.         binder.registerCustomEditor(Date.class"birthday",  
    43.                 new CustomDateEditor(format, true));  
    44.     }  
    45.   
    46.     @RequestMapping(method = RequestMethod.GET)  
    47.     public String initForm(ModelMap model) {  
    48.         Account account = new Account();  
    49.         model.addAttribute("account", account);  
    50.         // 直接跳转到登录页面  
    51.         return "account/register";  
    52.     }  
    53.   
    54.     @RequestMapping(method = RequestMethod.POST)  
    55.     protected String submit(@ModelAttribute("account") Account account) {  
    56.         int id = accountService.register(account).getId();  
    57.         // 跳转到用户信息页面  
    58.         return "redirect:profile.do?id=" + id;  
    59.     }  
    60. }  

    @InitBinder用于表单自定义属性绑定。这里我们要求输入一个日期格式的生日。 
    @RequestMapping(method = RequestMethod.GET)用于初始化页面。 
    @RequestMapping(method = RequestMethod.POST)用于提交页面。 
    再看注册页面 
    register.jsp 
    Jsp代码  收藏代码
    1. <html>  
    2. <head>  
    3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    4. <title>注册</title>  
    5. <link rel="stylesheet" type="text/css" href="css/style.css" />  
    6. <script type="text/javascript" src="js/calendar.js"></script>  
    7. </head>  
    8. <body>  
    9. <fieldset><legend>用户注册</legend><form:form  
    10.     commandName="account">  
    11.     <ul>  
    12.         <li><form:label path="username">用户名:</form:label><form:input  
    13.             path="username" /></li>  
    14.         <li><form:label path="password">密码:</form:label><form:password  
    15.             path="password" /></li>  
    16.         <li><form:label path="birthday">生日:</form:label><form:input  
    17.             path="birthday" onfocus="showDate(this);" /></li>  
    18.         <li><form:label path="email">Email:</form:label><form:input  
    19.             path="email" /></li>  
    20.         <li>  
    21.         <button type="submit">注册</button>  
    22.         <button type="reset">重置</button>  
    23.         </li>  
    24.     </ul>  
    25. </form:form></fieldset>  
    26. </body>  
    27. </html>  

    这里我用了一个JavaScript日期控制标签: 
    Html代码  收藏代码
    1. <script type="text/javascript" src="js/calendar.js"></script>  

    使用起来就像是这样: 
     
    非常好用!!! 当然,你完全可以使用JE上的那个JS控件! 
    接下来稍微调整一下AccountService接口及其实现AccountServiceImpl 
    AccountService.java 
    Java代码  收藏代码
    1. public interface AccountService {  
    2.     // 省略  
    3.     /** 
    4.      * 注册用户 
    5.      *  
    6.      * @param account 
    7.      * @return 
    8.      */  
    9.     @Transactional(readOnly = false, rollbackFor = DataAccessException.class)  
    10.     Account register(Account account);  
    11.     // 省略  
    12. }  


    Java代码  收藏代码
    1. @Service  
    2. public class AccountServiceImpl implements AccountService {  
    3.   
    4.     @Autowired  
    5.     private AccountDao accountDao;  
    6.   
    7.     // 省略  
    8.   
    9.     @Override  
    10.     public Account register(Account account) {  
    11.         accountDao.create(account);  
    12.         return accountDao.read(account.getUsername());  
    13.     }  
    14. }  

    为了在插入一条记录后获得当前用户的主键,我们还得这么玩! 的确有点雷人~ 
    从架构考虑,这是符合业务要求的实现!如果用iBatis或者Hibernate,这个问题就有数据库一次IO处理完成了! 
    再看看AccountDao接口及其实现AccountDaoImpl 
    AccountDao.java 
    Java代码  收藏代码
    1. public interface AccountDao {  
    2.         // 省略  
    3.     /** 
    4.      * 构建用户记录 
    5.      *  
    6.      * @param account 
    7.      * @return 
    8.      */  
    9.     void create(Account account);  
    10. }  


    AccountDaoImpl.java 
    Java代码  收藏代码
    1. @Repository  
    2. public class AccountDaoImpl implements AccountDao {  
    3.         // 省略  
    4.   
    5.     @Override  
    6.     public void create(Account account) {  
    7.         String sql = "INSERT INTO account(username, password, birthday, email) VALUES(?,?,?,?)";  
    8.   
    9.         jdbcTemplate.update(sql, new Object[] { account.getUsername(),  
    10.                 account.getPassword(), account.getBirthday(),  
    11.                 account.getEmail() });  
    12.     }  
    13. }  

    来个注册演示! 
    注册: 
     
    信息展示: 
     
    来制造一起事故! 
    先看看数据库目前的状况! 
     
    在AccountDaoImpl中来个破坏! 
    Java代码  收藏代码
    1. @Override  
    2.     public void create(Account account) {  
    3.         String sql = "INSERT INTO account(username, password, birthday, email) VALUES(?,?,?,?)";  
    4.   
    5.         jdbcTemplate.update(sql, new Object[] { account.getUsername(),  
    6.                 account.getPassword(), account.getBirthday(),  
    7.                 account.getEmail() });  
    8.   
    9.         throw new RecoverableDataAccessException("TEST");  
    10.     }  

    我们强行在执行完Insert语句后抛出DataAccessException异常(RecoverableDataAccessException)! 
    来个注册试试! 
     
    点击提交看看返回的异常! 

    异常回滚生效! 
    数据库中当然是什么都没有,我就不废话了! 
    相关实现见附件! 


    相关参考: 
    Spring 注解学习手札(一) 构建简单Web应用 
    Spring 注解学习手札(二) 控制层梳理 
    Spring 注解学习手札(三) 表单页面处理 
    Spring 注解学习手札(四) 持久层浅析 
    Spring 注解学习手札(五) 业务层事务处理 
    Spring 注解学习手札(六) 测试 
    Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable 
    Spring 注解学习手札(八) 补遗——@ExceptionHandler 

    Spring的@RequestBody非常牛x,可以将提交的json直接转换成POJO对象。

    正好今天有这样的需求,使用一下,结果一直报415,十分头疼。

    HTTP 415 错误 – 不支持的媒体类型(Unsupported media type)

    我的angularJs是这样写的

    复制代码
    $http({method: "POST",
        url: url;
        headers: {'Content-type': 'application/json;charset=UTF-8'},
        data: scope.$modelValue})
    .success(function(data, status) {
        // success handle code  
    })
    .error(function(data, status) {
        // error handle code
    });
    复制代码

    url与scope.$modelValue都是项目中的代码,在这里占个坑,scope.$modelValue是一个js对象,会被angularJs转换成json字符串,

    反复看angularJs的文档,又抓包分析,确认js没有问题。

    在网上一查貌似是Spring的问题,有的网友说需要在*-servlet.xml中增加<mvc:annotation-driven />,一看我的项目没加,立刻加上。

    当然还需要加上mvc的xml命名空间,否则该配置无法解析。

    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"

    <mvc:annotation-driven />会自动注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter两个bean

    AnnotationMethodHandlerAdapter将会初始化7个转换器,可以通过调用AnnotationMethodHandlerAdapter的getMessageConverts()方法来获取转换器的一个集合 List<HttpMessageConverter>

    复制代码
    ByteArrayHttpMessageConverter 
    StringHttpMessageConverter 
    ResourceHttpMessageConverter 
    SourceHttpMessageConverter 
    XmlAwareFormHttpMessageConverter 
    Jaxb2RootElementHttpMessageConverter 
    MappingJacksonHttpMessageConverter
    复制代码

    对于json的解析就是通过MappingJacksonHttpMessageConverter转换器完成的。

    只添加<mvc:annotation-driven />还不行,需要在classpath环境中能找到Jackson包,用maven配置如下

    复制代码
     <dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-asl</artifactId>  
            <version>1.9.8</version>  
            <type>jar</type>  
            <scope>compile</scope>  
     </dependency>  
    复制代码

    至此问题解决,附上Spring代码

    复制代码
    @RequestMapping(value = "/testjson", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public void testJson(@RequestBody JsonInfo jsonInfo,
        HttpServletRequest request, HttpServletResponse response)
    {
        //handle jsonInfo object instance
    }
    复制代码

     从下文得到帮助,对作者表示感谢:)

    http://snowolf.iteye.com/blog/1628861

     
    最近需要做些接口服务,服务协议定为JSON,为了整合在Spring中,一开始确实费了很大的劲,经朋友提醒才发现,SpringMVC已经强悍到如此地步,佩服! 

    相关参考: 
    Spring 注解学习手札(一) 构建简单Web应用 
    Spring 注解学习手札(二) 控制层梳理 
    Spring 注解学习手札(三) 表单页面处理 
    Spring 注解学习手札(四) 持久层浅析 
    Spring 注解学习手札(五) 业务层事务处理 
    Spring 注解学习手札(六) 测试 
    Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable 
    Spring 注解学习手札(八) 补遗——@ExceptionHandler 


    SpringMVC层跟JSon结合,几乎不需要做什么配置,代码实现也相当简洁。再也不用为了组装协议而劳烦辛苦了! 

    一、Spring注解@ResponseBody,@RequestBody和HttpMessageConverter 

    Spring 3.X系列增加了新注解@ResponseBody@RequestBody 

    • @RequestBody 将HTTP请求正文转换为适合的HttpMessageConverter对象。
    • @ResponseBody 将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象,写入输出流。

    HttpMessageConverter接口,需要开启<mvc:annotation-driven  />。 
    AnnotationMethodHandlerAdapter将会初始化7个转换器,可以通过调用AnnotationMethodHandlerAdaptergetMessageConverts()方法来获取转换器的一个集合 List<HttpMessageConverter> 
    引用
    ByteArrayHttpMessageConverter 
    StringHttpMessageConverter 
    ResourceHttpMessageConverter 
    SourceHttpMessageConverter 
    XmlAwareFormHttpMessageConverter 
    Jaxb2RootElementHttpMessageConverter 
    MappingJacksonHttpMessageConverter


    可以理解为,只要有对应协议的解析器,你就可以通过几行配置,几个注解完成协议——对象的转换工作! 

    PS:Spring默认的json协议解析由Jackson完成。 

    二、servlet.xml配置 

    Spring的配置文件,简洁到了极致,对于当前这个需求只需要三行核心配置: 
    Xml代码  收藏代码
    1. <context:component-scan base-package="org.zlex.json.controller" />  
    2. <context:annotation-config />  
    3. <mvc:annotation-driven />  


    三、pom.xml配置 

    闲言少叙,先说依赖配置,这里以Json+Spring为参考: 
    pom.xml 
    Xml代码  收藏代码
    1. <dependency>  
    2.         <groupId>org.springframework</groupId>  
    3.         <artifactId>spring-webmvc</artifactId>  
    4.         <version>3.1.2.RELEASE</version>  
    5.         <type>jar</type>  
    6.         <scope>compile</scope>  
    7.     </dependency>  
    8.     <dependency>  
    9.         <groupId>org.codehaus.jackson</groupId>  
    10.         <artifactId>jackson-mapper-asl</artifactId>  
    11.         <version>1.9.8</version>  
    12.         <type>jar</type>  
    13.         <scope>compile</scope>  
    14.     </dependency>  
    15.     <dependency>  
    16.         <groupId>log4j</groupId>  
    17.         <artifactId>log4j</artifactId>  
    18.         <version>1.2.17</version>  
    19.         <scope>compile</scope>  
    20.     </dependency>  

    主要需要spring-webmvcjackson-mapper-asl两个包,其余依赖包Maven会帮你完成。至于log4j,我还是需要看日志嘛。 
    包依赖图: 

    至于版本,看项目需要吧! 

    四、代码实现 

    域对象: 
    Java代码  收藏代码
    1. public class Person implements Serializable {  
    2.   
    3.     private int id;  
    4.     private String name;  
    5.     private boolean status;  
    6.   
    7.     public Person() {  
    8.         // do nothing  
    9.     }  
    10. }  


    这里需要一个空构造,由Spring转换对象时,进行初始化。 

    @ResponseBody,@RequestBody,@PathVariable 
    控制器: 
    Java代码  收藏代码
    1. @Controller  
    2. public class PersonController {  
    3.   
    4.     /** 
    5.      * 查询个人信息 
    6.      *  
    7.      * @param id 
    8.      * @return 
    9.      */  
    10.     @RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)  
    11.     public @ResponseBody  
    12.     Person porfile(@PathVariable int id, @PathVariable String name,  
    13.             @PathVariable boolean status) {  
    14.         return new Person(id, name, status);  
    15.     }  
    16.   
    17.     /** 
    18.      * 登录 
    19.      *  
    20.      * @param person 
    21.      * @return 
    22.      */  
    23.     @RequestMapping(value = "/person/login", method = RequestMethod.POST)  
    24.     public @ResponseBody  
    25.     Person login(@RequestBody Person person) {  
    26.         return person;  
    27.     }  
    28. }  


    备注:@RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)中的{id}/{name}/{status}@PathVariable int id, @PathVariable String name,@PathVariable boolean status一一对应,按名匹配。 这是restful式风格。 
    如果映射名称有所不一,可以参考如下方式: 

    Java代码  收藏代码
    1. @RequestMapping(value = "/person/profile/{id}", method = RequestMethod.GET)  
    2. public @ResponseBody  
    3. Person porfile(@PathVariable("id"int uid) {  
    4.     return new Person(uid, name, status);  
    5. }  


    • GET模式下,这里使用了@PathVariable绑定输入参数,非常适合Restful风格。因为隐藏了参数与路径的关系,可以提升网站的安全性,静态化页面,降低恶意攻击风险。
    • POST模式下,使用@RequestBody绑定请求对象,Spring会帮你进行协议转换,将Json、Xml协议转换成你需要的对象。
    • @ResponseBody可以标注任何对象,由Srping完成对象——协议的转换。


    做个页面测试下: 
    JS 
    Js代码  收藏代码
    1. $(document).ready(function() {  
    2.     $("#profile").click(function() {  
    3.         profile();  
    4.     });  
    5.     $("#login").click(function() {  
    6.         login();  
    7.     });  
    8. });  
    9. function profile() {  
    10.     var url = 'http://localhost:8080/spring-json/json/person/profile/';  
    11.     var query = $('#id').val() + '/' + $('#name').val() + '/'  
    12.             + $('#status').val();  
    13.     url += query;  
    14.     alert(url);  
    15.     $.get(url, function(data) {  
    16.         alert("id: " + data.id + " name: " + data.name + " status: "  
    17.                 + data.status);  
    18.     });  
    19. }  
    20. function login() {  
    21.     var mydata = '{"name":"' + $('#name').val() + '","id":"'  
    22.             + $('#id').val() + '","status":"' + $('#status').val() + '"}';  
    23.     alert(mydata);  
    24.     $.ajax({  
    25.         type : 'POST',  
    26.         contentType : 'application/json',  
    27.         url : 'http://localhost:8080/spring-json/json/person/login',  
    28.         processData : false,  
    29.         dataType : 'json',  
    30.         data : mydata,  
    31.         success : function(data) {  
    32.             alert("id: " + data.id + " name: " + data.name + " status: "  
    33.                     + data.status);  
    34.         },  
    35.         error : function() {  
    36.             alert('Err...');  
    37.         }  
    38.     });  

    Table 
    Html代码  收藏代码
    1. <table>  
    2.     <tr>  
    3.         <td>id</td>  
    4.         <td><input id="id" value="100" /></td>  
    5.     </tr>  
    6.     <tr>  
    7.         <td>name</td>  
    8.         <td><input id="name" value="snowolf" /></td>  
    9.     </tr>  
    10.     <tr>  
    11.         <td>status</td>  
    12.         <td><input id="status" value="true" /></td>  
    13.     </tr>  
    14.     <tr>  
    15.         <td><input type="button" id="profile" value="Profile——GET" /></td>  
    16.         <td><input type="button" id="login" value="Login——POST" /></td>  
    17.     </tr>  
    18. </table>  


    四、简单测试 

    Get方式测试: 




    Post方式测试: 




    五、常见错误 
    POST操作时,我用$.post()方式,屡次失败,一直报各种异常: 


    引用
    org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported 
    org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported 
    org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

    直接用$.post()直接请求会有点小问题,尽管我标识为json协议,但实际上提交的ContentType还是application/x-www-form-urlencoded。需要使用$.ajaxSetup()标示下ContentType。 
    Js代码  收藏代码
    1. function login() {  
    2.     var mydata = '{"name":"' + $('#name').val() + '","id":"'  
    3.             + $('#id').val() + '","status":"' + $('#status').val() + '"}';  
    4.     alert(mydata);  
    5.     $.ajaxSetup({  
    6.         contentType : 'application/json'  
    7.     });  
    8.     $.post('http://localhost:8080/spring-json/json/person/login', mydata,  
    9.             function(data) {  
    10.                 alert("id: " + data.id + " name: " + data.name  
    11.                         + " status: " + data.status);  
    12.             }, 'json');  
    13. };  

    效果是一样! 

    详见附件! 

    相关参考: 
    Spring 注解学习手札(一) 构建简单Web应用 
    Spring 注解学习手札(二) 控制层梳理 
    Spring 注解学习手札(三) 表单页面处理 
    Spring 注解学习手札(四) 持久层浅析 
    Spring 注解学习手札(五) 业务层事务处理 
    Spring 注解学习手札(六) 测试 
    Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable 
    Spring 注解学习手札(八) 补遗——@ExceptionHandler 

     

     

    @RequestParam @RequestBody @PathVariable 等参数绑定注解详解(转)

    引言:

    接上一篇文章,对@RequestMapping进行地址映射讲解之后,该篇主要讲解request 数据到handler method 参数数据的绑定所用到的注解和什么情形下使用;

    简介:

    handler method 参数绑定常用的注解,我们根据他们处理的Request的不同内容部分分为四类:(主要讲解常用类型)

    A、处理requet uri 部分(这里指uri template中variable,不含queryString部分)的注解:   @PathVariable;

    B、处理request header部分的注解:   @RequestHeader, @CookieValue;

    C、处理request body部分的注解:@RequestParam,  @RequestBody;

    D、处理attribute类型是注解: @SessionAttributes, @ModelAttribute;

    1、 @PathVariable 

    当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId}, 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。

    示例代码:

    复制代码
    @Controller
    @RequestMapping("/owners/{ownerId}")
    public class RelativePathUriTemplateController {
    
      @RequestMapping("/pets/{petId}")
      public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    
        // implementation omitted
      }
    }
    复制代码

    上面代码把URI template 中变量 ownerId的值和petId的值,绑定到方法的参数上。若方法参数名称和需要绑定的uri template中变量名称不一致,需要在@PathVariable("name")指定uri template中的名称。

    2、 @RequestHeader、@CookieValue

    @RequestHeader 注解,可以把Request请求header部分的值绑定到方法的参数上。

    示例代码:

    这是一个Request 的header部分:

    Host                    localhost:8080
    Accept                  text/html,application/xhtml+xml,application/xml;q=0.9
    Accept-Language         fr,en-gb;q=0.7,en;q=0.3
    Accept-Encoding         gzip,deflate
    Accept-Charset          ISO-8859-1,utf-8;q=0.7,*;q=0.7
    Keep-Alive              300
    复制代码
    @RequestMapping("/displayHeaderInfo.do")
    public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
                                  @RequestHeader("Keep-Alive") long keepAlive)  {
    
      //...
    
    }
    复制代码

    上面的代码,把request header部分的 Accept-Encoding的值,绑定到参数encoding上了, Keep-Alive header的值绑定到参数keepAlive上。

    @CookieValue 可以把Request header中关于cookie的值绑定到方法的参数上。

    例如有如下Cookie值:

    JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84

    参数绑定的代码:

    @RequestMapping("/displayHeaderInfo.do")
    public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie)  {
    
      //...
    
    }

    即把JSESSIONID的值绑定到参数cookie上。

    3、@RequestParam, @RequestBody

    @RequestParam 

    A) 常用来处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况( String--> 简单类型的转换操作由ConversionService配置的转换器来完成);因为使用request.getParameter()方式获取参数,所以可以处理get 方式中queryString的值,也可以处理post方式中 body data的值;

    B)用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST;

    C) 该注解有两个属性: value、required; value用来指定要传入值的id名称,required用来指示参数是否必须绑定;

    示例代码:

    复制代码
    @Controller
    @RequestMapping("/pets")
    @SessionAttributes("pet")
    public class EditPetForm {
    
        // ...
    
        @RequestMapping(method = RequestMethod.GET)
        public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
            Pet pet = this.clinic.loadPet(petId);
            model.addAttribute("pet", pet);
            return "petForm";
        }
    
        // ...
    复制代码

    @RequestBody

    该注解常用来处理Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;

    它是通过使用HandlerAdapter 配置的HttpMessageConverters来解析post data body,然后绑定到相应的bean上的。

    因为配置有FormHttpMessageConverter,所以也可以用来处理 application/x-www-form-urlencoded的内容,处理完的结果放在一个MultiValueMap<String, String>里,这种情况在某些特殊需求下使用,详情查看FormHttpMessageConverter api;

    示例代码:

    @RequestMapping(value = "/something", method = RequestMethod.PUT)
    public void handle(@RequestBody String body, Writer writer) throws IOException {
      writer.write(body);
    }

    4、@SessionAttributes, @ModelAttribute

    @SessionAttributes:

    该注解用来绑定HttpSession中的attribute对象的值,便于在方法中的参数里使用。

    该注解有value、types两个属性,可以通过名字和类型指定要使用的attribute 对象;

    示例代码:

    @Controller
    @RequestMapping("/editPet.do")
    @SessionAttributes("pet")
    public class EditPetForm {
        // ...
    }

    @ModelAttribute

    该注解有两个用法,一个是用于方法上,一个是用于参数上;

    用于方法上时:  通常用来在处理@RequestMapping之前,为请求绑定需要从后台查询的model;

    用于参数上时: 用来通过名称对应,把相应名称的值绑定到注解的参数bean上;要绑定的值来源于:

    A) @SessionAttributes 启用的attribute 对象上;

    B) @ModelAttribute 用于方法上时指定的model对象;

    C) 上述两种情况都没有时,new一个需要绑定的bean对象,然后把request中按名称对应的方式把值绑定到bean中。

    用到方法上@ModelAttribute的示例代码:

    复制代码
    // Add one attribute
    // The return value of the method is added to the model under the name "account"
    // You can customize the name via @ModelAttribute("myAccount")
    
    @ModelAttribute
    public Account addAccount(@RequestParam String number) {
        return accountManager.findAccount(number);
    }
    复制代码

    这种方式实际的效果就是在调用@RequestMapping的方法之前,为request对象的model里put(“account”, Account);

    用在参数上的@ModelAttribute示例代码:

    @RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute Pet pet) {
       
    }

    首先查询 @SessionAttributes有无绑定的Pet对象,若没有则查询@ModelAttribute方法层面上是否绑定了Pet对象,若没有则将URI template中的值按对应的名称绑定到Pet对象的各属性上。

    补充讲解:

    问题: 在不给定注解的情况下,参数是怎样绑定的?

    通过分析AnnotationMethodHandlerAdapter和RequestMappingHandlerAdapter的源代码发现,方法的参数在不给定参数的情况下:

    若要绑定的对象时简单类型:  调用@RequestParam来处理的。  

    若要绑定的对象时复杂类型:  调用@ModelAttribute来处理的。

    这里的简单类型指java的原始类型(boolean, int 等)、原始类型对象(Boolean, Int等)、String、Date等ConversionService里可以直接String转换成目标对象的类型;

    下面贴出AnnotationMethodHandlerAdapter中绑定参数的部分源代码:

    复制代码
    private Object[] resolveHandlerArguments(Method handlerMethod, Object handler,
                NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception {
    
            Class[] paramTypes = handlerMethod.getParameterTypes();
            Object[] args = new Object[paramTypes.length];
    
            for (int i = 0; i < args.length; i++) {
                MethodParameter methodParam = new MethodParameter(handlerMethod, i);
                methodParam.initParameterNameDiscovery(this.parameterNameDiscoverer);
                GenericTypeResolver.resolveParameterType(methodParam, handler.getClass());
                String paramName = null;
                String headerName = null;
                boolean requestBodyFound = false;
                String cookieName = null;
                String pathVarName = null;
                String attrName = null;
                boolean required = false;
                String defaultValue = null;
                boolean validate = false;
                Object[] validationHints = null;
                int annotationsFound = 0;
                Annotation[] paramAnns = methodParam.getParameterAnnotations();
    
                for (Annotation paramAnn : paramAnns) {
                    if (RequestParam.class.isInstance(paramAnn)) {
                        RequestParam requestParam = (RequestParam) paramAnn;
                        paramName = requestParam.value();
                        required = requestParam.required();
                        defaultValue = parseDefaultValueAttribute(requestParam.defaultValue());
                        annotationsFound++;
                    }
                    else if (RequestHeader.class.isInstance(paramAnn)) {
                        RequestHeader requestHeader = (RequestHeader) paramAnn;
                        headerName = requestHeader.value();
                        required = requestHeader.required();
                        defaultValue = parseDefaultValueAttribute(requestHeader.defaultValue());
                        annotationsFound++;
                    }
                    else if (RequestBody.class.isInstance(paramAnn)) {
                        requestBodyFound = true;
                        annotationsFound++;
                    }
                    else if (CookieValue.class.isInstance(paramAnn)) {
                        CookieValue cookieValue = (CookieValue) paramAnn;
                        cookieName = cookieValue.value();
                        required = cookieValue.required();
                        defaultValue = parseDefaultValueAttribute(cookieValue.defaultValue());
                        annotationsFound++;
                    }
                    else if (PathVariable.class.isInstance(paramAnn)) {
                        PathVariable pathVar = (PathVariable) paramAnn;
                        pathVarName = pathVar.value();
                        annotationsFound++;
                    }
                    else if (ModelAttribute.class.isInstance(paramAnn)) {
                        ModelAttribute attr = (ModelAttribute) paramAnn;
                        attrName = attr.value();
                        annotationsFound++;
                    }
                    else if (Value.class.isInstance(paramAnn)) {
                        defaultValue = ((Value) paramAnn).value();
                    }
                    else if (paramAnn.annotationType().getSimpleName().startsWith("Valid")) {
                        validate = true;
                        Object value = AnnotationUtils.getValue(paramAnn);
                        validationHints = (value instanceof Object[] ? (Object[]) value : new Object[] {value});
                    }
                }
    
                if (annotationsFound > 1) {
                    throw new IllegalStateException("Handler parameter annotations are exclusive choices - " +
                            "do not specify more than one such annotation on the same parameter: " + handlerMethod);
                }
    
                if (annotationsFound == 0) {// 若没有发现注解
                    Object argValue = resolveCommonArgument(methodParam, webRequest);    //判断WebRquest是否可赋值给参数
                    if (argValue != WebArgumentResolver.UNRESOLVED) {
                        args[i] = argValue;
                    }
                    else if (defaultValue != null) {
                        args[i] = resolveDefaultValue(defaultValue);
                    }
                    else {
                        Class<?> paramType = methodParam.getParameterType();
                        if (Model.class.isAssignableFrom(paramType) || Map.class.isAssignableFrom(paramType)) {
                            if (!paramType.isAssignableFrom(implicitModel.getClass())) {
                                throw new IllegalStateException("Argument [" + paramType.getSimpleName() + "] is of type " +
                                        "Model or Map but is not assignable from the actual model. You may need to switch " +
                                        "newer MVC infrastructure classes to use this argument.");
                            }
                            args[i] = implicitModel;
                        }
                        else if (SessionStatus.class.isAssignableFrom(paramType)) {
                            args[i] = this.sessionStatus;
                        }
                        else if (HttpEntity.class.isAssignableFrom(paramType)) {
                            args[i] = resolveHttpEntityRequest(methodParam, webRequest);
                        }
                        else if (Errors.class.isAssignableFrom(paramType)) {
                            throw new IllegalStateException("Errors/BindingResult argument declared " +
                                    "without preceding model attribute. Check your handler method signature!");
                        }
                        else if (BeanUtils.isSimpleProperty(paramType)) {// 判断是否参数类型是否是简单类型,若是在使用@RequestParam方式来处理,否则使用@ModelAttribute方式处理
                            paramName = "";
                        }
                        else {
                            attrName = "";
                        }
                    }
                }
    
                if (paramName != null) {
                    args[i] = resolveRequestParam(paramName, required, defaultValue, methodParam, webRequest, handler);
                }
                else if (headerName != null) {
                    args[i] = resolveRequestHeader(headerName, required, defaultValue, methodParam, webRequest, handler);
                }
                else if (requestBodyFound) {
                    args[i] = resolveRequestBody(methodParam, webRequest, handler);
                }
                else if (cookieName != null) {
                    args[i] = resolveCookieValue(cookieName, required, defaultValue, methodParam, webRequest, handler);
                }
                else if (pathVarName != null) {
                    args[i] = resolvePathVariable(pathVarName, methodParam, webRequest, handler);
                }
                else if (attrName != null) {
                    WebDataBinder binder =
                            resolveModelAttribute(attrName, methodParam, implicitModel, webRequest, handler);
                    boolean assignBindingResult = (args.length > i + 1 && Errors.class.isAssignableFrom(paramTypes[i + 1]));
                    if (binder.getTarget() != null) {
                        doBind(binder, webRequest, validate, validationHints, !assignBindingResult);
                    }
                    args[i] = binder.getTarget();
                    if (assignBindingResult) {
                        args[i + 1] = binder.getBindingResult();
                        i++;
                    }
                    implicitModel.putAll(binder.getBindingResult().getModel());
                }
            }
    
            return args;
        }
    复制代码

    RequestMappingHandlerAdapter中使用的参数绑定,代码稍微有些不同,有兴趣的同仁可以分析下,最后处理的结果都是一样的。

    示例:

    复制代码
    @RequestMapping ({"/", "/home"})
        public String showHomePage(String key){
            
            logger.debug("key="+key);
            
            return "home";
        }
    复制代码

    这种情况下,就调用默认的@RequestParam来处理。

    复制代码
        @RequestMapping (method = RequestMethod.POST)
        public String doRegister(User user){
            if(logger.isDebugEnabled()){
                logger.debug("process url[/user], method[post] in "+getClass());
                logger.debug(user);
            }
    
            return "user";
        }
    复制代码

    这种情况下,就调用@ModelAttribute来处理

     

     

     

    @RequestBody

    作用: 

          i) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上;

          ii) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。

    使用时机:

    A) GET、POST方式提时, 根据request header Content-Type的值来判断:

    •     application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);
    •     multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
    •     其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);

    B) PUT方式提交时, 根据request header Content-Type的值来判断:

    •     application/x-www-form-urlencoded, 必须;
    •     multipart/form-data, 不能处理;
    •     其他格式, 必须;

    说明:request的body部分的数据编码格式由header部分的Content-Type指定;

    @ResponseBody

    作用: 

          该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

    使用时机:

          返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

    HttpMessageConverter

    复制代码
    <span style="font-family:Microsoft YaHei;">/**
     * Strategy interface that specifies a converter that can convert from and to HTTP requests and responses.
     *
     * @author Arjen Poutsma
     * @author Juergen Hoeller
     * @since 3.0
     */
    public interface HttpMessageConverter<T> {
    
        /**
         * Indicates whether the given class can be read by this converter.
         * @param clazz the class to test for readability
         * @param mediaType the media type to read, can be {@code null} if not specified.
         * Typically the value of a {@code Content-Type} header.
         * @return {@code true} if readable; {@code false} otherwise
         */
        boolean canRead(Class<?> clazz, MediaType mediaType);
    
        /**
         * Indicates whether the given class can be written by this converter.
         * @param clazz the class to test for writability
         * @param mediaType the media type to write, can be {@code null} if not specified.
         * Typically the value of an {@code Accept} header.
         * @return {@code true} if writable; {@code false} otherwise
         */
        boolean canWrite(Class<?> clazz, MediaType mediaType);
    
        /**
         * Return the list of {@link MediaType} objects supported by this converter.
         * @return the list of supported media types
         */
        List<MediaType> getSupportedMediaTypes();
    
        /**
         * Read an object of the given type form the given input message, and returns it.
         * @param clazz the type of object to return. This type must have previously been passed to the
         * {@link #canRead canRead} method of this interface, which must have returned {@code true}.
         * @param inputMessage the HTTP input message to read from
         * @return the converted object
         * @throws IOException in case of I/O errors
         * @throws HttpMessageNotReadableException in case of conversion errors
         */
        T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
                throws IOException, HttpMessageNotReadableException;
    
        /**
         * Write an given object to the given output message.
         * @param t the object to write to the output message. The type of this object must have previously been
         * passed to the {@link #canWrite canWrite} method of this interface, which must have returned {@code true}.
         * @param contentType the content type to use when writing. May be {@code null} to indicate that the
         * default content type of the converter must be used. If not {@code null}, this media type must have
         * previously been passed to the {@link #canWrite canWrite} method of this interface, which must have
         * returned {@code true}.
         * @param outputMessage the message to write to
         * @throws IOException in case of I/O errors
         * @throws HttpMessageNotWritableException in case of conversion errors
         */
        void write(T t, MediaType contentType, HttpOutputMessage outputMessage)
                throws IOException, HttpMessageNotWritableException;
    
    }
    </span>
    复制代码

    该接口定义了四个方法,分别是读取数据时的 canRead(), read() 和 写入数据时的canWrite(), write()方法。

    在使用 <mvc:annotation-driven />标签配置时,默认配置了RequestMappingHandlerAdapter(注意是RequestMappingHandlerAdapter不是AnnotationMethodHandlerAdapter,详情查看Spring 3.1 document “16.14 Configuring Spring MVC”章节),并为他配置了一下默认的HttpMessageConverter:

    复制代码
        ByteArrayHttpMessageConverter converts byte arrays.
    
        StringHttpMessageConverter converts strings.
    
        ResourceHttpMessageConverter converts to/from org.springframework.core.io.Resource for all media types.
    
        SourceHttpMessageConverter converts to/from a javax.xml.transform.Source.
    
        FormHttpMessageConverter converts form data to/from a MultiValueMap<String, String>.
    
        Jaxb2RootElementHttpMessageConverter converts Java objects to/from XML — added if JAXB2 is present on the classpath.
    
        MappingJacksonHttpMessageConverter converts to/from JSON — added if Jackson is present on the classpath.
    
        AtomFeedHttpMessageConverter converts Atom feeds — added if Rome is present on the classpath.
    
        RssChannelHttpMessageConverter converts RSS feeds — added if Rome is present on the classpath.
    复制代码

    ByteArrayHttpMessageConverter: 负责读取二进制格式的数据和写出二进制格式的数据;

    StringHttpMessageConverter:   负责读取字符串格式的数据和写出二进制格式的数据;

    ResourceHttpMessageConverter:负责读取资源文件和写出资源文件数据; 

    FormHttpMessageConverter:       负责读取form提交的数据(能读取的数据格式为 application/x-www-form-urlencoded,不能读取multipart/form-data格式数据);负责写入application/x-www-from-urlencoded和multipart/form-data格式的数据;

    MappingJacksonHttpMessageConverter:  负责读取和写入json格式的数据;

    SouceHttpMessageConverter:                   负责读取和写入 xml 中javax.xml.transform.Source定义的数据;

    Jaxb2RootElementHttpMessageConverter:  负责读取和写入xml 标签格式的数据;

    AtomFeedHttpMessageConverter:              负责读取和写入Atom格式的数据;

    RssChannelHttpMessageConverter:           负责读取和写入RSS格式的数据;

    当使用@RequestBody和@ResponseBody注解时,RequestMappingHandlerAdapter就使用它们来进行读取或者写入相应格式的数据。

     

    HttpMessageConverter匹配过程:

    @RequestBody注解时: 根据Request对象header部分的Content-Type类型,逐一匹配合适的HttpMessageConverter来读取数据;

    spring 3.1源代码如下:

    复制代码
    private Object readWithMessageConverters(MethodParameter methodParam, HttpInputMessage inputMessage, Class paramType)
                throws Exception {
    
            MediaType contentType = inputMessage.getHeaders().getContentType();
            if (contentType == null) {
                StringBuilder builder = new StringBuilder(ClassUtils.getShortName(methodParam.getParameterType()));
                String paramName = methodParam.getParameterName();
                if (paramName != null) {
                    builder.append(' ');
                    builder.append(paramName);
                }
                throw new HttpMediaTypeNotSupportedException(
                        "Cannot extract parameter (" + builder.toString() + "): no Content-Type found");
            }
    
            List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
            if (this.messageConverters != null) {
                for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
                    allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
                    if (messageConverter.canRead(paramType, contentType)) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Reading [" + paramType.getName() + "] as "" + contentType
                                    +"" using [" + messageConverter + "]");
                        }
                        return messageConverter.read(paramType, inputMessage);
                    }
                }
            }
            throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes);
        }
    复制代码

    @ResponseBody注解时: 根据Request对象header部分的Accept属性(逗号分隔),逐一按accept中的类型,去遍历找到能处理的HttpMessageConverter;

    源代码如下:

    复制代码
    private void writeWithMessageConverters(Object returnValue,
                    HttpInputMessage inputMessage, HttpOutputMessage outputMessage)
                    throws IOException, HttpMediaTypeNotAcceptableException {
                List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
                if (acceptedMediaTypes.isEmpty()) {
                    acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
                }
                MediaType.sortByQualityValue(acceptedMediaTypes);
                Class<?> returnValueType = returnValue.getClass();
                List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
                if (getMessageConverters() != null) {
                    for (MediaType acceptedMediaType : acceptedMediaTypes) {
                        for (HttpMessageConverter messageConverter : getMessageConverters()) {
                            if (messageConverter.canWrite(returnValueType, acceptedMediaType)) {
                                messageConverter.write(returnValue, acceptedMediaType, outputMessage);
                                if (logger.isDebugEnabled()) {
                                    MediaType contentType = outputMessage.getHeaders().getContentType();
                                    if (contentType == null) {
                                        contentType = acceptedMediaType;
                                    }
                                    logger.debug("Written [" + returnValue + "] as "" + contentType +
                                            "" using [" + messageConverter + "]");
                                }
                                this.responseArgumentUsed = true;
                                return;
                            }
                        }
                    }
                    for (HttpMessageConverter messageConverter : messageConverters) {
                        allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
                    }
                }
                throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes);
            }
    复制代码

    补充:

    MappingJacksonHttpMessageConverter 调用了 objectMapper.writeValue(OutputStream stream, Object)方法,使用@ResponseBody注解返回的对象就传入Object参数内。若返回的对象为已经格式化好的json串时,不使用@RequestBody注解,而应该这样处理:
    1、response.setContentType("application/json; charset=UTF-8");
    2、response.getWriter().print(jsonStr);
    直接输出到body区,然后的视图为void。

    前段时间项目中用到了RESTful模式来开发程序,但是当用POST、PUT模式提交数据时,发现服务器端接受不到提交的数据(服务器端参数绑定没有加任何注解),查看了提交方式为application/json, 而且服务器端通过request.getReader() 打出的数据里确实存在浏览器提交的数据。为了找出原因,便对参数绑定(@RequestParam、 @RequestBody、 @RequestHeader 、 @PathVariable)进行了研究,同时也看了一下HttpMessageConverter的相关内容,在此一并总结。

    简介:

    @RequestMapping

    RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

    RequestMapping注解有六个属性,下面我们把她分成三类进行说明。

    1、 value, method;

    value:     指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);

    method:  指定请求的method类型, GET、POST、PUT、DELETE等;

    2、 consumes,produces;

    consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

    produces:    指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

    3、 params,headers;

    params: 指定request中必须包含某些参数值是,才让该方法处理。

    headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

    示例:

    1、value  / method 示例

    默认RequestMapping("....str...")即为value的值;

    复制代码
    @Controller
    @RequestMapping("/appointments")
    public class AppointmentsController {
    
        private AppointmentBook appointmentBook;
        
        @Autowired
        public AppointmentsController(AppointmentBook appointmentBook) {
            this.appointmentBook = appointmentBook;
        }
    
        @RequestMapping(method = RequestMethod.GET)
        public Map<String, Appointment> get() {
            return appointmentBook.getAppointmentsForToday();
        }
    
        @RequestMapping(value="/{day}", method = RequestMethod.GET)
        public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
            return appointmentBook.getAppointmentsForDay(day);
        }
    
        @RequestMapping(value="/new", method = RequestMethod.GET)
        public AppointmentForm getNewForm() {
            return new AppointmentForm();
        }
    
        @RequestMapping(method = RequestMethod.POST)
        public String add(@Valid AppointmentForm appointment, BindingResult result) {
            if (result.hasErrors()) {
                return "appointments/new";
            }
            appointmentBook.addAppointment(appointment);
            return "redirect:/appointments";
        }
    }
    复制代码

    value的uri值为以下三类:

    A) 可以指定为普通的具体值;

    B)  可以指定为含有某变量的一类值(URI Template Patterns with Path Variables);

    C) 可以指定为含正则表达式的一类值( URI Template Patterns with Regular Expressions);

    example B)

    @RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
    public String findOwner(@PathVariable String ownerId, Model model) {
      Owner owner = ownerService.findOwner(ownerId);  
      model.addAttribute("owner", owner);  
      return "displayOwner"; 
    }

    example C)

    @RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:d.d.d}.{extension:.[a-z]}")
      public void handle(@PathVariable String version, @PathVariable String extension) {    
        // ...
      }
    }

    2 consumes、produces 示例

    cousumes的样例:

    @Controller
    @RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
    public void addPet(@RequestBody Pet pet, Model model) {    
        // implementation omitted
    }

    方法仅处理request Content-Type为“application/json”类型的请求。

    produces的样例:

    @Controller
    @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
    @ResponseBody
    public Pet getPet(@PathVariable String petId, Model model) {    
        // implementation omitted
    }

    方法仅处理request请求中Accept头中包含了"application/json"的请求,同时暗示了返回的内容类型为application/json;

    3 params、headers 示例

    params的样例:

    复制代码
    @Controller
    @RequestMapping("/owners/{ownerId}")
    public class RelativePathUriTemplateController {
    
      @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")
      public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    
        // implementation omitted
      }
    }
    复制代码

    仅处理请求中包含了名为“myParam”,值为“myValue”的请求;

    headers的样例:

    复制代码
    @Controller
    @RequestMapping("/owners/{ownerId}")
    public class RelativePathUriTemplateController {
    
    @RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")
      public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    
        // implementation omitted
      }
    }
    复制代码

    仅处理request的header中包含了指定“Refer”请求头和对应值为“http://www.ifeng.com/”的请求;

     

    http://www.codeweblog.com/stag/spring-requestmapping-method-requestmethod-post/

     

    Rest介绍

     

     

    /blog/1 HTTP GET =>  得到id = 1的blog
    /blog/1 HTTP DELETE => 删除 id = 1的blog
    /blog/1 HTTP PUT =>  更新id = 1的blog
    /blog   HTTP POST =>  新增BLOG

     

     

        以下详细解一下spring rest使用.

     

        首先,我们带着如下两个问题查看本文。

     

            1.如何在java构造没有扩展名的RESTful url,如 /forms/1,而不是 /forms/1.do

     

            2.浏览器的form标签不支持提交delete,put请求,如何曲线解决

     

        springmvc rest 实现

     

        springmvc的resturl是通过@RequestMapping 及@PathVariable annotation提供的,
        通过如@RequestMapping(value="/blog /{id}",method=RequestMethod.DELETE)即可处理/blog/1 的delete请求.

     

     

    1@RequestMapping(value="/blog/{id}",method=RequestMethod.DELETE)
    2public ModelAndView delete(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) {
    3  blogManager.removeById(id);
    4  return new ModelAndView(LIST_ACTION);
    5}


        @RequestMapping @PathVariable如果URL中带参数,则配合使用,如

     

     

    1@RequestMapping(value="/blog/{blogId}/message/{msgId}",method=RequestMethod.DELETE)
    2public ModelAndView delete(@PathVariable("blogId") Long blogId,@PathVariable("msgId") Long msgId,HttpServletRequest request,HttpServletResponse response) {
    3}

     

     

        1.springmvc web.xml配置

     

     1<!-- 该servlet为tomcat,jetty等容器提供,将静态资源映射从/改为/static/目录,如原来访问 http://localhost/foo.css ,现在http://localhost/static/foo.css -->
     2  <servlet-mapping>
     3  <servlet-name>default</servlet-name>
     4  <url-pattern>/static/*</url-pattern>
     5  </servlet-mapping>
     6  <servlet>
     7    <servlet-name>springmvc</servlet-name>
     8    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     9    <load-on-startup>1</load-on-startup>
    10  </servlet>
    11
    12  <!-- URL重写filter,用于将访问静态资源http://localhost/foo.css 转为http://localhost/static/foo.css -->
    13  <filter>
    14  <filter-name>UrlRewriteFilter</filter-name>
    15  <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
    16  <init-param>
    17     <param-name>confReloadCheckInterval</param-name>
    18     <param-value>60</param-value>
    19    </init-param>
    20  <init-param>
    21        <param-name>logLevel</param-name>
    22        <param-value>DEBUG</param-value>
    23      </init-param>
    24  </filter>
    25  <filter-mapping>
    26  <filter-name>UrlRewriteFilter</filter-name>
    27  <url-pattern>/*</url-pattern>
    28  </filter-mapping>
    29
    30  <!-- 覆盖default servlet的/, springmvc servlet将处理原来处理静态资源的映射 -->
    31  <servlet-mapping>
    32    <servlet-name>springmvc</servlet-name>
    33    <url-pattern>/</url-pattern>
    34  </servlet-mapping>
    35
    36  <!-- 浏览器不支持put,delete等method,由该filter将/blog?_method=delete转换为标准的http delete方法 -->
    37  <filter>
    38  <filter-name>HiddenHttpMethodFilter</filter-name>
    39  <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    40  </filter>
    41
    42  <filter-mapping>
    43  <filter-name>HiddenHttpMethodFilter</filter-name>
    44  <servlet-name>springmvc</servlet-name>
    45  </filter-mapping>

     

     

        2.webapp/WEB-INF/springmvc-servlet.xml配置,使用如下两个class激活@RequestMapping annotation

     

     

     

    1<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>   
    2<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>  
    3

     

     

        3.Controller编写

     

     1/**
     2  * @RequestMapping("/userinfo") 具有层次关系,方法级的将在类一级@RequestMapping之一,
     3  * 如下面示例, 访问方法级别的@RequestMapping("/new"),则URL为 /userinfo/new
     4  */

     5@Controller
     6@RequestMapping("/userinfo")
     7public class UserInfoController extends BaseSpringController{
     8  //默认多列排序,example: username desc,createTime asc
     9  protected static final String DEFAULT_SORT_COLUMNS = null;
    10
    11  private UserInfoManager userInfoManager;
    12
    13  private final String LIST_ACTION = "redirect:/userinfo";
    14
    15  /**
    16  * 通过spring自动注入
    17  **/

    18  public void setUserInfoManager(UserInfoManager manager) {
    19  this.userInfoManager = manager;
    20  }

    21
    22  /** 列表 */
    23  @RequestMapping
    24  public ModelAndView index(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) {
    25  PageRequest<Map> pageRequest = newPageRequest(request,DEFAULT_SORT_COLUMNS);
    26  //pageRequest.getFilters(); //add custom filters 
    27
    28  Page page = this.userInfoManager.findByPageRequest(pageRequest);
    29  savePage(page,pageRequest,request);
    30  return new ModelAndView("/userinfo/list","userInfo",userInfo);
    31  }

    32
    33  /** 进入新增 */
    34  @RequestMapping(value="/new")
    35  public ModelAndView _new(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) throws Exception {
    36  return new ModelAndView("/userinfo/new","userInfo",userInfo);
    37  }

    38
    39  /** 显示 */
    40  @RequestMapping(value="/{id}")
    41  public ModelAndView show(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws Exception {
    42  UserInfo userInfo = (UserInfo)userInfoManager.getById(id);
    43  return new ModelAndView("/userinfo/show","userInfo",userInfo);
    44  }

    45
    46  /** 编辑 */
    47  @RequestMapping(value="/{id}/edit")
    48  public ModelAndView edit(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws Exception {
    49  UserInfo userInfo = (UserInfo)userInfoManager.getById(id);
    50  return new ModelAndView("/userinfo/edit","userInfo",userInfo);
    51  }

    52
    53  /** 保存新增 */
    54  @RequestMapping(method=RequestMethod.POST)
    55  public ModelAndView create(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) throws Exception {
    56  userInfoManager.save(userInfo);
    57  return new ModelAndView(LIST_ACTION);
    58  }

    59
    60  /** 保存更新 */
    61  @RequestMapping(value="/{id}",method=RequestMethod.PUT)
    62  public ModelAndView update(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws Exception {
    63  UserInfo userInfo = (UserInfo)userInfoManager.getById(id);
    64  bind(request,userInfo);
    65  userInfoManager.update(userInfo);
    66  return new ModelAndView(LIST_ACTION);
    67  }

    68
    69  /** 删除 */
    70  @RequestMapping(value="/{id}",method=RequestMethod.DELETE)
    71  public ModelAndView delete(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) {
    72  userInfoManager.removeById(id);
    73  return new ModelAndView(LIST_ACTION);
    74  }

    75
    76  /** 批量删除 */
    77  @RequestMapping(method=RequestMethod.DELETE)
    78  public ModelAndView batchDelete(HttpServletRequest request,HttpServletResponse response) {
    79  String[] items = request.getParameterValues("items");
    80  for(int i = 0; i < items.length; i++) {
    81   java.lang.Long id = new java.lang.Long(items[i]);
    82   userInfoManager.removeById(id);
    83  }

    84  return new ModelAndView(LIST_ACTION);
    85  }

    86
    87}

    88

     

     

    1/userinfo  => index()
    2  /userinfo/new => _new()
    3  /userinfo/{id} => show()
    4  /userinfo/{id}/edit  => edit()
    5  /userinfo POST => create()
    6  /userinfo/{id} PUT => update()
    7  /userinfo/{id} DELETE => delete()
    8  /userinfo DELETE => batchDelete()
    9

     

     

        
        注(不使用 /userinfo/add  => add() 方法是由于add这个方法会被maxthon浏览器当做广告链接过滤掉,因为包含ad字符)

     


     

     

        4.jsp 编写

     

    1<form:form action="${ctx}/userinfo${userInfo.userId}" method="put">
    2</form:form>

     

     

        生成的html内容如下, 生成一个hidden的_method=put,并于web.xml中的HiddenHttpMethodFilter配合使用,在服务端将post请求改为put请求

     

    1<form id="userInfo" action="/springmvc_rest_demo/userinfo/2" method="post">
    2  <input type="hidden" name="_method" value="put"/>
    3</form>

     

     

        另外一种方法是你可以使用ajax发送put,delete请求.

     

        5.静态资源的URL重写

     

            如上我们描述,现因为将default servlet映射至/static/的子目录,现我们访问静态资源将会带一个/static/前缀.

     

            如 /foo.gif, 现在访问该文件将是 /static/foo.gif.

     

            那如何避免这个前缀呢,那就是应用URL rewrite,现我们使用 http://tuckey.org/urlrewrite/, 重写规则如下

     

        

     

    1<urlrewrite>
    2   <!-- 访问jsp及jspx将不rewrite url,其它.js,.css,.gif等将重写,如 /foo.gif => /static/foo.gif -->
    3   <rule>
    4    <condition operator="notequal" next="and" type="request-uri">.*.jsp</condition>
    5    <condition operator="notequal" next="and" type="request-uri">.*.jspx</condition>
    6     <from>^(/.*..*)$</from>
    7     <to>/static$1</to>
    8   </rule>
    9</urlrewrite>

     

    ----------------------------------------------------

    第一讲:SpringMVC 页面跳转实例,通过请求访问start.jsp页面 

    1.1 加包 

    1.2 web.xml 

            <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>*.do</url-pattern> 

          </servlet-mapping> 


    abc 
    1.3 建springMVC-servlet.xml(注:spring默认要求建立在WEB-INF目录下,并且名称为servlet-name_servlet.xml 

        <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" 
            xsi:schemaLocation=" 
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
            <context:component-scan base-package="com.wdl.cn.controllers" /> 
            <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
                <property name="prefix" value="/WEB-INF/page/"/> 
                <property name="suffix" value=".jsp"/> 
            </bean> 
        </beans> 


    1.4 StartController.java 

        package com.wdl.cn.controllers; 

        import org.springframework.stereotype.Controller; 
        import org.springframework.web.bind.annotation.RequestMapping; 

        @Controller 
        public class StartController { 

            @RequestMapping(value="/start") 
            public String start(){ 
                System.out.println("start method invoked..."); 
                return "start"; 
            } 
        } 


    1.5 新建 WEB-INF/page/start.jsp 

    1.6 访问:http://localhost:8080/springMVC_001/start.do 
    总结:本例子搭建一个简单的spingmvc实例,通过本例学习springMVC最简单的流程及搭建元素。 
    第二讲 灵活指定springmvc映射文件及路径 
        更多情况下,对于第一讲中的springMVC-servlet.xml 文件,我们并不想去放在WEB-INF,或者说我们可能在一个项目中并不是只有这一个文件,所以本节我们来讲述如何灵活配置此文件及文件名。 
    2.1 修改web.xml 

        <servlet> 
              <servlet-name>springMVC</servlet-name> 
              <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
              <init-param> 
                  <param-name>contextConfigLocation</param-name> 
                  <param-value>classpath*:/com/wdl/cn/config/mvc/*.xml</param-value> 
              </init-param> 
              <load-on-startup>1</load-on-startup> 
          </servlet> 
          <servlet-mapping> 
              <servlet-name>springMVC</servlet-name> 
              <url-pattern>*.do</url-pattern> 
          </servlet-mapping> 

    2.2 将WEB-INF下面的springMVC-servlet.xml 移动到com.wdl.cn.config.mvc包下并将其修改名称为springMVC-first.xml 

    2.3 测试原来的路径 : http://localhost:8080/springMVC_002/start.do 

    总结:本讲主要学习了如何灵活配置springMVC配置文件。下节将重点讲述@RequestMapping的使用。 

    第三讲 springMVC_003  @RequestMapping的使用 

    3.1 @RequestMapping 使用位置 
        a.使用于方法,此方法则可以被请求访问; 
        b.使用于类,则可以将请求分(又叫分路径,分模块)包处理 
    3.2 将controller类上加@RequestMapping,修改StartController.java 

        package com.wdl.cn.controllers; 

        import org.springframework.stereotype.Controller; 
        import org.springframework.web.bind.annotation.RequestMapping; 

        @Controller 
        @RequestMapping(value="/test") 
        public class StartController { 

            @RequestMapping(value="/start") 
            public String start(){ 
                System.out.println("start method invoked..."); 
                return "start"; 
            } 
        } 

    3.3 访问:http://localhost:8080/springMVC_003/test/start.do ,由此可见,可以通过在类上加@RequestMapping将请求分路径。 

    3.4 @RequestMapping 参数详解 
        a.value表示访问的路径 
        b.method 表示请求的方式 GET | POST 
        step1:修改StartController.java 

        import org.springframework.stereotype.Controller; 
        import org.springframework.web.bind.annotation.RequestMapping; 
        import org.springframework.web.bind.annotation.RequestMethod; 

        @Controller 
        @RequestMapping(value="/test") 
        public class StartController { 

            @RequestMapping(value="/start",method=RequestMethod.GET) 
            public String start(){ 
                System.out.println("start method invoked..."); 
                return "start"; 
            } 
            @RequestMapping(value="/start",method=RequestMethod.POST) 
            public String start2(){ 
                System.out.println("start2 method invoked..."); 
                return "start"; 
            } 
        }          

    step2:修改start.jsp模拟POST请求 
    3.5 访问http://localhost:8080/springMVC_003/test/start.do,接着转到start.jsp页面,接着点击页面的中按钮,发送POST请求,则可以看出不同的请求方式可以调用不同的方法。 
    3.6 参数传递(常用参数传递,restful风格参数传递) 

          a.httpservletreqeust方式参数传递 
            step1:修改StartController.java 
          

        package com.wdl.cn.controllers; 

        import javax.servlet.http.HttpServletRequest; 

        import org.springframework.stereotype.Controller; 
        import org.springframework.web.bind.annotation.RequestMapping; 
        import org.springframework.web.bind.annotation.RequestMethod; 

        @Controller 
        @RequestMapping(value="/test") 
        public class StartController { 

            @RequestMapping(value="/start",method=RequestMethod.GET) 
            public String start(HttpServletRequest request){ 
                System.out.println("start method invoked..."); 
                String name = request.getParameter("name"); 
                int age = Integer.parseInt(request.getParameter("age")); 
                System.out.println("name=" + name + " age = " + age); 
                return "start"; 
            } 
            @RequestMapping(value="/start",method=RequestMethod.POST) 
            public String start2(){ 
                System.out.println("start2 method invoked..."); 
                return "start"; 
            } 
        } 
        step2:访问:http://localhost:8080/springMVC_003/test/start.do?name=zhangsan&age=45 

          b.restfull风格参数传递 
            step1:修改StartController.java 

        package com.wdl.cn.controllers; 

        import org.springframework.stereotype.Controller; 
        import org.springframework.web.bind.annotation.PathVariable; 
        import org.springframework.web.bind.annotation.RequestMapping; 
        import org.springframework.web.bind.annotation.RequestMethod; 

        @Controller 
        @RequestMapping(value="/test") 
        public class StartController { 

            @RequestMapping(value="/start/{name}/{age}",method=RequestMethod.GET) 
            public String start(@PathVariable("name") String name,@PathVariable("age") int age){ 
                System.out.println("start method invoked..."); 
                System.out.println("name="+name+" age="+age); 
                return "start"; 
            } 
            @RequestMapping(value="/start",method=RequestMethod.POST) 
            public String start2(){ 
                System.out.println("start2 method invoked..."); 
                return "start"; 
            } 
        } 

        step2:访问时,将参数值加入请求路径 http://localhost:8080/springMVC_003/test/start/zhangsan/45.do 
    总结:本讲主要讲述请求参数传递,主要掌握HttpServletRequest方式与restfull风格参数传递,下讲主要讲述form表单提交 

    第四讲 form表单提交 
        使用struts2后,我们习惯将form表单的数据封装成一个对象,这也是面向对象编程的一个思维,本节讲述form表单提交。 
        具体代码见UserController.java 

        package com.wdl.cn.controllers; 

        import java.text.SimpleDateFormat; 
        import java.util.Date; 

        import javax.servlet.http.HttpSession; 

        import org.springframework.beans.propertyeditors.CustomDateEditor; 
        import org.springframework.stereotype.Controller; 
        import org.springframework.web.bind.WebDataBinder; 
        import org.springframework.web.bind.annotation.InitBinder; 
        import org.springframework.web.bind.annotation.RequestMapping; 
        import org.springframework.web.bind.annotation.RequestMethod; 
        import org.springframework.web.servlet.ModelAndView; 

        import com.wdl.cn.entity.User; 

        @Controller 
        @RequestMapping(value="/form") 
        public class UserController { 

            @RequestMapping(value="/add",method=RequestMethod.GET) 
            public String toUserAddPage(){ 
                System.out.println("toUserAddPage method invoked..."); 
                return "useradd"; 
            } 
           
            @RequestMapping(value="/add",method=RequestMethod.POST) 
            public ModelAndView addUser(HttpSession session,User user){ 
                System.out.println("addUser method invoked..."); 
                System.out.println(user); 
                ModelAndView mav = new ModelAndView(); 
                session.setAttribute("abc", user); 
                mav.setViewName("redirect:/form/add.do"); 
                mav.addObject("abc", user); 
                //return "useradd"; 
                return mav; 
            } 
           
            @InitBinder 
            public void initBinder(WebDataBinder binder){ 
                binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false)); 
            } 
        } 

         注:addUser方法中参数User则是接收请求发过来的参数;initBinder方法则是用来绑定用户提交的数据,前台提交过来的日期,在这里后面并不知情,则由这个方法来处理。 
    总结:本讲主要讲述如何来提交表单数据,并将其封装成一个对象。 

    第五节 一个Controller处理多个请求 
          很多情况下,我们都想把有关联的请求放在一个controller中,比如,对于一个用户的增删改查,都可以放在一个controller类中。对于springMVC注解的方式有两种方式可以实现。 
        1.一个controller类中每个处理请求的方法的@requestMapping的param中可以带参数,比如:@RequestMapping(param="method=method1"),在类级别的@RequestMapping上面指定请求路径。 

        package com.wdl.cn.controllers; 

        import org.springframework.stereotype.Controller; 
        import org.springframework.web.bind.annotation.RequestMapping; 
        import org.springframework.web.servlet.ModelAndView; 

        @Controller 
        @RequestMapping(value="/manyRequest") 
        public class ReceiveManyRequestController { 
            @RequestMapping(params="method=method1") 
            public ModelAndView methodOne(){ 
                System.out.println("method methodOne invoked..."); 
                ModelAndView mav = new ModelAndView("ReceiveManyRequest"); 
                mav.addObject("msg", "请求第一个方法"); 
                return mav; 
            } 
            @RequestMapping(params="method=method2") 
            public ModelAndView methodTwo(){ 
                System.out.println("method methodTwo invoked..."); 
                ModelAndView mav = new ModelAndView("ReceiveManyRequest"); 
                mav.addObject("msg", "请求第二个方法"); 
                return mav; 
            } 
           
        } 

          2.每个接收请求的方法的@RequestMapping的value中指定请求路径,看ReceveManyRequestController2.java 

        package com.wdl.cn.controllers; 

        import org.springframework.stereotype.Controller; 
        import org.springframework.web.bind.annotation.RequestMapping; 
        import org.springframework.web.servlet.ModelAndView; 

        @Controller 
        @RequestMapping(value="/manyRequest") 
        public class ReceiveManyRequestController2 { 
            @RequestMapping(value="/request1") 
            public ModelAndView methodOne(){ 
                System.out.println("method methodOne invoked..."); 
                ModelAndView mav = new ModelAndView("ReceiveManyRequest"); 
                mav.addObject("msg", "请求第一个方法"); 
                return mav; 
            } 
            @RequestMapping(value="/request2") 
            public ModelAndView methodTwo(){ 
                System.out.println("method methodTwo invoked..."); 
                ModelAndView mav = new ModelAndView("ReceiveManyRequest"); 
                mav.addObject("msg", "请求第二个方法"); 
                return mav; 
            } 
        } 

    这里访问WEB-INF目录下的页面,这个还不知道有没有类似struts2那样的通配符来可以访问不同的action,不同的method,不同的页面,用户则很爽,有的话求告知,而且我还有一个问题就是配置了如下的配置,但却访问不到静态资源,望解答!!-----访问路径:http://localhost:8080/Springmvc3/images/4.jpg

    好了,其他不说了,看如下:

    配置视图解析器

    package com.tgb.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    import com.tgb.entity.User;
    
    @Controller
    @RequestMapping("/test")
    //这里也可以写成@RequestMapping("/test.do")也可以不写,因为在web.xml中配置了*.do
    public class TestController {
    	
    	@RequestMapping(params="method=addUser")
    	public String addUser(User user){
    		System.out.println("dddddddddd");
    		return "success";
    	}
    	
    	@RequestMapping(value="/test0")//默认为get方式
    	public String test0(){
    		System.out.println("访问路径:test/test0.do");
    		return "success";
    	}
    
    	@RequestMapping(value="/test1",method=RequestMethod.POST)
    	public String test1(String sex){
    		System.out.println(sex);
    		System.out.println("访问路径为:test/test1.do,而且是get方式______"+sex);
    		return "success";
    	}
    	
    	@RequestMapping(value="/test2",method=RequestMethod.GET,params="param=test2")
    	public String test2(){
    		System.out.println("访问路径为:test/test1.do?param=test2,而且是get方式");
    		return "success";
    	}
    	
    	//REST风格的参数
    	@RequestMapping(value="/test3/{name}")
    	public String test3(@PathVariable String name){//形参和接收参数的名称一致
    		System.out.println(name);
    		System.out.println("访问路径为:test/test3/zhangsan.do");
    		System.out.println("看这里的访问路径,直接就将‘zhangsan’这个参数值就传递给了@RequestMapping(value="/test3/{name}")中的name参数名,可随意命名参数名称,");
    		return "success";
    	}
    	
    	@RequestMapping(value="/test5/{name}")
    	public String test5(@PathVariable("name")String rename){//形参和接收参数的名称不一致
    		System.out.println(rename);
    		System.out.println("访问路径为:test/test5/zhangsan.do");
    		System.out.println("看这里的访问路径,直接就将‘zhangsan’这个参数值就传递给了@RequestMapping(value="/test5/{name}")中的name参数名,可随意命名参数名称," +
    				"然后后面的@PathVariable("name")中的name名称要和上面的那个name保持一致,然后把此name绑定到形参rename");
    		return "success";
    	}
    	
    	@RequestMapping(value="/test4/{sex}/{sno}")
    	//这里我写成@RequestMapping(value="test4/{sex}/{sno}")也是可以滴
    	public String test4(@PathVariable("sex")String sex,@PathVariable("sno")String sno){
    		System.out.println(sex);
    		System.err.println(sno);
    		System.out.println("访问路径:test/test4/male/10506.do");
    		return "success";
    	}
    	
    	//支持正则
    	@RequestMapping(value="/test6/{textualPart:[a-z-]+}.{numericPart:[\d]+}")
    	public String test6(@PathVariable String textualPart,@PathVariable String numericPart){
    		System.out.println(textualPart);//输出sometxt
    		System.out.println(numericPart);//输出123
    		System.out.println("访问路径:test/test6/sometxt.123.do");
    		return "success";
    	}
    	
    	//访问WEB-INF下的views文件中的不同目录的页面,这里访问的是user目录下的,不知道其他有什么好的办法没
    	@RequestMapping(value="/test7")
    	public String test7(){
    		System.out.println("访问路径:test/test7.do");
    		return "user/success";
    	}
    	
    }









       
           

           

     
  • 相关阅读:
    终于搞明白Unicode,ASCII,UTF8,UCS2编码是啥了
    在IDEA中构建Tomcat项目流程
    在执行jar包时如何使用调优参数
    在浏览器运行JS脚本实现博客园文章批量删除
    线索二叉树之初步剖析(献给那些想形象思考二叉树遍历过程的人)
    二分查找c++实现
    c++学习之初话 函数指针和函数对象 的因缘
    继承与动态内存分配
    C++入门之初话多态与虚函数
    c++入门之类继承初步
  • 原文地址:https://www.cnblogs.com/fx2008/p/3762468.html
Copyright © 2011-2022 走看看