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

 分类:

Web(2) 

版权声明:本文为博主原创文章,未经博主允许不得转载。

最近在做一个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. # the mysql open source driver
  4. #realdriver=com.mysql.jdbc.Driver
  5. realdriver= com.mysql.jdbc.Driver
  6. #the DriverManager class sequentially tries every driver that is
  7. #registered to find the right driver.  In some instances, it‘s possible to
  8. #load up the realdriver before the p6spy driver, in which case your connections
  9. #will not get wrapped as the realdriver will "steal" the connection before
  10. #p6spy sees it.  Set the following property to "true" to cause p6spy to
  11. #explicitily deregister the realdrivers
  12. deregisterdrivers=true
  13. # outagedetection=true|false
  14. # outagedetectioninterval=integer time (seconds)
  15. #
  16. outagedetection=false
  17. # filter what is logged
  18. filter=false
  19. # turn on tracing
  20. autoflush   = true
  21. # sets the date format using Java‘s SimpleDateFormat routine
  22. dateformat=yyyy-MM-dd HH:mm:ss:SS
  23. #list of categories to explicitly include
  24. includecategories=error,statement
  25. #list of categories to exclude: error, info, batch, debug, statement,
  26. #commit, rollback and result are valid values
  27. excludecategories=info,debug,result,batch,resultset,commit
  28. # prints a stack trace for every statement logged
  29. stacktrace=false
  30. # if stacktrace=true, specifies the stack trace to print
  31. stacktraceclass=
  32. # determines if property file should be reloaded
  33. reloadproperties=false
  34. # determines how often should be reloaded in seconds
  35. reloadpropertiesinterval=60
  36. #if=true then url must be prefixed with p6spy:
  37. useprefix=false
  38. #specifies the appender to use for logging
  39. appender=com.p6spy.engine.logging.appender.StdoutLogger
  40. append=true
  41. #The following are for log4j logging only
  42. log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
  43. log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
  44. log4j.appender.STDOUT.layout.ConversionPattern=p6spy - %m%n
  45. 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. <error-page>
  46. <error-code>500</error-code>
  47. <location>/commons/error.jsp</location>
  48. </error-page>
  49. <error-page>
  50. <error-code>404</error-code>
  51. <location>/commons/404.jsp</location>
  52. </error-page>
  53. <error-page>
  54. <error-code>403</error-code>
  55. <location>/commons/403.jsp</location>
  56. </error-page>
  57. </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. <import resource="datasource.xml" />
  9. <context:annotation-config/>
  10. <context:component-scan base-package="com.qlzx"></context:component-scan>
  11. <!-- 配置mybatis的sqlsessionFactory -->
  12. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  13. <property name="dataSource" ref="dataSource" />
  14. <property name="configLocation" value="classpath:conf/MapperConfig.xml" />
  15. </bean>
  16. <!--配置 mybatis的映射器 方式一 -->
  17. <!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
  18. <property name="sqlSessionFactory" ref="sqlSessionFactory"/> <property name="mapperInterface"
  19. value="org.ko.webservice.dao.UserMapper"/> </bean> -->
  20. <!-- 配置 mybatis的映射器 方式二:也可不指定特定mapper,而使用自动扫描包的方式来注册各种Mapper ,配置如下: -->
  21. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  22. <property name="basePackage" value="com.qlzx" />
  23. <property name="sqlSessionFactory" ref="sqlSessionFactory" />
  24. <property name="annotationClass" value="org.springframework.stereotype.Component" />
  25. </bean>
  26. <!-- bean class="org.mybatis.spring.annotation.MapperScannerPostProcessor">
  27. <property name="basePackage" value="org.ko.webservice.dao" /> </bean -->
  28. <!-- 配置事务管理 -->
  29. <bean id="transactionManager"
  30. class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  31. <property name="dataSource">
  32. <ref bean="dataSource" />
  33. </property>
  34. </bean>
  35. <!-- tx:annotation-driven transaction-manager="transactionManager" / -->
  36. <!-- 配置事务代理拦截器 -->
  37. <bean id="transactionInterceptor"
  38. class="org.springframework.transaction.interceptor.TransactionInterceptor">
  39. <property name="transactionManager" ref="transactionManager" />
  40. <property name="transactionAttributes">
  41. <props>
  42. <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
  43. <prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>
  44. <prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>
  45. <prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>
  46. <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
  47. <prop key="del*">PROPAGATION_REQUIRED,-Exception</prop>
  48. <prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
  49. <prop key="remove*">PROPAGATION_REQUIRED,-Exception</prop>
  50. <prop key="query*">PROPAGATION_REQUIRED, readOnly,-Exception</prop>
  51. <prop key="search*">PROPAGATION_REQUIRED, readOnly,-Exception</prop>
  52. <prop key="select*">PROPAGATION_REQUIRED, readOnly,-Exception</prop>
  53. <prop key="get*">PROPAGATION_REQUIRED, readOnly,-Exception</prop>
  54. <prop key="load*">PROPAGATION_REQUIRED, -Exception</prop>
  55. <prop key="*">readOnly</prop>
  56. </props>
  57. </property>
  58. </bean>
  59. <!-- 配置要拦截哪些方法 -->
  60. <bean id="trasactionMethodPointcutAdvisor"
  61. class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
  62. <property name="mappedNames">
  63. <list>
  64. <value>*</value> <!-- 所有方法 -->
  65. </list>
  66. </property>
  67. <property name="advice">
  68. <ref local="transactionInterceptor" />
  69. </property>
  70. </bean>
  71. <!-- 配置要拦截哪些类,并使用那些拦截器 -->
  72. <bean id="ServiceAutoProxyCreator"
  73. class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
  74. <property name="proxyTargetClass" value="true"></property>
  75. <property name="beanNames">
  76. <list>
  77. <value>*Service*</value>
  78. </list>
  79. </property>
  80. <property name="interceptorNames">
  81. <list>
  82. <value>trasactionMethodPointcutAdvisor</value>
  83. </list>
  84. </property>
  85. </bean>
  86. </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. <bean id="configurer"
  7. class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  8. <property name="location">
  9. <value>classpath:conf/db.properties</value>
  10. </property>
  11. </bean>
  12. <!-- 配置数据源 -->
  13. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
  14. destroy-method="close">
  15. <property name="driverClass">
  16. <value>com.p6spy.engine.spy.P6SpyDriver</value>
  17. </property>
  18. <property name="jdbcUrl">
  19. <value>${jdbc.url}</value>
  20. </property>
  21. <property name="user">
  22. <value>${jdbc.username}</value>
  23. </property>
  24. <property name="password">
  25. <value>${jdbc.password}</value>
  26. </property>
  27. <!--连接池中保留的最小连接数。 -->
  28. <property name="minPoolSize">
  29. <value>2</value>
  30. </property>
  31. <!--连接池中保留的最大连接数。Default: 15 -->
  32. <property name="maxPoolSize">
  33. <value>15</value>
  34. </property>
  35. <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
  36. <property name="initialPoolSize">
  37. <value>2</value>
  38. </property>
  39. <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
  40. <property name="maxIdleTime">
  41. <value>1800</value>
  42. </property>
  43. <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
  44. <property name="acquireIncrement">
  45. <value>2</value>
  46. </property>
  47. <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
  48. 如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->
  49. <property name="maxStatements">
  50. <value>0</value>
  51. </property>
  52. <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
  53. <property name="idleConnectionTestPeriod">
  54. <value>0</value>
  55. </property>
  56. <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
  57. <property name="acquireRetryAttempts">
  58. <value>30</value>
  59. </property>
  60. <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试
  61. 获取连接失败后该数据源将申明已断开并永久关闭。Default: false -->
  62. <property name="breakAfterAcquireFailure">
  63. <value>false</value>
  64. </property>
  65. <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable
  66. 等方法来提升连接测试的性能。Default: false -->
  67. <property name="testConnectionOnCheckout">
  68. <value>false</value>
  69. </property>
  70. <property name="debugUnreturnedConnectionStackTraces">
  71. <value>false</value>
  72. </property>
  73. <property name="acquireRetryDelay">
  74. <value>100</value>
  75. </property>
  76. </bean>
  77. </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. <constant name="struts.i18n.encoding" value="UTF-8" />
  6. <!-- 指定被struts2处理的请求后缀类型。多个用逗号隔开 -->
  7. <constant name="struts.action.extension" value="action,do,htm" />
  8. <!-- 当struts.xml改动后,是否重新加载。默认值为false(生产环境下使用),开发阶段最好打开 -->
  9. <constant name="struts.configuration.xml.reload" value="true" />
  10. <!-- 是否使用struts的开发模式。开发模式会有更多的调试信息。默认值为false(生产环境下使用),开发阶段最好打开 -->
  11. <constant name="struts.devMode" value="true" />
  12. <!-- 设置浏览器是否缓存静态内容。默认值为true(生产环境下使用),开发阶段最好关闭 -->
  13. <constant name="struts.serve.static.browserCache" value="false" />
  14. <!-- 指定由spring负责action对象的创建 -->
  15. <constant name="struts.objectFactory" value="spring" />
  16. <!-- 是否开启动态方法调用 -->
  17. <constant name="struts.enable.DynamicMethodInvocation" value="false" />
  18. </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. <select id="selectUsers" parameterType="java.util.Map"
  11. resultMap="userlist">
  12. select ID,USERNAME,USERPWD from USERINFO where 1=1
  13. <if test="action == ‘login‘">
  14. <if test="userName != null and userPwd != ‘‘">
  15. and USERNAME = #{userName}
  16. and USERPWD = #{password}
  17. </if>
  18. </if>
  19. </select>
  20. <!-- 公共 查询 记录集合 -->
  21. <select id="selectByMap" resultType="java.util.HashMap"
  22. parameterType="java.util.Map">
  23. </select>
  24. </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. import org.apache.ibatis.annotations.Param;
  5. public abstract interface BaseDao<T, E, PK extends Serializable>
  6. {
  7. public abstract int countByExample(E paramE);
  8. public abstract List<T> query();
  9. public abstract int deleteByExample(E paramE);
  10. public abstract int deleteByPrimaryKey(PK paramPK);
  11. public abstract int insert(T paramT);
  12. public abstract int insertSelective(T paramT);
  13. public abstract List<T> selectByExample(E paramE);
  14. public abstract T selectByPrimaryKey(PK paramPK);
  15. public abstract int updateByExampleSelective(@Param("record") T paramT, @Param("example") E paramE);
  16. public abstract int updateByExample(@Param("record") T paramT, @Param("example") E paramE);
  17. public abstract int updateByPrimaryKeySelective(T paramT);
  18. public abstract int updateByPrimaryKey(T paramT);
  19. public abstract List<T> selectByExampleWithBLOBs(E paramE);
  20. public abstract int updateByPrimaryKeyWithBLOBs(T paramT);
  21. }

UserDao

[java] view plain copy

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

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

Service:

UserService

[java] view plain copy

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

Service接口,不需要多讲。

UserServiceImpl:

[java] view plain copy

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

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

BaseAction

[java] view plain copy

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

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

首先要说的是,因为要返回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. import java.security.MessageDigest;
  3. import java.util.Random;
  4. import sun.misc.BASE64Encoder;
  5. public class Util {
  6. public static String getToken(){
  7. String token = System.currentTimeMillis()+new Random().nextInt()+"";
  8. try {
  9. MessageDigest md = MessageDigest.getInstance("MD5");
  10. byte[] md5 = md.digest(token.getBytes());
  11. BASE64Encoder encoder = new BASE64Encoder();
  12. return encoder.encode(md5);
  13. } catch (Exception e) {
  14. throw new RuntimeException(e);
  15. }
  16. }
  17. }

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

RandomPic

[java] view plain copy

  1. package com.qlzx.utils;
  2. import java.awt.Color;
  3. import java.awt.Font;
  4. import java.awt.Graphics;
  5. import java.awt.Graphics2D;
  6. import java.awt.image.BufferedImage;
  7. import java.util.Random;
  8. /**
  9. * 产生随机图片
  10. * @author Administrator
  11. *
  12. */
  13. public class RandomPic{
  14. private static final long serialVersionUID = 1L;
  15. public static final  int WIDTH = 120;   //图片的宽
  16. public static final  int HEIGHT = 45;       //图片高
  17. private String code = "";
  18. public BufferedImage validatePic() {
  19. //创建一个图像
  20. BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
  21. //获取图像
  22. Graphics g = image.getGraphics();
  23. //1.设置背景色
  24. setBackground(g);
  25. //2.设置边框
  26. setBorder(g);
  27. //3.画干扰线
  28. drawRandomLine(g);
  29. //4、生成并画随机验证码
  30. drawRandomNum((Graphics2D)g);
  31. return image;
  32. }
  33. private void drawRandomLine(Graphics g) {
  34. g.setColor(Color.GREEN);
  35. //画至少6条干扰线
  36. int k = 0;
  37. while (k < 1){
  38. k = new Random().nextInt(6);
  39. }
  40. for (int i = 0; i < k; i++) {
  41. //生成干扰线随机起始坐标
  42. int x1 = new Random().nextInt(WIDTH);
  43. int y1 = new Random().nextInt(HEIGHT);
  44. //生成干扰线随机结束坐标
  45. int x2 = new Random().nextInt(WIDTH);
  46. int y2 = new Random().nextInt(HEIGHT);
  47. //画干扰线
  48. g.drawLine(x1, y1, x2, y2);
  49. }
  50. }
  51. /**
  52. * 写随机汉字。因为 <code> Graphics</code> 没有旋转的方法。但默认生成的 <code>Graphics2D</code> 中有旋转的方法
  53. * 所以在传参时将参数类型强转成 <code>Graphics2D</code>
  54. * (<code>BufferedImage.getGraphics()</code>方法返回的其实就是<code>Graphics2DGraphics2D</code>)。
  55. * @param g
  56. */
  57. private void drawRandomNum(Graphics2D g) {
  58. code = "";
  59. g.setColor(Color.RED);
  60. g.setFont(new Font("微软雅黑",Font.BOLD,20));
  61. //常用汉字
  62. String base = "\u96d5\u864e\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1\u4e9b\u73b0\u5c71\u6c11\u5019\u7ecf\u53d1\u5de5\u5411\u4e8b\u547d\u7ed9\u957f\u6c34\u51e0\u4e49\u4e09\u58f0\u4e8e\u9ad8\u624b\u77e5\u7406\u773c\u5fd7\u70b9\u5fc3\u6218\u4e8c\u95ee\u4f46\u8eab\u65b9\u5b9e\u5403\u505a\u53eb\u5f53\u4f4f\u542c\u9769\u6253\u5462\u771f\u5168\u624d\u56db\u5df2\u6240\u654c\u4e4b\u6700\u5149\u4ea7\u60c5\u8def\u5206\u603b\u6761\u767d\u8bdd\u4e1c\u5e2d\u6b21\u4eb2\u5982\u88ab\u82b1\u53e3\u653e\u513f\u5e38\u6c14\u9ec4\u4e94\u7b2c\u4f7f\u5199\u519b\u6728\u73cd\u5427\u6587\u8fd0\u518d\u679c\u600e\u5b9a\u8bb8\u5feb\u660e\u884c\u56e0\u522b\u98de\u5916\u6811\u7269\u6d3b\u90e8\u95e8\u65e0\u5f80\u8239\u671b\u65b0\u5e26\u961f\u5148\u529b\u5b8c\u5374\u7ad9\u4ee3\u5458\u673a\u66f4\u4e5d\u60a8\u6bcf\u98ce\u7ea7\u8ddf\u7b11\u554a\u5b69\u4e07\u5c11\u76f4\u610f\u591c\u6bd4\u9636\u8fde\u8f66\u91cd\u4fbf\u6597\u9a6c\u54ea\u5316\u592a\u6307\u53d8\u793e\u4f3c\u58eb\u8005\u5e72\u77f3\u6ee1\u6885\u65e5\u51b3\u767e\u539f\u62ff\u7fa4\u7a76\u5404\u516d\u672c\u601d\u89e3\u7acb\u6cb3\u6751\u516b\u96be\u65e9\u8bba\u5417\u6839\u5171\u8ba9\u76f8\u7814\u4eca\u5176\u4e66\u5750\u63a5\u5e94\u5173\u4fe1\u89c9\u6b65\u53cd\u5904\u8bb0\u5c06\u5343\u627e\u4e89\u9886\u6216\u5e08\u7ed3\u5757\u8dd1\u8c01\u8349\u8d8a\u5b57\u52a0\u811a\u7d27\u7231\u7b49\u4e60\u9635\u6015\u6708\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u5f20\u56e2\u5c4b\u79bb\u8272\u8138\u7247\u79d1\u5012\u775b\u5229\u4e16\u521a\u4e14\u7531\u9001\u5207\u661f\u5bfc\u665a\u8868\u591f\u6574\u8ba4\u54cd\u96ea\u6d41\u672a\u573a\u8be5\u5e76\u5e95\u6df1\u523b\u5e73\u4f1f\u5fd9\u63d0\u786e\u8fd1\u4eae\u8f7b\u8bb2\u519c\u53e4\u9ed1\u544a\u754c\u62c9\u540d\u5440\u571f\u6e05\u9633\u7167\u529e\u53f2\u6539\u5386\u8f6c\u753b\u9020\u5634\u6b64\u6cbb\u5317\u5fc5\u670d\u96e8\u7a7f\u5185\u8bc6\u9a8c\u4f20\u4e1a\u83dc\u722c\u7761\u5174\u5f62\u91cf\u54b1\u89c2\u82e6\u4f53\u4f17\u901a\u51b2\u5408\u7834\u53cb\u5ea6\u672f\u996d\u516c\u65c1\u623f\u6781\u5357\u67aa\u8bfb\u6c99\u5c81\u7ebf\u91ce\u575a\u7a7a\u6536\u7b97\u81f3\u653f\u57ce\u52b3\u843d\u94b1\u7279\u56f4\u5f1f\u80dc\u6559\u70ed\u5c55\u5305\u6b4c\u7c7b\u6e10\u5f3a\u6570\u4e61\u547c\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u5e2e\u5566\u53d7\u7cfb\u4ee4\u8df3\u975e\u4f55\u725b\u53d6\u5165\u5cb8\u6562\u6389\u5ffd\u79cd\u88c5\u9876\u6025\u6234\u6797\u505c\u606f\u53e5\u533a\u8863\u822c\u62a5\u53f6\u538b\u6162\u53d4\u80cc\u7ec6\u8273\u4f50";
  63. //写四个汉字
  64. for (int i = 0; i < 4; i++) {
  65. //在字符串范围内取一个汉字
  66. String ch = base.charAt(new Random().nextInt(base.length()))+"";
  67. //将生成的汉字添加到变量中
  68. code = code+ch;
  69. //写字的X坐标
  70. int x = i*30+3;
  71. //旋转30度以内
  72. //因为也要向左旋转,所以先生成一个随机数后再模30即可
  73. int degree = new Random().nextInt() % 30;
  74. //旋转的弧度
  75. double theta = degree*Math.PI/180;
  76. //旋转
  77. g.rotate(theta, x, 30);
  78. //写字
  79. g.drawString(ch, x, 30);
  80. //将弧度转回去
  81. g.rotate(-theta, x, 30);
  82. }
  83. }
  84. private void setBorder(Graphics g) {
  85. g.setColor(Color.BLUE);
  86. g.drawRect(0, 0, WIDTH - 2, HEIGHT - 2);
  87. }
  88. private void setBackground(Graphics g) {
  89. g.setColor(Color.WHITE);
  90. g.fillRect(0, 0, WIDTH, HEIGHT);
  91. }
  92. public String getCode() {
  93. return code;
  94. }
  95. }

这个类用于生成一个汉字验证码。代码很简单,一看就懂,要说明的是,因为每次生成的验证码不一样,所以没有将此类中的变量写成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

时间: 2024-08-27 01:00:32

Struts2+Spring3+MyBatis3整合以及Spring注解开发的相关文章

Struts2+Spring3+Mybatis3开发环境搭建

本文主要介绍Struts2+Spring3+Mybatis3开发环境搭建 Struts和Spring不过多介绍. MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架.MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及结果集的检索.MyBatis 使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plan Old Java Objects,普通的 Java 对象)映射成数据库中的记录. 环境: Struts-2.3.14

Struts2+Spring3+Hibernate——整合byMaven

在平时的JavaEE开发中,为了能够用最快的速度开发项目,一般都会选择使用Struts2,SpringMVC,Spring,Hibernate,MyBatis这些开源框架来开发项目,而这些框架一般不是单独使用的,经常是Struts2+Spring3+Hibernate.SpringMVC+Spring+Hibernate.SpringMVC+Spring+Mybatis这几种组合中的一种,也就是多个框架配合起来使用.今天来总结一下如何使用Maven搭建Struts2+Spring3+Hibern

Struts2,Spring3,Hibernate4整合--SSH框架

Struts2,Spring3,Hibernate4整合--SSH框架(学习中) 一.包的导入 1.Spring包 2.Hibernate 包 3.struts 包 4.数据库方面的包及junt4的包 二.配置文件 1.beans.xml (具体要注意的已经注释到 xml 中了,目前整合了Spring 与 hibernate4 ) <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="h

struts2 + spring3 + mybatis3 环境搭建

struts2 + spring3 + mybatis3 1. 框架下载 struts2: http://struts.apache.org/ 下载 struts-2.3.14-all.zip spring3: http://www.springsource.org/spring-framework 下载 spring-framework-3.2.2-dist.zip mybatis3: http://code.google.com/p/mybatis/ 下载 mybatis-3.2.2.zip

Spring 注解开发和测试

一,Spring注解开发 1.1 Spring原始注解 1.2 Spring新注解 二,Spring整合Junit 2.1 原始Junit测试Spring的问题 2.2 spring整合junit 一,Spring注解开发 1.1 Spring原始注解 Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率.Spring原始注解主要是替代的配置 ,从而尽量解决配置繁重的问题. 有如下原始注解: 注解 说明 @Com

Annotation(三)——Spring注解开发

Spring框架的核心功能IoC(Inversion of Control),也就是通过Spring容器进行对象的管理,以及对象之间组合关系的映射.通常情况下我们会在xml配置文件中进行action,service,dao等层的声明,然后并告知框架我们想要的注入方式,然后在类中声明要组合类的get,set方法.而通过Spring框架中注解的运用也就主要是解决这类问题的.而框架中另一个核心知识AOP,一种面向横切面的方法编程,在程序中一般都是进行一次设置就可以的,所以都还放在配置文件中.例如声明式

spring注解开发中常用注解以及简单配置

一.spring注解开发中常用注解以及简单配置 1.为什么要用注解开发:spring的核心是Ioc容器和Aop,对于传统的Ioc编程来说我们需要在spring的配置文件中邪大量的bean来向spring容器中注入bean对象, 然而,通过注解编程可以缩短我们开发的时间,简化程序员的代码编写. 2.如何开启注解开发:最常用的方法是使用<mvc:annotation-driven/>来开启注解编程(用一个标签配置了spring注解编程的映射器和适配器,同时配置了许多的参数) 3.如何将有注解的be

spring注解开发及AOP

Spring的bean管理(注解) 注解介绍 1 代码里面特殊标记,使用注解可以完成功能 2 注解写法 @注解名称(属性名称=属性值) 3 注解使用在类上面,方法上面 和 属性上面 Spring注解开发准备 1 导入jar包 (1)导入基本的jar包 (2)导入aop的jar包 2 创建类,创建方法 3 创建spring配置文件,引入约束 (1)第一天做ioc基本功能,引入约束beans (2)做spring的ioc注解开发,引入新的约束 <beans xmlns:xsi="http://

Spring注解开发系列 VIII --- SpringMVC

SpringMVC是三层架构中的控制层部分,有过JavaWEB开发经验的同学一定很熟悉它的使用了.这边有我之前整理的SpringMVC相关的链接: 1.SpringMVC入门 2.SpringMVC进阶 3.深入SpringMVC注解 看过之后大致对springmvc有一个了解,但对于真正完全掌握springmvc还差得远,本篇博客主要针对的是springmvc的注解开发,传统的项目使用spingmvc避免不了地需要在web.xml里配置前端控制器等等,想要在项目中优雅地去掉这些配置,还得学习如