Struts2+Spring3+MyBatis3整合以及Spring注解开发

 分类:

最近在做一个SpringMVC+spring+MyBatis的项目,突然想起以前自己要搭建一个Struts2+Spring+IBatis的框架,但是没成功,正好看见培训时候老师给的千里之行的开源项目。于是将这个项目提供的SQL加入到了自己的数据库中(所以数据和项目名用的是qlzx),打算以后做练习的时候用这个数据库。那么接下来问题来了(不要说某翔或者不约,不是那个问题):我有了数据库和数据,想要搭建一个网站,该怎么做?

1、环境

IDE

Eclipse Kepler(4.3.1)

Server

Tomcat 6.0

Struts

2.2.3.1

Spring

3.0.6

MyBatis

3.0.6

Database

MySQL 5.5

DB驱动

mysql-connector-Java-5.1.27

测试工具

JUnit 4 (Eclipse自带)

特别说明:因为Struts2在13年爆出了一个严重的安全漏洞,导致黑客可能获取网站最高权限(相关消息:http://news.mydrivers.com/1/269/269596.htmhttp://it.sohu.com/20130718/n381990046.shtml),所以真实建站时需要将Struts2升级至2.3.15.1或以上版本。这里因为是demo,所以仍然使用2.2.3.1。

2、需要的包

3、开发步骤

项目结构:

路径

功能

说明

action.base

包下的Action类为其他Action类的BaseAction,继承ActionSupport。

这个类中提供一些其他Action中的通用的方法。如果有这个类存在,那么其他Action类应该继承此包下的BaseAction。

action

存放所有Action类的包

如果没有写BaseAction的话则应该继承ActionSupport,否则此包下的所有类都应该继承BaseAction。

bean包为存放Java实体类的包。

dao.basedao

规定其他所有dao类的方法。

此包下的类应该为接口。

dao

dao的接口

因为使用MyBatis,所以不提供实现类。此包中的接口应该继承BaseDao。其中的方法名必须要和MyBatisMapper文件中的id大小写一致

service

服务层的接口。

service.impl

服务层的实现类。

utils

工具包。

conf

文件夹,存放基本配置。

comf.mapper

文件夹,存放mybatis的配置文件。


配置文件:

db.properties:

spy.properties

[plain] view plain copy
 
  1. module.log=com.p6spy.engine.logging.P6LogFactory  
  2. #module.outage=com.p6spy.engine.outage.P6OutageFactory  
  3.   
  4. # the mysql open source driver  
  5. #realdriver=com.mysql.jdbc.Driver  
  6. realdriver= com.mysql.jdbc.Driver  
  7.   
  8. #the DriverManager class sequentially tries every driver that is  
  9. #registered to find the right driver.  In some instances, it's possible to  
  10. #load up the realdriver before the p6spy driver, in which case your connections  
  11. #will not get wrapped as the realdriver will "steal" the connection before  
  12. #p6spy sees it.  Set the following property to "true" to cause p6spy to  
  13. #explicitily deregister the realdrivers  
  14. deregisterdrivers=true  
  15.   
  16. # outagedetection=true|false  
  17. # outagedetectioninterval=integer time (seconds)  
  18. #  
  19. outagedetection=false  
  20.   
  21. # filter what is logged  
  22. filter=false  
  23.   
  24. # turn on tracing  
  25. autoflush   = true  
  26.   
  27. # sets the date format using Java's SimpleDateFormat routine  
  28. dateformat=yyyy-MM-dd HH:mm:ss:SS  
  29.   
  30. #list of categories to explicitly include   
  31. includecategories=error,statement  
  32.   
  33. #list of categories to exclude: error, info, batch, debug, statement,  
  34. #commit, rollback and result are valid values  
  35. excludecategories=info,debug,result,batch,resultset,commit  
  36.   
  37. # prints a stack trace for every statement logged  
  38. stacktrace=false  
  39. # if stacktrace=true, specifies the stack trace to print  
  40. stacktraceclass=  
  41.   
  42. # determines if property file should be reloaded  
  43. reloadproperties=false  
  44. # determines how often should be reloaded in seconds  
  45. reloadpropertiesinterval=60  
  46.   
  47. #if=true then url must be prefixed with p6spy:  
  48. useprefix=false  
  49.   
  50. #specifies the appender to use for logging  
  51. appender=com.p6spy.engine.logging.appender.StdoutLogger  
  52.   
  53. append=true  
  54.   
  55. #The following are for log4j logging only  
  56. log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender  
  57. log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout  
  58. log4j.appender.STDOUT.layout.ConversionPattern=p6spy - %m%n  
  59.   
  60. log4j.logger.p6spy=INFO,STDOUT  

这里使用到了一个包,叫p6spy.jar。

P6Spy 是针对数据库访问操作的动态监测框架(为开源项目,项目首页:www.p6spy.com)它使得数据库数据可无缝截取和操纵,而不必对现有应用程序的代码作任何修改。P6Spy 分发包包括P6Log,它是一个可记录任何 Java 应用程序的所有JDBC事务的应用程序。其配置完成使用时,可以进行数据访问性能的监测。

我们最需要的功能,查看sql语句,不是预编译的带问号的哦,而是真正的数据库执行的sql,更直观,更简单。

这个包主要用于调试sql,很方便。

web.xml:


[html] view plain copy
 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  
  3.   <display-name>qlzx</display-name>  
  4.   <welcome-file-list>  
  5.     <welcome-file>index.jsp</welcome-file>  
  6.   </welcome-file-list>  
  7.   <filter>  
  8.     <filter-name>struts2</filter-name>  
  9.     <filter-class>  
  10.         org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter  
  11.     </filter-class>  
  12.     <init-param>  
  13.         <param-name>config</param-name>  
  14.         <param-value>struts-default.xml,struts-plugin.xml,struts.xml</param-value>  
  15.     </init-param>  
  16. </filter>  
  17. <filter-mapping>  
  18.     <filter-name>struts2</filter-name>  
  19.     <url-pattern>/*</url-pattern>  
  20. </filter-mapping>  
  21.  <context-param>  
  22.     <param-name>contextConfigLocation</param-name>  
  23.     <param-value>classpath:applicationContext.xml</param-value>  
  24.   </context-param>  
  25.  <filter>  
  26.       <filter-name>encodingFilter</filter-name>  
  27.       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  28.       <init-param>  
  29.        <param-name>encoding</param-name>  
  30.        <param-value>utf-8</param-value>  
  31.       </init-param>  
  32.    </filter>  
  33.    <filter-mapping>  
  34.       <filter-name>encodingFilter</filter-name>  
  35.       <url-pattern>/*</url-pattern>  
  36.    </filter-mapping>  
  37. <!-- 配置监听 -->  
  38.   <listener>  
  39.     <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
  40.   </listener>  
  41.   <listener>  
  42.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  43.   </listener>  
  44.   
  45.   
  46.   <!-- 配置错误页面 -->  
  47.   <error-page>  
  48.     <error-code>500</error-code>  
  49.     <location>/commons/error.jsp</location>  
  50.   </error-page>  
  51.   <error-page>  
  52.     <error-code>404</error-code>  
  53.     <location>/commons/404.jsp</location>  
  54.   </error-page>  
  55.   <error-page>  
  56.     <error-code>403</error-code>  
  57.     <location>/commons/403.jsp</location>  
  58.   </error-page>  
  59.   
  60. </web-app>  

applicationContext.xml

[html] view plain copy
 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  5.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  6.     http://www.springframework.org/schema/context  
  7.     http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  8.   
  9.     <import resource="datasource.xml" />  
  10.   
  11.     <context:annotation-config/>  
  12.     <context:component-scan base-package="com.qlzx"></context:component-scan>  
  13.   
  14.     <!-- 配置mybatis的sqlsessionFactory -->  
  15.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  16.         <property name="dataSource" ref="dataSource" />  
  17.         <property name="configLocation" value="classpath:conf/MapperConfig.xml" />  
  18.     </bean>  
  19.   
  20.     <!--配置 mybatis的映射器 方式一 -->  
  21.     <!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">   
  22.         <property name="sqlSessionFactory" ref="sqlSessionFactory"/> <property name="mapperInterface"   
  23.         value="org.ko.webservice.dao.UserMapper"/> </bean> -->  
  24.   
  25.     <!-- 配置 mybatis的映射器 方式二:也可不指定特定mapper,而使用自动扫描包的方式来注册各种Mapper ,配置如下: -->  
  26.     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  27.         <property name="basePackage" value="com.qlzx" />  
  28.         <property name="sqlSessionFactory" ref="sqlSessionFactory" />  
  29.         <property name="annotationClass" value="org.springframework.stereotype.Component" />  
  30.     </bean>  
  31.   
  32.     <!-- bean class="org.mybatis.spring.annotation.MapperScannerPostProcessor">   
  33.         <property name="basePackage" value="org.ko.webservice.dao" /> </bean -->  
  34.   
  35.   
  36.     <!-- 配置事务管理 -->  
  37.     <bean id="transactionManager"  
  38.         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  39.         <property name="dataSource">  
  40.             <ref bean="dataSource" />  
  41.         </property>  
  42.     </bean>  
  43. <!-- tx:annotation-driven transaction-manager="transactionManager" / -->  
  44.   
  45.     <!-- 配置事务代理拦截器 -->  
  46.     <bean id="transactionInterceptor"  
  47.         class="org.springframework.transaction.interceptor.TransactionInterceptor">  
  48.         <property name="transactionManager" ref="transactionManager" />  
  49.         <property name="transactionAttributes">  
  50.             <props>  
  51.                 <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>  
  52.                 <prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>  
  53.                 <prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>  
  54.                 <prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>  
  55.                 <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>  
  56.                 <prop key="del*">PROPAGATION_REQUIRED,-Exception</prop>  
  57.                 <prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>  
  58.                 <prop key="remove*">PROPAGATION_REQUIRED,-Exception</prop>  
  59.                 <prop key="query*">PROPAGATION_REQUIRED, readOnly,-Exception</prop>  
  60.                 <prop key="search*">PROPAGATION_REQUIRED, readOnly,-Exception</prop>  
  61.                 <prop key="select*">PROPAGATION_REQUIRED, readOnly,-Exception</prop>  
  62.                 <prop key="get*">PROPAGATION_REQUIRED, readOnly,-Exception</prop>  
  63.                 <prop key="load*">PROPAGATION_REQUIRED, -Exception</prop>  
  64.                 <prop key="*">readOnly</prop>  
  65.             </props>  
  66.         </property>  
  67.     </bean>  
  68.   
  69.     <!-- 配置要拦截哪些方法 -->  
  70.     <bean id="trasactionMethodPointcutAdvisor"  
  71.         class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">  
  72.         <property name="mappedNames">  
  73.             <list>  
  74.                 <value>*</value<!-- 所有方法 -->  
  75.             </list>  
  76.         </property>  
  77.         <property name="advice">  
  78.             <ref local="transactionInterceptor" />  
  79.         </property>  
  80.     </bean>  
  81.   
  82.     <!-- 配置要拦截哪些类,并使用那些拦截器 -->  
  83.     <bean id="ServiceAutoProxyCreator"  
  84.         class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">  
  85.         <property name="proxyTargetClass" value="true"></property>  
  86.         <property name="beanNames">  
  87.             <list>  
  88.                 <value>*Service*</value>  
  89.             </list>  
  90.         </property>  
  91.         <property name="interceptorNames">  
  92.             <list>  
  93.                 <value>trasactionMethodPointcutAdvisor</value>  
  94.             </list>  
  95.         </property>  
  96.     </bean>  
  97. </beans>  

其中最开始的两段:

<context:annotation-config/>

      <context:component-scanbase-package="com.qlzx"></context:component-scan>

这两段是告诉Spring使用注解配置,扫描哪个包下的类中的注解。我这里的项目使用到了注解,所以必须要写这两句。同时,如果需要Struts2和MyBaties支持的话,那么就必须用到两个包:mybaties-spring-1.0.0.jar和struts2-spring-plugin.jar。

mybatis-spring-1.x.x.jar用于将mybatis无缝整合到Spring中。使用这个包需要用到java5+以及Spring3.0+的版本。版本的对应关系如下图:

根据这张表,因为我的MyBatis版本为3.0.6,所以使用mybatis-spring-1.0.2.jar

关于mybatis-spring.jar的简介、使用、以及API等更多信息,请参阅官网:http://mybatis.github.io/spring/zh/index.html

至于struts2-spring-plugin.jar不多说了,这个是用于整个Struts2和Spring的,这个包在Struts2的包中应该是有的,没有的话那就随便去网上下一个吧。

datasource.xml

[html] view plain copy
 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  5.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  6.   
  7.   
  8.   
  9.     <bean id="configurer"  
  10.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  11.         <property name="location">  
  12.             <value>classpath:conf/db.properties</value>  
  13.         </property>  
  14.     </bean>  
  15.   
  16.     <!-- 配置数据源 -->  
  17.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"  
  18.         destroy-method="close">  
  19.   
  20.         <property name="driverClass">  
  21.             <value>com.p6spy.engine.spy.P6SpyDriver</value>  
  22.         </property>  
  23.         <property name="jdbcUrl">  
  24.             <value>${jdbc.url}</value>  
  25.         </property>  
  26.         <property name="user">  
  27.             <value>${jdbc.username}</value>  
  28.         </property>  
  29.         <property name="password">  
  30.             <value>${jdbc.password}</value>  
  31.         </property>  
  32.   
  33.   
  34.         <!--连接池中保留的最小连接数。 -->  
  35.         <property name="minPoolSize">  
  36.             <value>2</value>  
  37.         </property>  
  38.   
  39.         <!--连接池中保留的最大连接数。Default: 15 -->  
  40.         <property name="maxPoolSize">  
  41.             <value>15</value>  
  42.         </property>  
  43.   
  44.         <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->  
  45.         <property name="initialPoolSize">  
  46.             <value>2</value>  
  47.         </property>  
  48.   
  49.         <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->  
  50.         <property name="maxIdleTime">  
  51.             <value>1800</value>  
  52.         </property>  
  53.   
  54.         <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->  
  55.         <property name="acquireIncrement">  
  56.             <value>2</value>  
  57.         </property>  
  58.   
  59.         <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。   
  60.             如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->  
  61.         <property name="maxStatements">  
  62.             <value>0</value>  
  63.         </property>  
  64.   
  65.         <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->  
  66.         <property name="idleConnectionTestPeriod">  
  67.             <value>0</value>  
  68.         </property>  
  69.   
  70.         <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->  
  71.         <property name="acquireRetryAttempts">  
  72.             <value>30</value>  
  73.         </property>  
  74.   
  75.         <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试   
  76.             获取连接失败后该数据源将申明已断开并永久关闭。Default: false -->  
  77.         <property name="breakAfterAcquireFailure">  
  78.             <value>false</value>  
  79.         </property>  
  80.   
  81.         <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable   
  82.             等方法来提升连接测试的性能。Default: false -->  
  83.         <property name="testConnectionOnCheckout">  
  84.             <value>false</value>  
  85.         </property>  
  86.   
  87.         <property name="debugUnreturnedConnectionStackTraces">  
  88.             <value>false</value>  
  89.         </property>  
  90.   
  91.         <property name="acquireRetryDelay">  
  92.             <value>100</value>  
  93.         </property>  
  94.     </bean>  
  95.   
  96. </beans>  

这个xml因为有注释,一看即明,不再赘述。使用到了c3p0连接池,所以记得引入c3p0.jar

datasource.xml和applicationContext.xml两个XML中有一个需要注意的细节就是:其中所有标签的属性,键和值之间不能有空格或者换行存在。如以下三种情况是错误的:
[html] view plain copy
 
  1. <value>false </value>  
[html] view plain copy
 
  1. <value>false  
  2. </value>  
[html] view plain copy
 
  1. <property name = "acquireRetryDelay">  

空格不容易被发现,但是却影响程序运行,所以平时要养成良好的习惯。

struts.xml

[html] view plain copy
 
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">  
  3. <struts>  
  4.     <!-- 请求参数的编码方式 -->  
  5.   
  6.     <constant name="struts.i18n.encoding" value="UTF-8" />  
  7.   
  8.     <!-- 指定被struts2处理的请求后缀类型。多个用逗号隔开 -->  
  9.   
  10.     <constant name="struts.action.extension" value="action,do,htm" />  
  11.   
  12.     <!-- 当struts.xml改动后,是否重新加载。默认值为false(生产环境下使用),开发阶段最好打开 -->  
  13.   
  14.     <constant name="struts.configuration.xml.reload" value="true" />  
  15.   
  16.     <!-- 是否使用struts的开发模式。开发模式会有更多的调试信息。默认值为false(生产环境下使用),开发阶段最好打开 -->  
  17.   
  18.     <constant name="struts.devMode" value="true" />  
  19.   
  20.     <!-- 设置浏览器是否缓存静态内容。默认值为true(生产环境下使用),开发阶段最好关闭 -->  
  21.   
  22.     <constant name="struts.serve.static.browserCache" value="false" />  
  23.   
  24.     <!-- 指定由spring负责action对象的创建 -->  
  25.   
  26.     <constant name="struts.objectFactory" value="spring" />  
  27.   
  28.     <!-- 是否开启动态方法调用 -->  
  29.     <constant name="struts.enable.DynamicMethodInvocation" value="false" />  
  30.   
  31. </struts>    

这个唯一要说的就是,因为项目使用注解配置Action,所以这里就不再配置Action。

MapperConfig.xml

[html] view plain copy
 
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" >  
  3. <configuration>  
  4.     <mappers>  
  5.         <mapper resource="conf/mapper/PublicMapper.xml" />  
  6.     </mappers>  
  7. </configuration>  

这个文件的作用就是引入其他的Mabits的xml配置文件,如果写多个的话在这里添加即可。

PublicMapper.xml

[html] view plain copy
 
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >  
  3. <mapper namespace="com.qlzx.dao.UserDao">  
  4.     <resultMap id="userlist" type="com.qlzx.bean.Users">  
  5.             <id column="id" property="id" />  
  6.             <result column="USERNAME" property="userName" />  
  7.             <result column="USERPWD" property="userPwd" />  
  8.     </resultMap>  
  9.   
  10.     <!-- 公共查询 记录数 -->  
  11.     <select id="selectUsers" parameterType="java.util.Map"  
  12.         resultMap="userlist">  
  13.         select ID,USERNAME,USERPWD from USERINFO where 1=1  
  14.         <if test="action == 'login'">  
  15.             <if test="userName != null and userPwd != ''">  
  16.                 and USERNAME = #{userName}  
  17.                 and USERPWD = #{password}  
  18.             </if>  
  19.         </if>  
  20.     </select>  
  21.   
  22.     <!-- 公共 查询 记录集合 -->  
  23.     <select id="selectByMap" resultType="java.util.HashMap"  
  24.         parameterType="java.util.Map">  
  25.   
  26.     </select>  
  27.   
  28. </mapper>  

这个文件也没什么好说的。mapper标签里的namespace是指向Dao的。resultMap是告诉MyBatis查出来的结果和bean的对应关系。具体用法在网上有一大堆,不再赘述。

我在这里接收的参数全都是HashMap。因为这样可以比较灵活。在select中的if中的判断条件,其中acton是存在参数集合中的key,意思是如果传来的参数中有一个action的key并且其value为login的话,那么sql中就添加if中的那些,如果没有的话那么就只执行外面那个。这样做的好处是,如果是登陆的话,那么在参数map中可以放三个键值对,分别是action、userName、password。如果我需要查询所有用户的集合的话,那么只需要穿一个空的参数集合即可(能不能穿null还未测试)。

另外还有一点要说的就是,resultMap。这里的resultMap是上面定义好的resultMap,值和上面定义的resultMap的id对应。如果是具体的类型的话,那么需要将resultMap改成resultType。使用resultMap的结果自动为集合,哪怕只有一个前台也可以使用List来接收。

代码:

DAO层:

BaseDao:因为我这里有一个basedao,所以这里先贴出basedao的代码。

[java] view plain copy
 
  1. package com.qlzx.dao.basedao;  
  2. import java.io.Serializable;  
  3. import java.util.List;  
  4.   
  5. import org.apache.ibatis.annotations.Param;  
  6.   
  7. public abstract interface BaseDao<T, E, PK extends Serializable>  
  8. {  
  9.   public abstract int countByExample(E paramE);  
  10.   
  11.   public abstract List<T> query();  
  12.   
  13.   public abstract int deleteByExample(E paramE);  
  14.   
  15.   public abstract int deleteByPrimaryKey(PK paramPK);  
  16.   
  17.   public abstract int insert(T paramT);  
  18.   
  19.   public abstract int insertSelective(T paramT);  
  20.   
  21.   public abstract List<T> selectByExample(E paramE);  
  22.   
  23.   public abstract T selectByPrimaryKey(PK paramPK);  
  24.   
  25.   public abstract int updateByExampleSelective(@Param("record") T paramT, @Param("example") E paramE);  
  26.   
  27.   public abstract int updateByExample(@Param("record") T paramT, @Param("example") E paramE);  
  28.   
  29.   public abstract int updateByPrimaryKeySelective(T paramT);  
  30.   
  31.   public abstract int updateByPrimaryKey(T paramT);  
  32.   
  33.   public abstract List<T> selectByExampleWithBLOBs(E paramE);  
  34.   
  35.   public abstract int updateByPrimaryKeyWithBLOBs(T paramT);  
  36. }  

UserDao

[java] view plain copy
 
  1. package com.qlzx.dao;  
  2.   
  3. import java.math.BigDecimal;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import org.springframework.stereotype.Repository;  
  8.   
  9. import com.qlzx.bean.Users;  
  10. import com.qlzx.dao.basedao.BaseDao;  
  11. @Repository  
  12. public interface UserDao extends BaseDao<Users, Map<String,?>, BigDecimal> {  
  13.     public abstract List<Users> selectUsers(Map<String ,?> paramMap);  
  14.     public abstract int insert (Map<String,?>paramMap);  
  15.     public abstract int delete(Map<String,?> paramMap);  
  16.     public abstract int updateByMap(Map<String,?> paramMap);  
  17. }  

注意这个Dao只是一个接口。前面说过,因为具体的查询已经在xml中配置了,所以这个接口不需要写实现类,直接调用方法即可。这个dao的包名和xml中的namespace对应,方法名和对应xml中的id对应,包括大小写。

Service:

UserService

[java] view plain copy
 
  1. package com.qlzx.service;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import com.qlzx.bean.Users;  
  7.   
  8. public abstract class UserService {  
  9.     public abstract List<Users> selectUsers(Map<String ,?> paramMap);  
  10.     public abstract int insert (Map<String,?>paramMap);  
  11.     public abstract int delete(Map<String,?> paramMap);  
  12.     public abstract int updateByMap(Map<String,?> paramMap);  
  13. }  

Service接口,不需要多讲。

UserServiceImpl:

[java] view plain copy
 
  1. package com.qlzx.service.impl;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import javax.annotation.Resource;  
  7.   
  8. import org.springframework.stereotype.Service;  
  9.   
  10. import com.qlzx.bean.Users;  
  11. import com.qlzx.dao.UserDao;  
  12. import com.qlzx.service.UserService;  
  13.   
  14. @Service  
  15. public class UserServiceImpl extends UserService {  
  16.   
  17.     @Resource  
  18.     public UserDao dao;  
  19.   
  20.     public void setDao(UserDao dao) {  
  21.         this.dao = dao;  
  22.     }  
  23.   
  24.     @Override  
  25.     public List<Users> selectUsers(Map<String, ?> paramMap) {  
  26.         return dao.selectUsers(paramMap);  
  27.     }  
  28.   
  29.     @Override  
  30.     public int insert(Map<String, ?> paramMap) {  
  31.         return 0;  
  32.     }  
  33.   
  34.     @Override  
  35.     public int delete(Map<String, ?> paramMap) {  
  36.         return 0;  
  37.     }  
  38.   
  39.     @Override  
  40.     public int updateByMap(Map<String, ?> paramMap) {  
  41.         return 0;  
  42.     }  
  43.   
  44. }  

Service实现类,同样不需要多讲。

BaseAction

[java] view plain copy
 
  1. package com.qlzx.action.base;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import javax.servlet.http.HttpServletResponse;  
  5.   
  6. import org.apache.struts2.interceptor.ServletRequestAware;  
  7. import org.apache.struts2.interceptor.ServletResponseAware;  
  8.   
  9. import com.opensymphony.xwork2.ActionSupport;  
  10.   
  11. public class BaseAction extends ActionSupport implements ServletRequestAware,  
  12.         ServletResponseAware {  
  13.     private static final long serialVersionUID = 7079198825973108720L;  
  14.     protected HttpServletRequest request;  
  15.     protected HttpServletResponse response;  
  16.     @Override  
  17.     public void setServletResponse(HttpServletResponse response) {  
  18.         this.response = response;  
  19.     }  
  20.   
  21.     @Override  
  22.     public void setServletRequest(HttpServletRequest request) {  
  23.         this.request = request;  
  24.     }  
  25. }  

这个类要说明的是除了继承ActionSupport以外,还实现了两个接口:ServletRequestAware,ServletResponseAware 。这两个接口用于IOC自动注入HttpServletRequest和HttpServletResponse。因为Action中可能对Session、Response和Request进行操作,所以在BaseAction中实现了这两个接口。获取Session、Request和Response除了这个方法以外还可以通过ActionContext获得。

 

 

PublicController:

[java] view plain copy
 
  1. package com.qlzx.action;  
  2.   
  3. import java.awt.image.BufferedImage;  
  4. import java.io.ByteArrayInputStream;  
  5. import java.io.ByteArrayOutputStream;  
  6. import java.io.IOException;  
  7. import java.util.HashMap;  
  8. import java.util.List;  
  9. import java.util.Map;  
  10.   
  11. import javax.annotation.Resource;  
  12. import javax.servlet.http.HttpServletResponse;  
  13. import javax.servlet.http.HttpSession;  
  14.   
  15. import net.sf.json.JSONArray;  
  16.   
  17. import org.apache.struts2.convention.annotation.Action;  
  18. import org.apache.struts2.convention.annotation.ParentPackage;  
  19. import org.apache.struts2.convention.annotation.Result;  
  20. import org.springframework.stereotype.Controller;  
  21.   
  22. import com.opensymphony.xwork2.ActionContext;  
  23. import com.qlzx.action.base.BaseAction;  
  24. import com.qlzx.bean.Users;  
  25. import com.qlzx.service.UserService;  
  26. import com.qlzx.utils.RandomPic;  
  27. import com.qlzx.utils.Util;  
  28. import com.sun.image.codec.jpeg.ImageFormatException;  
  29. import com.sun.image.codec.jpeg.JPEGCodec;  
  30. import com.sun.image.codec.jpeg.JPEGImageEncoder;  
  31.   
  32. @Controller  
  33. @ParentPackage(value="json-default")  
  34. public class PublicController extends BaseAction {  
  35.   
  36.     private static final long serialVersionUID = -1941557452311902440L;  
  37.     @Resource  
  38.     UserService userService;  
  39.     private String userName;  
  40.     private String password;  
  41.     private String formid;  
  42.     private String resultJson;  
  43.     private String code;  
  44.     private ByteArrayInputStream imageStream;  
  45.       
  46.     @Action(value = "login", results = {   
  47.             @Result(name = "success", location = "/message.jsp") ,  
  48.             @Result(name = "failed",type="json",params={"root","resultJson"})  
  49.     })   
  50.     public String login() {  
  51.         Map<String,Object> paramMap = new HashMap<String,Object>();  
  52.         Map<String, ?> session = (Map<String, ?>) ActionContext.getContext()  
  53.                 .getSession();  
  54.         String formid = (String) session.get("formid");  
  55.         if (null != formid && this.formid.equals(formid)) {  
  56.             resultJson="请勿重复提交";  
  57.             return "failed";  
  58.         }  
  59.         if(!session.get("code").toString().equals(this.code)){  
  60.             resultJson = "验证码错误";  
  61.             return "failed";  
  62.         }  
  63.         paramMap.put("action", "login");  
  64.         paramMap.put("userName", userName);  
  65.         paramMap.put("password", password);  
  66.         List<Users> user = userService.selectUsers(paramMap);  
  67.         if (user != null && user.size()>0) {  
  68.             String sessionid = Util.getToken();  
  69.             resultJson = "登陆成功";  
  70.             HttpSession cession = request.getSession(true);  
  71.             cession.setAttribute("user", user.get(0));  
  72.             cession.setAttribute("sessionId",sessionid);  
  73.             return "success";  
  74.         } else {  
  75.             resultJson = "用户名或密码错误";  
  76.             return "failed";  
  77.         }  
  78.     }  
  79.     @Action(value = "alluser", results = {   
  80.             @Result(name = "success",type="json",params={"root","resultJson"})  
  81.     })   
  82.     public String allUsers() throws IOException {  
  83.         Map<String, String> paramMap = new HashMap<String, String>();  
  84.         List<Users> userList = userService.selectUsers(paramMap);  
  85.         // 将要被返回到客户端的对象  
  86.         // 如果是List类型则使用JsonArray,如果是其他对象类型则使用jsonObject  
  87.         JSONArray array = new JSONArray();  
  88.         array.addAll(userList);  
  89.         this.resultJson = array.toString();  
  90.         return "success";  
  91.     }  
  92.     @Action(value = "logout", results = { @Result(name = "success", location = "/index.jsp") })   
  93.     public String logout(){  
  94.         Map<String, ?> session = (Map<String, ?>) ActionContext.getContext()  
  95.                 .getSession();  
  96.         session.clear();  
  97.         return "success";  
  98.     }  
  99.     @Action(value = "validateCode", results = {   
  100.             @Result(name = "success",type="stream",params={"contentType","image/jpeg","inputName","imageStream"})  
  101.     })   
  102.     public String validateCode() {  
  103.         RandomPic pic = new RandomPic();  
  104.         BufferedImage image = pic.validatePic();  
  105.         String code = pic.getCode();  
  106.         System.out.println(code);  
  107.         ActionContext.getContext().getSession().put("code", code);  
  108.         imageStream = convertImageToStream(image);  
  109.         return "success";  
  110.     }  
  111.   
  112.     /** 
  113.      * 将BufferedImage转换成ByteArrayInputStream 
  114.      * @param image 图片 
  115.      * @return ByteArrayInputStream 流 
  116.      */  
  117.     private static ByteArrayInputStream convertImageToStream(BufferedImage image) {  
  118.   
  119.         ByteArrayInputStream inputStream = null;  
  120.         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  121.         JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(bos);  
  122.         try {  
  123.             jpeg.encode(image);  
  124.             byte[] bts = bos.toByteArray();  
  125.             inputStream = new ByteArrayInputStream(bts);  
  126.         } catch (ImageFormatException e) {  
  127.             e.printStackTrace();  
  128.         } catch (IOException e) {  
  129.             e.printStackTrace();  
  130.         }  
  131.         return inputStream;  
  132.     }  
  133.     @Action(value = "formid", results = {   
  134.             @Result(name = "success",type="json",params={"root","resultJson"})  
  135.     })   
  136.     public String formid() {  
  137.         resultJson = Util.getToken();  
  138.         return "success";  
  139.     }  
  140.   
  141.     public void setService(UserService service) {  
  142.         this.userService = service;  
  143.     }  
  144.   
  145.   
  146.     public void setResponse(HttpServletResponse response) {  
  147.         this.response = response;  
  148.     }  
  149.   
  150.     public void setUserName(String userName) {  
  151.         this.userName = userName;  
  152.     }  
  153.   
  154.     public void setPassword(String password) {  
  155.         this.password = password;  
  156.     }  
  157.   
  158.     public void setFormid(String formid) {  
  159.         this.formid = formid;  
  160.     }  
  161.   
  162.     public String getResultJson() {  
  163.         return resultJson;  
  164.     }  
  165.   
  166.     public ByteArrayInputStream getImageStream() {  
  167.         return imageStream;  
  168.     }  
  169.   
  170.     public void setCode(String code) {  
  171.         this.code = code;  
  172.     }  
  173.   
  174. }  

首先要说的是,因为要返回Json,所以我使用了JsonObject。要使用这个家伙除了代表他自己的json-lib外,还有6个包是必须的,列表如下:


JsonObject可以很方便的将Java对象转换为Json字符串。使用过程中有一点需要注意,那就是如果这个java对象是个集合,那么就要使用JsonArray类,简单的使用方法在allusers这个方法里已经有写。如果是java非集合对象的话,那么就使用JsonOject类。

另外,不要因为使用注解配置Action就以为那些属性可以使用通过@Autoware或者@Resource注解自动注入。经过我亲测这种方法是不行的。我想因为前台页面无法沟通到Spring的原因吧。所以这些属性必须要手动写setter和getter。

关于配置Action,因为使用到注解配置,所以一会儿说到注解的时候一起记录。


工具类

Util

 

[java] view plain copy
 
  1. package com.qlzx.utils;  
  2.   
  3. import java.security.MessageDigest;  
  4. import java.util.Random;  
  5.   
  6. import sun.misc.BASE64Encoder;  
  7.   
  8. public class Util {  
  9.     public static String getToken(){  
  10.         String token = System.currentTimeMillis()+new Random().nextInt()+"";  
  11.         try {  
  12.             MessageDigest md = MessageDigest.getInstance("MD5");  
  13.             byte[] md5 = md.digest(token.getBytes());  
  14.             BASE64Encoder encoder = new BASE64Encoder();  
  15.             return encoder.encode(md5);  
  16.         } catch (Exception e) {  
  17.             throw new RuntimeException(e);  
  18.         }  
  19.     }  
  20.       
  21. }  

这个类只有一个方法,就是生成一个唯一的Token,这个Token可以用在表单号、sessionid等地方、甚至改写一下可以为密码加密。

 

RandomPic

[java] view plain copy
 
  1. package com.qlzx.utils;  
  2.   
  3. import java.awt.Color;  
  4. import java.awt.Font;  
  5. import java.awt.Graphics;  
  6. import java.awt.Graphics2D;  
  7. import java.awt.image.BufferedImage;  
  8. import java.util.Random;  
  9. /** 
  10.  * 产生随机图片 
  11.  * @author Administrator 
  12.  * 
  13.  */  
  14. public class RandomPic{  
  15.     private static final long serialVersionUID = 1L;  
  16.     public static final  int WIDTH = 120;   //图片的宽  
  17.     public static final  int HEIGHT = 45;       //图片高  
  18.     private String code = "";  
  19.     public BufferedImage validatePic() {  
  20.         //创建一个图像  
  21.         BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);  
  22.         //获取图像  
  23.         Graphics g = image.getGraphics();  
  24.         //1.设置背景色  
  25.         setBackground(g);  
  26.         //2.设置边框  
  27.         setBorder(g);  
  28.         //3.画干扰线  
  29.         drawRandomLine(g);  
  30.         //4、生成并画随机验证码  
  31.         drawRandomNum((Graphics2D)g);  
  32.         return image;  
  33.     }  
  34.     private void drawRandomLine(Graphics g) {  
  35.         g.setColor(Color.GREEN);  
  36.         //画至少6条干扰线  
  37.         int k = 0;  
  38.         while (k < 1){  
  39.             k = new Random().nextInt(6);  
  40.         }  
  41.         for (int i = 0; i < k; i++) {  
  42.             //生成干扰线随机起始坐标  
  43.             int x1 = new Random().nextInt(WIDTH);  
  44.             int y1 = new Random().nextInt(HEIGHT);  
  45.             //生成干扰线随机结束坐标  
  46.             int x2 = new Random().nextInt(WIDTH);  
  47.             int y2 = new Random().nextInt(HEIGHT);  
  48.             //画干扰线  
  49.             g.drawLine(x1, y1, x2, y2);  
  50.               
  51.               
  52.         }  
  53.           
  54.     }  
  55.     /** 
  56.      * 写随机汉字。因为 <code> Graphics</code> 没有旋转的方法。但默认生成的 <code>Graphics2D</code> 中有旋转的方法 
  57.      * 所以在传参时将参数类型强转成 <code>Graphics2D</code>  
  58.      * (<code>BufferedImage.getGraphics()</code>方法返回的其实就是<code>Graphics2DGraphics2D</code>)。 
  59.      * @param g 
  60.      */  
  61.     private void drawRandomNum(Graphics2D g) {  
  62.         code = "";  
  63.         g.setColor(Color.RED);  
  64.         g.setFont(new Font("微软雅黑",Font.BOLD,20));  
  65.         //常用汉字  
  66.         String base = "u96d5u864eu7684u4e00u4e86u662fu6211u4e0du5728u4ebau4eecu6709u6765u4ed6u8fd9u4e0au7740u4e2au5730u5230u5927u91ccu8bf4u5c31u53bbu5b50u5f97u4e5fu548cu90a3u8981u4e0bu770bu5929u65f6u8fc7u51fau5c0fu4e48u8d77u4f60u90fdu628au597du8fd8u591au6ca1u4e3au53c8u53efu5bb6u5b66u53eau4ee5u4e3bu4f1au6837u5e74u60f3u751fu540cu8001u4e2du5341u4eceu81eau9762u524du5934u9053u5b83u540eu7136u8d70u5f88u50cfu89c1u4e24u7528u5979u56fdu52a8u8fdbu6210u56deu4ec0u8fb9u4f5cu5bf9u5f00u800cu5df1u4e9bu73b0u5c71u6c11u5019u7ecfu53d1u5de5u5411u4e8bu547du7ed9u957fu6c34u51e0u4e49u4e09u58f0u4e8eu9ad8u624bu77e5u7406u773cu5fd7u70b9u5fc3u6218u4e8cu95eeu4f46u8eabu65b9u5b9eu5403u505au53ebu5f53u4f4fu542cu9769u6253u5462u771fu5168u624du56dbu5df2u6240u654cu4e4bu6700u5149u4ea7u60c5u8defu5206u603bu6761u767du8bddu4e1cu5e2du6b21u4eb2u5982u88abu82b1u53e3u653eu513fu5e38u6c14u9ec4u4e94u7b2cu4f7fu5199u519bu6728u73cdu5427u6587u8fd0u518du679cu600eu5b9au8bb8u5febu660eu884cu56e0u522bu98deu5916u6811u7269u6d3bu90e8u95e8u65e0u5f80u8239u671bu65b0u5e26u961fu5148u529bu5b8cu5374u7ad9u4ee3u5458u673au66f4u4e5du60a8u6bcfu98ceu7ea7u8ddfu7b11u554au5b69u4e07u5c11u76f4u610fu591cu6bd4u9636u8fdeu8f66u91cdu4fbfu6597u9a6cu54eau5316u592au6307u53d8u793eu4f3cu58ebu8005u5e72u77f3u6ee1u6885u65e5u51b3u767eu539fu62ffu7fa4u7a76u5404u516du672cu601du89e3u7acbu6cb3u6751u516bu96beu65e9u8bbau5417u6839u5171u8ba9u76f8u7814u4ecau5176u4e66u5750u63a5u5e94u5173u4fe1u89c9u6b65u53cdu5904u8bb0u5c06u5343u627eu4e89u9886u6216u5e08u7ed3u5757u8dd1u8c01u8349u8d8au5b57u52a0u811au7d27u7231u7b49u4e60u9635u6015u6708u9752u534au706bu6cd5u9898u5efau8d76u4f4du5531u6d77u4e03u5973u4efbu4ef6u611fu51c6u5f20u56e2u5c4bu79bbu8272u8138u7247u79d1u5012u775bu5229u4e16u521au4e14u7531u9001u5207u661fu5bfcu665au8868u591fu6574u8ba4u54cdu96eau6d41u672au573au8be5u5e76u5e95u6df1u523bu5e73u4f1fu5fd9u63d0u786eu8fd1u4eaeu8f7bu8bb2u519cu53e4u9ed1u544au754cu62c9u540du5440u571fu6e05u9633u7167u529eu53f2u6539u5386u8f6cu753bu9020u5634u6b64u6cbbu5317u5fc5u670du96e8u7a7fu5185u8bc6u9a8cu4f20u4e1au83dcu722cu7761u5174u5f62u91cfu54b1u89c2u82e6u4f53u4f17u901au51b2u5408u7834u53cbu5ea6u672fu996du516cu65c1u623fu6781u5357u67aau8bfbu6c99u5c81u7ebfu91ceu575au7a7au6536u7b97u81f3u653fu57ceu52b3u843du94b1u7279u56f4u5f1fu80dcu6559u70edu5c55u5305u6b4cu7c7bu6e10u5f3au6570u4e61u547cu97f3u7b54u54e5u9645u65e7u795eu5ea7u7ae0u5e2eu5566u53d7u7cfbu4ee4u8df3u975eu4f55u725bu53d6u5165u5cb8u6562u6389u5ffdu79cdu88c5u9876u6025u6234u6797u505cu606fu53e5u533au8863u822cu62a5u53f6u538bu6162u53d4u80ccu7ec6u8273u4f50";  
  67.         //写四个汉字  
  68.         for (int i = 0; i < 4; i++) {  
  69.             //在字符串范围内取一个汉字  
  70.             String ch = base.charAt(new Random().nextInt(base.length()))+"";  
  71.             //将生成的汉字添加到变量中  
  72.             code = code+ch;  
  73.             //写字的X坐标  
  74.             int x = i*30+3;  
  75.             //旋转30度以内  
  76.             //因为也要向左旋转,所以先生成一个随机数后再模30即可  
  77.             int degree = new Random().nextInt() % 30;  
  78.             //旋转的弧度  
  79.             double theta = degree*Math.PI/180;  
  80.             //旋转  
  81.             g.rotate(theta, x, 30);  
  82.             //写字  
  83.             g.drawString(ch, x, 30);  
  84.             //将弧度转回去  
  85.             g.rotate(-theta, x, 30);  
  86.         }  
  87.           
  88.     }  
  89.     private void setBorder(Graphics g) {  
  90.         g.setColor(Color.BLUE);  
  91.         g.drawRect(0, 0, WIDTH - 2, HEIGHT - 2);  
  92.           
  93.     }  
  94.     private void setBackground(Graphics g) {  
  95.         g.setColor(Color.WHITE);  
  96.         g.fillRect(0, 0, WIDTH, HEIGHT);  
  97.     }  
  98.     public String getCode() {  
  99.         return code;  
  100.     }  
  101. }  

这个类用于生成一个汉字验证码。代码很简单,一看就懂,要说明的是,因为每次生成的验证码不一样,所以没有将此类中的变量写成static,因此对应的方法也就不是static的。使用此类生成验证码的时候需要先创建对象。另外,汉字列表可以写在properties文件中,使用静态代码块加载后使用。


注解。

首先,要使用注解,必须在spring的配置文件中写上这两句:
[html] view plain copy
 
  1. <context:annotation-config/>  
  2. <context:component-scan base-package="com.qlzx"></context:component-scan>  

这两句第一句的意思是使用注解配置。有了这句Spring注解才有用。第二句的意思是自动扫描,扫描的内容自然是注解了。里面有一个属性:base-package,这个属性用来告诉Spring扫描哪个包下的类。比如我的代码就是扫描com.qlzx包下的所有类,包括其中的子包。

然后就是Struts对注解的支持了,Struts2要实现对注解的支持,那就必须要使用到struts2-convention-plugin-2.x.x.jar。有了这个包,才能使Struts2支持注解。

 

对于注解,MVC三层有四种注解,分别是:@Component/@Repository/@Service/@Controller。

如果某个类的头上带有以上注解,就会将这个对象作为Bean注册进Spring容器。以上的4个注解,用法完全一摸一样,只有语义上的区别。

其中后三个注解是第一个注解@Component的细化。@Component在三层中都可以使用,而细化后,Dao层使用@Repository,Service层使用@Service,而Action使用@Controller。

按照网上的资料,说其中的@Component不推荐使用,至于为什么,还没想出来,大概是因为@Component范围太广容易出问题吧。而这几个注解都可以带参数,如:@Service("exampleService")或者@Service(value="exampleService")。使用注解后相当于在spring配置文件中添加了bean节点,而像上面这样带参数写的话相当于给bean添加了name属性。在我的代码中因为只有一个Action类、Service类、Dao类都各只有一个,所以没有写value。如果是有多个的话,必须在注解中写上value以示区分。

 

在spring中生成bean之后,就要定义那些属性需要自动注入了。使用自动注入有两个注解:@Resource和@Autowired。这两个注解作用一样,只不过 @Autowired 按 byType 自动注入,面@Resource 默认按 byName 自动注入罢了。@Autowired是自动寻找匹配类型,然后注入。@Resource 有两个属性是比较重要的,分别是 name 和 type,Spring 将@Resource注释的 name 属性解析为 Bean 的名字,而 type 属性则解析为 Bean 的类型。所以如果使用 name 属性,则使用 byName 的自动注入策略,而使用 type 属性时则使用 byType 自动注入策略。如果既不指定 name 也不指定 type 属性,这时将通过反射机制使用 byName 自动注入策略。这里的name就是上一段说的@Service(value="exampleService")中的exampleService部分。

 

如果在使用@Autowired注解注入的时候,需要特定的名称,那么可以使用@Qualifier注释指定需要注入那个bean。如:
[java] view plain copy
 
  1. @Autowired  
  2. @Qualifier("userServiceImpl")  
  3. UserService userService;  

这样在使用的时候Spring就会自动寻找所有标记注解的类中的UserServiceImpl这个类去注入。

注意:因为@AutoWired是按类型注入,所以参数只能是类型名。而因为bean中的name默认类型名首字母小写,所以这里也是首字母小写。

 

那么如果这样写行不行呢?

[java] view plain copy
 
  1. @Resource  
  2. @Qualifier("userServiceImpl")  
  3. UserService userService;  

行不行,我也不知道,我猜想应该是可以的,本人没有亲测。为什么?因为Eclipse没有报错 : P (开玩笑的)。

这里要提一下,@Resource注解需要使用到Spring中的common-annotations.jar,所以这个包记得引入。

 

需要了解以上几个注解的更多知识,参看网址:

http://blog.csdn.net/xyh820/article/details/7303330

(感谢xyh820和原作者)

 

三层的类都注解好了,接下来就是使用注解配置Action了。

 

要使用注解配置Struts2的Action,那么就必须引入一个包:struts2-convention-plugin.jar。我在这个项目中使用的是struts2-convention-plugin-2.2.3.1.jar

 

使用注解配置Action的时候,需要用到的最主要的注解为@Action。这个注解为配置Action时候必须用到的注解。
[java] view plain copy
 
  1. @Action(value = "login", results = {   
  2.             @Result(name = "success", location = "/message.jsp") ,  
  3.             @Result(name = "failed",type="json",params={"root","resultJson"})  
  4.     })  
  5. public String login() {}  

以上这段代码是将login方法通过注解配置成一个名字叫login的action。如果这个方法返回的是success字符串,那么则跳转到message.jsp,如果返回的事failed字符串,则返回一个json。@Action是配置Action相关的信息。而@Result这个注解是配置这个Action返回的信息,其中的信息的含义对照一下下面的xml代码就能看出来。特别要说明的是params这个属性,他接受的是一个String类型的数组,写的形式是key、value、key、value这样的,例如下面:

[java] view plain copy
 
  1. @Action(value = "validateCode", results = {   
  2.             @Result(name = "success",type="stream",params={"contentType","image/jpeg","inputName","imageStream"})  
  3.     })   

这个是返回一个流,它相当于在struts2的配置文件中加入下面这段代码:

[html] view plain copy
 
  1. <action name="validateCode" class="com.qlzx.action.PublicController" method="validateCode">  
  2.             <result name="success" type="stream">  
  3.                 <param name="contentType">image/jpeg</param>  
  4.                 <param name="inputName">imageStream</param>  
  5.             </result>  
  6. </action>  

当然,因为返回了Json,所以只有上面那个注解是不行的,还需要在这个方法的类中加一个注解:

[java] view plain copy
 
  1. @ParentPackage(value="json-default")  
  2. public class PublicController extends BaseAction {}  

上面配置login的注解相当于在Struts中的配置文件写入了如下的代码:

[html] view plain copy
 
  1. <package name="User" namespace="/" extends="struts-default,json-default">  
  2.         <action name="login" class="com.qlzx.action.PublicController"  
  3.             method="login">  
  4.             <result name="success" type="redirect">/message.jsp</result>  
  5.             <result name="failed" type="json">  
  6.                 <param name="root">resultJson</param>  
  7.             </result>  
  8.         </action>  
  9. </package>  

其中@ParentPackage相当于配置中的extends这个属性。不过经过测试这个注解的value不能是多个值。

常用的注解配置如下:

1) @ParentPackage 指定父包,(不写默认 “struts-default”)

2) @Namespace 指定命名空间(不写默认为 “/”)

3) @Results 一组结果的数组(在只有多个处理结果的时候使用)

4)@Result(name="success",location="/msg.jsp") 一个结果的映射

5)@Action(value="login") 指定某个请求处理方法的请求URL。注意,它不能添加在Action类上,要添加到方法上。

6) @ExceptionMappings一级声明异常的数组

7) @ExceptionMapping映射一个声明异常

特别要说明的是:如果使用Struts的标注配置了Action后,那么视图层类上的@Controller这个标注可以不需要。

最后就是JSP页面了,代码这里省略。附上效果图。

index.jsp

执行的sql:


message.jsp


写在最后的话:

因为本人也是在学习过程当中,所以文章中难免出现什么错误之处。如果对这个文章有什么疑问或者某些地方有更好的方案或者错误的指正,欢迎留言一起讨论。

本文为原创,如果转载请注明出处:

http://blog.csdn.net/levelmini
原文地址:https://www.cnblogs.com/cxxjohnson/p/7476327.html