SpringMVC轻松学习-注解的使用(三)
            时间:2014-04-30 13:49:15  
            收藏:0  
            阅读:625
        
        
        根据上一讲的例子,我们下面就注解的使用进行详细说明。
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
        
        我们采用sprng MVC开发项目时,通常都会采用注解的方式,这样可以大大提高我们的开发效率。实现零配置。下面我们从零开始重新做一个spring MVC的配置。这个项目完全采用注解的方式开发。同时,我们以后的spring MVC项目也都会采用注解的方式。
修改web.xml,文件内容如下:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?xmlversion="1.0"encoding="UTF-8"?><web-appversion="2.5"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     <servlet>        <servlet-name>springmvc</servlet-name>        <servlet-class>            org.springframework.web.servlet.DispatcherServlet        </servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>/WEB-INF/hib-config.xml,/WEB-INF/springmvc-servlet.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></web-app> | 
springmvc-servlet.xml配置内容如下:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?xmlversion="1.0"encoding="UTF-8"?><beans    xsi:schemaLocation="http://www.springframework.org/schema/beans          <!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->    <context:component-scanbase-package="com.sxt"/>    <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->    <beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>    <!--对模型视图名称的解析,即在模型视图名称添加前后缀 -->    <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"        p:suffix=".jsp"/></beans> | 
hib-config.xml(配置了spring集成hibernate)
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | <?xmlversion="1.0"encoding="UTF-8"?>    xsi:schemaLocation="">    <context:component-scanbase-package="com.sxt"/>       <!-- 支持aop注解 -->    <aop:aspectj-autoproxy/>                <beanid="dataSource"            class="org.apache.commons.dbcp.BasicDataSource">              <propertyname="driverClassName"                value="com.mysql.jdbc.Driver">              </property>              <propertyname="username"value="root"></property>              <propertyname="password"value="123456"></property>    </bean>     <beanid="sessionFactory"       class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">             <propertyname="dataSource">                 <refbean="dataSource"/>             </property>           <propertyname="hibernateProperties">                 <props>                  <!-- key的名字前面都要加hibernate. -->                   <propkey="hibernate.dialect">                         org.hibernate.dialect.MySQLDialect                     </prop>                     <propkey="hibernate.show_sql">true</prop>                   <propkey="hibernate.hbm2ddl.auto">update</prop>               </props>           </property>        <propertyname="packagesToScan">            <value>com.sxt.po</value>        </property>   </bean>  <beanid="hibernateTemplate"class="org.springframework.orm.hibernate3.HibernateTemplate">    <propertyname="sessionFactory"ref="sessionFactory"></property></bean><!--配置一个JdbcTemplate实例--><beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">        <propertyname="dataSource"ref="dataSource"/>   </bean>  <!-- 配置事务管理 --><beanid="txManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">    <propertyname="sessionFactory"ref="sessionFactory"></property></bean><tx:annotation-driventransaction-manager="txManager"/><aop:config>     <aop:pointcutexpression="execution(public * com.sxt.service.impl.*.*(..))"id="businessService"/>     <aop:advisoradvice-ref="txAdvice"pointcut-ref="businessService"/> </aop:config> <tx:adviceid="txAdvice"transaction-manager="txManager">     <tx:attributes>         <tx:methodname="find*"read-only="true"propagation="NOT_SUPPORTED"/>         <!-- get开头的方法不需要在事务中运行 。         有些情况是没有必要使用事务的,比如获取数据。开启事务本身对性能是有一定的影响的-->        <tx:methodname="*"/>    <!-- 其他方法在实务中运行 -->    </tx:attributes> </tx:advice> </beans> | 
reg.jsp如下
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <%@ page language="java"import="java.util.*"pageEncoding="gbk"%><%Stringpath = request.getContextPath();StringbasePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">         <title>My JSP ‘index.jsp‘starting page</title>    <meta http-equiv="pragma"content="no-cache">    <meta http-equiv="cache-control"content="no-cache">    <meta http-equiv="expires"content="0">       <meta http-equiv="keywords"content="keyword1,keyword2,keyword3">    <meta http-equiv="description"content="This is my page">    <!--    <link rel="stylesheet"type="text/css"href="styles.css">    -->  </head>     <body><form action="user.do">  用户名:<input type=text name=uname /><br/><input type=hidden name=method value=reg /><input type=submit value=注册 /></form>  </body></html> | 
index.jsp 如下:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <%@ page language="java"import="java.util.*"pageEncoding="gbk"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP ‘index.jsp‘starting page</title>    <meta http-equiv="pragma"content="no-cache">    <meta http-equiv="cache-control"content="no-cache">    <meta http-equiv="expires"content="0">        <meta http-equiv="keywords"content="keyword1,keyword2,keyword3">    <meta http-equiv="description"content="This is my page">    <!--    <link rel="stylesheet"type="text/css"href="styles.css">    -->  </head>    <body>   <h1>**********${params.uname}</h1>   <h1>**********${requestScope.u}</h1>   <h1>**********${requestScope.user}</h1>  </body></html> | 
User.java
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | packagecom.sxt.po;importjavax.persistence.Entity;importjavax.persistence.GeneratedValue;importjavax.persistence.GenerationType;importjavax.persistence.Id;@EntitypublicclassUser {    @Id    @GeneratedValue(strategy=GenerationType.AUTO)    privateintid;    privateString uname;    privateString pwd;            publicString getPwd() {        returnpwd;    }    publicvoidsetPwd(String pwd) {        this.pwd = pwd;    }    publicintgetId() {        returnid;    }    publicvoidsetId(intid) {        this.id = id;    }    publicString getUname() {        returnuname;    }    publicvoidsetUname(String uname) {        this.uname = uname;    }        } | 
UserDao.java
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | packagecom.sxt.dao;importjavax.annotation.Resource;importorg.springframework.orm.hibernate3.HibernateTemplate;importorg.springframework.stereotype.Repository;importcom.sxt.po.User;@Repository("userDao")publicclassUserDao {    @Resource    privateHibernateTemplate hibernateTemplate;        publicvoidadd(User u){        System.out.println("UserDao.add()");        hibernateTemplate.save(u);    }    publicHibernateTemplate getHibernateTemplate() {        returnhibernateTemplate;    }    publicvoidsetHibernateTemplate(HibernateTemplate hibernateTemplate) {        this.hibernateTemplate = hibernateTemplate;    }    } | 
UserService.Java
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | packagecom.sxt.service;importjavax.annotation.Resource;importorg.springframework.stereotype.Service;importcom.sxt.dao.UserDao;importcom.sxt.po.User;@Service("userService")publicclassUserService {    @Resource    privateUserDao userDao;        publicvoidadd(String uname){        System.out.println("UserService.add()");        User u = newUser();        u.setUname(uname);        userDao.add(u);    }    publicUserDao getUserDao() {        returnuserDao;    }    publicvoidsetUserDao(UserDao userDao) {        this.userDao = userDao;    }    } | 
UserController.java
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | packagecom.sxt.web;importjavax.annotation.Resource;importorg.springframework.stereotype.Controller;importorg.springframework.ui.ModelMap;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.SessionAttributes;importcom.sxt.po.User;importcom.sxt.service.UserService;@Controller("userController")//这里的@RequestMapping("/user.do")     publicclassUserController  {    @Resource    privateUserService userService;        @RequestMapping(params="method=reg")     publicString reg(String uname) {        System.out.println("HelloController.handleRequest()");        userService.add(uname);         return"index";    }        publicUserService getUserService() {        returnuserService;    }    publicvoidsetUserService(UserService userService) {        this.userService = userService;    }    } | 
说明:
  - @Controller("userController")这里也可以使用component进行注解,这里的controller和component一样,但是一般不用component,而这样的注解还@Repository、@Service、@Controller大家估计都知道怎么使用了,不会的话看我的之前发的blog:http://www.cnblogs.com/wang3680/p/0f4eea023d8eb01b097c732fddba5725.html
- @RequestMapping("/user.do") 
  注解说明:这个注解是页面提交到user.dao中进行操作的controller,之前我们的controller还需要进行实现controller接口,而现在不需要实现此接口了,而且controller里面的函数也不需要去复写handleRequest方法了,这里我们就可以自己写自己的方法了,但是我们怎么知道页面提交给那个方法了呢?
- @RequestMapping(params="method=reg")说明:这个注解就是去解释页面提交的给了那个方法的,就是提交来的带有method=reg的就会调转到此方法中,我们上面的页面中是这样定义传值的<input type=hidden name=method value=reg />
- 问题又来啦,struts2中我们是根据属性的set和get方法得到我们传递来的值得,这里怎么办呢?我们在controller方法中添加参数将传递的值传递来,public String reg(String uname) 
  这里的命名必须和页面传来的对应上。
上面的controller中,我们传递的是uname,我们这样呢,将参数改成User user为public String reg(User user)
 
| 1 2 3 4 5 6 | @RequestMapping(params="method=reg2")   publicStringreg(User user) {       System.out.println("HelloController.handleRequest()");       userService.add(user.getUname());       return"index";   } | 
说明:
这里呢其实是将User模型中的属性拿来用了,我们必须保证页面定义的名称和模型中的一样才行,这一点类此与struts2里面的模型驱动
            评论(0)
        
        
        