Spring注解

简介:

一、SpringMVC注解入门

1. 创建web项目
2. 在springmvc的配置文件中指定注解驱动,配置扫描器

Xml代码  收藏代码

  1. <!-- mvc的注解驱动 -->  

  2. <mvc:annotation-driven />  

  3.   

  4. <!--只要定义了扫描器,注解驱动就不需要,扫描器已经有了注解驱动的功能 -->  

  5. <context:component-scan base-package="org.study1.mvc.controller" />  

  6.   

  7. <!-- 前缀+ viewName +后缀 -->  

  8. <bean  

  9.     class="org.springframework.web.servlet.view.InternalResourceViewResolver">  

  10.     <!-- WebContent(WebRoot)到某一指定的文件夹的路径 ,如下表示/WEB-INF/view/*.jsp -->  

  11.     <property name="prefix" value="/WEB-INF/view/"></property>  

  12.     <!-- 视图名称的后缀 -->  

  13.     <property name="suffix" value=".jsp"></property>  

  14. </bean>  

<context:component-scan/> 扫描指定的包中的类上的注解,常用的注解有:

@Controller 声明Action组件
@Service    声明Service组件    @Service("myMovieLister") 
@Repository 声明Dao组件
@Component   泛指组件, 当不好归类时. 
@RequestMapping("/menu")  请求映射
@Resource  用于注入,( j2ee提供的 ) 默认按名称装配,@Resource(name="beanName") 
@Autowired 用于注入,(srping提供的) 默认按类型装配 
@Transactional( rollbackFor={Exception.class}) 事务管理
@ResponseBody
@Scope("prototype")   设定bean的作用

3. @controller:标识当前类是控制层的一个具体的实现
4. @requestMapping:放在方法上面用来指定某个方法的路径,当它放在类上的时候相当于命名空间需要组合方法上的requestmapping来访问。

Java代码  收藏代码

  1. @Controller // 用来标注当前类是springmvc的控制层的类  

  2. @RequestMapping("/test"// RequestMapping表示 该控制器的唯一标识或者命名空间  

  3. public class TestController {  

  4.   

  5.     /** 

  6.      * 方法的返回值是ModelAndView中的 

  7.      */  

  8.     @RequestMapping("/hello.do"// 用来访问控制层的方法的注解  

  9.     public String hello() {  

  10.         System.out.println("springmvc annotation... ");  

  11.         return "jsp1/index";  

  12.     }  

  13.   

  14.     //*****  

  15. }  

在本例中,项目部署名为mvc,tomcat url为 http://localhost,所以实际为:http://localhos/mvc

在本例中,因为有命名空间 /test,所以请求hello方法地址为:http://localhost/mvc/test/hello.do

输出:springmvc annotation...

二、注解形式的参数接收

1. HttpServletRequest可以直接定义在参数的列表,通过该请求可以传递参数

url:http://localhost/mvc/test/toPerson.do?name=zhangsan

Java代码  收藏代码

  1. /** 

  2.  * HttpServletRequest可以直接定义在参数的列表, 

  3.  *  

  4.  */  

  5. @RequestMapping("/toPerson.do")  

  6. public String toPerson(HttpServletRequest request) {  

  7.     String result = request.getParameter("name");  

  8.     System.out.println(result);  

  9.     return "jsp1/index";  

  10. }  

 可以从HttpServletRequest 取出“name”属性,然后进行操作!如上,可以取出 “name=zhangsan”

输出:zhangsan
2. 在参数列表上直接定义要接收的参数名称,只要参数名称能匹配的上就能接收所传过来的数据, 可以自动转换成参数列表里面的类型,注意的是值与类型之间是可以转换的

2.1传递多种不同类型的参数:

url:http://localhost/mvc/test/toPerson1.do?name=zhangsan&age=14&address=china&birthday=2000-2-11

Java代码  收藏代码

  1. /** 

  2.  * 传递的参数的名字必须要与实体类的属性set方法后面的字符串匹配的上才能接收到参数,首字符的大小写不区分 

  3.  * 请求中传的参数只要是能和参数列表里面的变量名或者实体里面的set后面的字符串匹配的上就能接收到 a 

  4.  *  

  5.  */  

  6. @RequestMapping("/toPerson1.do")  

  7. public String toPerson1(String name, Integer age, String address,  

  8.              Date birthday) {  

  9.            System.out.println(name + " " + age + " " + address + " " + birthday);  

  10.            return "jsp1/index";  

  11. }  

  12.   

  13. /** 

  14.  * 注册时间类型的属性编辑器,将String转化为Date 

  15.  */  

  16. @InitBinder  

  17. public void initBinder(ServletRequestDataBinder binder) {  

  18.     binder.registerCustomEditor(Date.classnew CustomDateEditor(  

  19.             new SimpleDateFormat("yyyy-MM-dd"), true));  

  20. }  

输出:zhangsan 14 china Fri Feb 11 00:00:00 CST 2000

2.2传递数组:

url:http://localhost/mvc/test/toPerson2.do?name=tom&name=jack  

Java代码  收藏代码

  1. /** 

  2.  * 对数组的接收,定义为同名即可  

  3.  */  

  4. @RequestMapping("/toPerson2.do")  

  5. public String toPerson2(String[] name) {  

  6.     for (String result : name) {  

  7.         System.out.println(result);  

  8.     }  

  9.     return "jsp1/index";  

  10. }  

 输出:tom jack

2.3传递自定义对象(可多个):

url:http://localhost/mvc/test/toPerson3.do?name=zhangsan&age=14&address=china&birthday=2000-2-11

 User 定义的属性有:name,age,并且有各自属性的对应的set方法以及toString方法

 Person定义的属性有:name,age.address,birthday,并且有各自属性的对应的set方法以及toString方法

Java代码  收藏代码

  1. /** 

  2.  *  

  3.  * 传递的参数的名字必须要与实体类的属性set方法后面的字符串匹配的上才能接收到参数,首字符的大小写不区分 

  4.  * 请求中传的参数只要是能和参数列表里面的变量名或者实体里面的set后面的字符串匹配的上就能接收到  

  5.  *  

  6.  */  

  7. @RequestMapping("/toPerson3.do")  

  8. public String toPerson3(Person person, User user) {  

  9.     System.out.println(person);  

  10.     System.out.println(user);  

  11.     return "jsp1/index";  

  12. }  

  输出:

Person [name=zhangsan, age=14, address=china, birthday=Fri Feb 11 00:00:00 CST 2000]
User [name=zhangsan, age=14]
 

自动封装了对象,并且被分别注入进来!

 

三、注解形式的结果返回

 1. 数据写到页面,方法的返回值采用ModelAndView, new ModelAndView("index", map);,相当于把结果数据放到response里面

url:http://localhost/mvc/test/toPerson41.do

url:http://localhost/mvc/test/toPerson42.do

url:http://localhost/mvc/test/toPerson43.do

url:http://localhost/mvc/test/toPerson44.do 

Java代码  收藏代码

  1. /** 

  2.  * HttpServletRequest可以直接定义在参数的列表,并且带回返回结果 

  3.  *  

  4.  */  

  5. @RequestMapping("/toPerson41.do")  

  6. public String toPerson41(HttpServletRequest request) throws Exception {  

  7.     request.setAttribute("p", newPesion());  

  8.     return "index";  

  9. }  

  10.   

  11. /** 

  12.  *  

  13.  * 方法的返回值采用ModelAndView, new ModelAndView("index", map); 

  14.  * ,相当于把结果数据放到Request里面,不建议使用 

  15.  *  

  16.  */  

  17. @RequestMapping("/toPerson42.do")  

  18. public ModelAndView toPerson42() throws Exception {  

  19.     Map<String, Object> map = new HashMap<String, Object>();  

  20.     map.put("p", newPesion());  

  21.     return new ModelAndView("index", map);  

  22. }  

  23.   

  24. /** 

  25.  *  

  26.  * 直接在方法的参数列表中来定义Map,这个Map即使ModelAndView里面的Map, 

  27.  * 由视图解析器统一处理,统一走ModelAndView的接口,也不建议使用 

  28.  */  

  29. @RequestMapping("/toPerson43.do")  

  30. public String toPerson43(Map<String, Object> map) throws Exception {  

  31.     map.put("p", newPesion());  

  32.     return "index";  

  33. }  

  34.   

  35. /** 

  36.  *  

  37.  * 在参数列表中直接定义Model,model.addAttribute("p", person); 

  38.  * 把参数值放到request类里面去,建议使用 

  39.  *  

  40.  */  

  41. @RequestMapping("/toPerson44.do")  

  42. public String toPerson44(Model model) throws Exception {  

  43.     // 把参数值放到request类里面去  

  44.     model.addAttribute("p", newPesion());  

  45.     return "index";  

  46. }  

  47.   

  48. /** 

  49.  * 为了测试,创建一个Persion对象 

  50.  *  

  51.  */  

  52. public Person newPesion(){  

  53.     Person person = new Person();  

  54.     person.setName("james");  

  55.     person.setAge(29);  

  56.     person.setAddress("maami");  

  57.     SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  

  58.     Date date = format.parse("1984-12-28");  

  59.     person.setBirthday(date);  

  60.     return person;  

  61. }  

  以上四种方式均能达到相同的效果,但在参数列表中直接定义Model,model.addAttribute("p", person);把参数值放到request类里面去,建议使用

 

2. Ajax调用springmvc的方法:直接在参数的列表上定义PrintWriter,out.write(result);把结果写到页面,建议使用的

 url:http://localhost/mvc/test/toAjax.do 

 

Java代码  收藏代码

  1.     /** 

  2.      *  

  3.      * ajax的请求返回值类型应该是void,参数列表里直接定义HttpServletResponse, 

  4.      * 获得PrintWriter的类,最后可把结果写到页面 不建议使用  

  5.      */  

  6.     @RequestMapping("/ajax1.do")  

  7.     public void ajax1(String name, HttpServletResponse response) {  

  8.         String result = "hello " + name;  

  9.         try {  

  10.             response.getWriter().write(result);  

  11.         } catch (IOException e) {  

  12.             e.printStackTrace();  

  13.         }  

  14.     }  

  15.   

  16.     /** 

  17.      *  

  18.      * 直接在参数的列表上定义PrintWriter,out.write(result); 

  19.      * 把结果写到页面,建议使用的  

  20.      *  

  21.      */  

  22.     @RequestMapping("/ajax2.do")  

  23.     public void ajax2(String name, PrintWriter out) {  

  24.         String result = "hello " + name;  

  25.         out.write(result);  

  26.     }  

  27.     /** 

  28.      * 转向ajax.jsp页面 

  29.      */  

  30.   

  31.     @RequestMapping("/toAjax.do")  

  32.    

  33.     public String toAjax() {  

  34.         return "ajax";  

  35.    }  

ajax页面代码如下:

Html代码  收藏代码

  1. <script type="text/javascript" src="js/jquery-1.6.2.js"></script>  

  2. <script type="text/javascript">  

  3.         $(function(){  

  4.             $("#mybutton").click(function(){  

  5.                 $.ajax({  

  6.                     url:"test/ajax1.do",  

  7.                     type:"post",  

  8.                     dataType:"text",  

  9.                     data:{  

  10.                         name:"zhangsan"  

  11.                     },  

  12.                     success:function(responseText){  

  13.                         alert(responseText);  

  14.                     },  

  15.                     error:function(){  

  16.                         alert("system error");  

  17.                     }  

  18.                 });  

  19.             });  

  20.         });  

  21.     </script>  

  22. </head>  

  23. <body>  

  24.     <input id="mybutton" type="button" value="click">  

  25. </body>  

  26.    

四、表单提交和重定向

1、表单提交:

请求方式的指定:@RequestMapping( method=RequestMethod.POST )可以指定请求方式,前台页面就必须要以它制定好的方式来访问,否则出现405错误

 表单jsp页面: 

Html代码  收藏代码

  1. <html>  

  2.   <head>  

  3.     <base href="<%=basePath%>">  

  4.     <title>SpringMVC Form</title>  

  5.   </head>  

  6.   <body>  

  7.     <form action="test/toPerson5.do" method="post">  

  8.         name:<input name="name" type="text"><br>  

  9.         age:<input name="age" type="text"><br>  

  10.         address:<input name="address" type="text"><br>  

  11.         birthday:<input name="birthday" type="text"><br>  

  12.         <input type="submit" value="submit"><br>  

  13.     </form>  

  14.   </body>  

  15. </html>  

 对应方法为:

Java代码  收藏代码

  1. /** 

  2.  * 转向form.jsp页面 

  3.  * @return 

  4.  */  

  5. @RequestMapping("/toform.do")  

  6. public String toForm() {  

  7.     return "form";  

  8. }  

  9.   

  10. /** 

  11.  *  

  12.  * @RequestMapping( method=RequestMethod.POST) 

  13.  * 可以指定请求方式,前台页面就必须要以它制定好的方式来访问,否则出现405错误 a 

  14.  *  

  15.  */  

  16. @RequestMapping(value = "/toPerson5.do", method = RequestMethod.POST)  

  17. public String toPerson5(Person person) {  

  18.     System.out.println(person);  

  19.     return "jsp1/index";  

  20. }  

 url:http://localhost/mvc/test/toform.do  

2. 重 定向:controller内部重定向,redirect:加上同一个controller中的requestMapping的值,controller 之间的重定向:必须要指定好controller的命名空间再指定requestMapping的值,redirect:后必须要加/,是从根目录开始

Java代码  收藏代码

  1. /** 

  2.  *  

  3.  * controller内部重定向 

  4.  * redirect:加上同一个controller中的requestMapping的值  

  5.  *  

  6.  */  

  7. @RequestMapping("/redirectToForm.do")  

  8. public String redirectToForm() {  

  9.     return "redirect:toform.do";  

  10. }  

  11.   

  12. /** 

  13.  *  

  14.  * controller之间的重定向:必须要指定好controller的命名空间再指定requestMapping的值, 

  15.  * redirect:后必须要加/,是从根目录开始 

  16.  */  

  17. @RequestMapping("/redirectToForm1.do")  

  18. public String redirectToForm1() {  

  19.               //test1表示另一个Controller的命名空间  

  20.     return "redirect:/test1/toForm.do";  

  21. }  



转载:http://alog2012.iteye.com/blog/2040214




      本文转自tianjian_0913 51CTO博客,原文链接:http://blog.51cto.com/tianjian/1668956,如需转载请自行联系原作者



相关文章
|
3天前
|
Java 开发者 Spring
深入理解Spring Boot的@ComponentScan注解
【4月更文挑战第22天】在构建 Spring Boot 应用时,@ComponentScan 是一个不可或缺的工具,它使得组件发现变得自动化和高效。这篇博客将详细介绍 @ComponentScan 的基本概念、关键属性及其在实际开发中的应用。
20 4
|
4天前
|
Java 开发者 Spring
Spring Framework 中的 @Autowired 注解:概念与使用方法
【4月更文挑战第20天】在Spring Framework中,@Autowired 注解是实现依赖注入(Dependency Injection, DI)的一种非常强大的工具。通过使用 @Autowired,开发者可以减少代码中的引用绑定,提高模块间的解耦能力
28 6
|
1月前
|
XML Java 数据库连接
spring boot 参数的过滤注解与实战
在Spring Boot应用中,对于入参的过滤,通常会涉及到对Web层的数据验证和处理。Spring Boot借助Spring框架提供了强大的验证框架支持,主要基于JSR-303/JSR-380(Bean Validation API)规范,以及Spring自身的@Valid或@Validated注解来实现请求参数的验证。以下是一些常见的使用案例来展示如何对参数进行过滤和验证。
29 1
|
1月前
|
Java Spring 容器
【Java】Spring如何扫描自定义的注解?
【Java】Spring如何扫描自定义的注解?
35 0
|
1月前
|
Java 测试技术 数据库
SpringBoot:@Profile注解和Spring EL
SpringBoot:@Profile注解和Spring EL
|
1月前
|
Java API 开发者
Spring中@import注解终极揭秘
在Spring框架中,@Import注解可以用来引入一个或多个组件,这些组件通常是通过@Bean注解定义的,当使用@Import注解时,实际上是在告诉Spring:“除了当前配置类中的bean定义外,还想包含另一个配置类(或多个配置类)中定义的bean。”
Spring中@import注解终极揭秘
|
2月前
|
监控 Java 调度
Spring中的任务调度:探索@Scheduled和@Schedules注解的威力
Spring中的任务调度:探索@Scheduled和@Schedules注解的威力
37 0
|
1月前
|
存储 缓存 Java
【Spring原理高级进阶】有Redis为啥不用?深入剖析 Spring Cache:缓存的工作原理、缓存注解的使用方法与最佳实践
【Spring原理高级进阶】有Redis为啥不用?深入剖析 Spring Cache:缓存的工作原理、缓存注解的使用方法与最佳实践
|
1月前
|
Java 数据库 Spring
【spring(四)】Spring事务管理和@Transactional注解
【spring(四)】Spring事务管理和@Transactional注解
|
1月前
|
Java Spring 容器
Spring中@Autowired和@Resource注解异同点
Spring中@Autowired和@Resource注解异同点
31 0