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

module.log=com.p6spy.engine.logging.P6LogFactory
#module.outage=com.p6spy.engine.outage.P6OutageFactory

# the mysql open source driver
#realdriver=com.mysql.jdbc.Driver
realdriver= com.mysql.jdbc.Driver

#the DriverManager class sequentially tries every driver that is
#registered to find the right driver.  In some instances, it's possible to
#load up the realdriver before the p6spy driver, in which case your connections
#will not get wrapped as the realdriver will "steal" the connection before
#p6spy sees it.  Set the following property to "true" to cause p6spy to
#explicitily deregister the realdrivers
deregisterdrivers=true

# outagedetection=true|false
# outagedetectioninterval=integer time (seconds)
#
outagedetection=false

# filter what is logged
filter=false

# turn on tracing
autoflush   = true

# sets the date format using Java's SimpleDateFormat routine
dateformat=yyyy-MM-dd HH:mm:ss:SS

#list of categories to explicitly include 
includecategories=error,statement

#list of categories to exclude: error, info, batch, debug, statement,
#commit, rollback and result are valid values
excludecategories=info,debug,result,batch,resultset,commit

# prints a stack trace for every statement logged
stacktrace=false
# if stacktrace=true, specifies the stack trace to print
stacktraceclass=

# determines if property file should be reloaded
reloadproperties=false
# determines how often should be reloaded in seconds
reloadpropertiesinterval=60

#if=true then url must be prefixed with p6spy:
useprefix=false

#specifies the appender to use for logging
appender=com.p6spy.engine.logging.appender.StdoutLogger

append=true

#The following are for log4j logging only
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=p6spy - %m%n

log4j.logger.p6spy=INFO,STDOUT

這裏使用到了一個包,叫p6spy.jar。

P6Spy 是針對數據庫訪問操作的動態監測框架(爲開源項目,項目首頁:www.p6spy.com)它使得數據庫數據可無縫截取和操縱,而不必對現有應用程序的代碼作任何修改。P6Spy 分發包包括P6Log,它是一個可記錄任何 Java 應用程序的所有JDBC事務的應用程序。其配置完成使用時,可以進行數據訪問性能的監測。

我們最需要的功能,查看sql語句,不是預編譯的帶問號的哦,而是真正的數據庫執行的sql,更直觀,更簡單。

這個包主要用於調試sql,很方便。

web.xml:


<?xml version="1.0" encoding="UTF-8"?>
<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">
  <display-name>qlzx</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
	<filter-name>struts2</filter-name>
  	<filter-class>
		org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
	</filter-class>
  	<init-param>
		<param-name>config</param-name>
		<param-value>struts-default.xml,struts-plugin.xml,struts.xml</param-value>
	</init-param>
</filter>
<filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>/*</url-pattern>
</filter-mapping>
 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
 <filter>
      <filter-name>encodingFilter</filter-name>
      <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
      <init-param>
       <param-name>encoding</param-name>
       <param-value>utf-8</param-value>
      </init-param>
   </filter>
   <filter-mapping>
      <filter-name>encodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
<!-- 配置監聽 -->
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>


  <!-- 配置錯誤頁面 -->
  <error-page>
    <error-code>500</error-code>
    <location>/commons/error.jsp</location>
  </error-page>
  <error-page>
    <error-code>404</error-code>
    <location>/commons/404.jsp</location>
  </error-page>
  <error-page>
    <error-code>403</error-code>
    <location>/commons/403.jsp</location>
  </error-page>

</web-app>



applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<import resource="datasource.xml" />

	<context:annotation-config/>
	<context:component-scan base-package="com.qlzx"></context:component-scan>

	<!-- 配置mybatis的sqlsessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:conf/MapperConfig.xml" />
	</bean>

	<!--配置 mybatis的映射器 方式一 -->
	<!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
		<property name="sqlSessionFactory" ref="sqlSessionFactory"/> <property name="mapperInterface" 
		value="org.ko.webservice.dao.UserMapper"/> </bean> -->

	<!-- 配置 mybatis的映射器 方式二:也可不指定特定mapper,而使用自動掃描包的方式來註冊各種Mapper ,配置如下: -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.qlzx" />
		<property name="sqlSessionFactory" ref="sqlSessionFactory" />
		<property name="annotationClass" value="org.springframework.stereotype.Component" />
	</bean>

	<!-- bean class="org.mybatis.spring.annotation.MapperScannerPostProcessor"> 
		<property name="basePackage" value="org.ko.webservice.dao" /> </bean -->


	<!-- 配置事務管理 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
	</bean>
<!-- tx:annotation-driven transaction-manager="transactionManager" / -->

	<!-- 配置事務代理攔截器 -->
	<bean id="transactionInterceptor"
		class="org.springframework.transaction.interceptor.TransactionInterceptor">
		<property name="transactionManager" ref="transactionManager" />
		<property name="transactionAttributes">
			<props>
				<prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="del*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="remove*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="query*">PROPAGATION_REQUIRED, readOnly,-Exception</prop>
				<prop key="search*">PROPAGATION_REQUIRED, readOnly,-Exception</prop>
				<prop key="select*">PROPAGATION_REQUIRED, readOnly,-Exception</prop>
				<prop key="get*">PROPAGATION_REQUIRED, readOnly,-Exception</prop>
				<prop key="load*">PROPAGATION_REQUIRED, -Exception</prop>
				<prop key="*">readOnly</prop>
			</props>
		</property>
	</bean>

	<!-- 配置要攔截哪些方法 -->
	<bean id="trasactionMethodPointcutAdvisor"
		class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
		<property name="mappedNames">
			<list>
				<value>*</value> <!-- 所有方法 -->
			</list>
		</property>
		<property name="advice">
			<ref local="transactionInterceptor" />
		</property>
	</bean>

	<!-- 配置要攔截哪些類,並使用那些攔截器 -->
	<bean id="ServiceAutoProxyCreator"
		class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
		<property name="proxyTargetClass" value="true"></property>
		<property name="beanNames">
			<list>
				<value>*Service*</value>
			</list>
		</property>
		<property name="interceptorNames">
			<list>
				<value>trasactionMethodPointcutAdvisor</value>
			</list>
		</property>
	</bean>
</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


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">



	<bean id="configurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location">
			<value>classpath:conf/db.properties</value>
		</property>
	</bean>

	<!-- 配置數據源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">

		<property name="driverClass">
			<value>com.p6spy.engine.spy.P6SpyDriver</value>
		</property>
		<property name="jdbcUrl">
			<value>${jdbc.url}</value>
		</property>
		<property name="user">
			<value>${jdbc.username}</value>
		</property>
		<property name="password">
			<value>${jdbc.password}</value>
		</property>


		<!--連接池中保留的最小連接數。 -->
		<property name="minPoolSize">
			<value>2</value>
		</property>

		<!--連接池中保留的最大連接數。Default: 15 -->
		<property name="maxPoolSize">
			<value>15</value>
		</property>

		<!--初始化時獲取的連接數,取值應在minPoolSize與maxPoolSize之間。Default: 3 -->
		<property name="initialPoolSize">
			<value>2</value>
		</property>

		<!--最大空閒時間,60秒內未使用則連接被丟棄。若爲0則永不丟棄。Default: 0 -->
		<property name="maxIdleTime">
			<value>1800</value>
		</property>

		<!--當連接池中的連接耗盡的時候c3p0一次同時獲取的連接數。Default: 3 -->
		<property name="acquireIncrement">
			<value>2</value>
		</property>

		<!--JDBC的標準參數,用以控制數據源內加載的PreparedStatements數量。但由於預緩存的statements 屬於單個connection而不是整個連接池。所以設置這個參數需要考慮到多方面的因素。 
			如果maxStatements與maxStatementsPerConnection均爲0,則緩存被關閉。Default: 0 -->
		<property name="maxStatements">
			<value>0</value>
		</property>

		<!--每60秒檢查所有連接池中的空閒連接。Default: 0 -->
		<property name="idleConnectionTestPeriod">
			<value>0</value>
		</property>

		<!--定義在從數據庫獲取新連接失敗後重復嘗試的次數。Default: 30 -->
		<property name="acquireRetryAttempts">
			<value>30</value>
		</property>

		<!--獲取連接失敗將會引起所有等待連接池來獲取連接的線程拋出異常。但是數據源仍有效 保留,並在下次調用getConnection()的時候繼續嘗試獲取連接。如果設爲true,那麼在嘗試 
			獲取連接失敗後該數據源將申明已斷開並永久關閉。Default: false -->
		<property name="breakAfterAcquireFailure">
			<value>false</value>
		</property>

		<!--因性能消耗大請只在需要的時候使用它。如果設爲true那麼在每個connection提交的 時候都將校驗其有效性。建議使用idleConnectionTestPeriod或automaticTestTable 
			等方法來提升連接測試的性能。Default: false -->
		<property name="testConnectionOnCheckout">
			<value>false</value>
		</property>

		<property name="debugUnreturnedConnectionStackTraces">
			<value>false</value>
		</property>

		<property name="acquireRetryDelay">
			<value>100</value>
		</property>
	</bean>

</beans>

這個xml因爲有註釋,一看即明,不再贅述。使用到了c3p0連接池,所以記得引入c3p0.jar

 

datasource.xml和applicationContext.xml兩個XML中有一個需要注意的細節就是:其中所有標籤的屬性,鍵和值之間不能有空格或者換行存在。如以下三種情況是錯誤的:
<value>false </value>
<value>false
</value>
<property name = "acquireRetryDelay">

空格不容易被發現,但是卻影響程序運行,所以平時要養成良好的習慣。

 

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<!-- 請求參數的編碼方式 -->

	<constant name="struts.i18n.encoding" value="UTF-8" />

	<!-- 指定被struts2處理的請求後綴類型。多個用逗號隔開 -->

	<constant name="struts.action.extension" value="action,do,htm" />

	<!-- 當struts.xml改動後,是否重新加載。默認值爲false(生產環境下使用),開發階段最好打開 -->

	<constant name="struts.configuration.xml.reload" value="true" />

	<!-- 是否使用struts的開發模式。開發模式會有更多的調試信息。默認值爲false(生產環境下使用),開發階段最好打開 -->

	<constant name="struts.devMode" value="true" />

	<!-- 設置瀏覽器是否緩存靜態內容。默認值爲true(生產環境下使用),開發階段最好關閉 -->

	<constant name="struts.serve.static.browserCache" value="false" />

	<!-- 指定由spring負責action對象的創建 -->

	<constant name="struts.objectFactory" value="spring" />

	<!-- 是否開啓動態方法調用 -->
	<constant name="struts.enable.DynamicMethodInvocation" value="false" />

</struts>  

這個唯一要說的就是,因爲項目使用註解配置Action,所以這裏就不再配置Action。

 

MapperConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" >
<configuration>
	<mappers>
		<mapper resource="conf/mapper/PublicMapper.xml" />
	</mappers>
</configuration>

這個文件的作用就是引入其他的Mabits的xml配置文件,如果寫多個的話在這裏添加即可。

 

PublicMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.qlzx.dao.UserDao">
	<resultMap id="userlist" type="com.qlzx.bean.Users">
			<id column="id" property="id" />
			<result column="USERNAME" property="userName" />
			<result column="USERPWD" property="userPwd" />
	</resultMap>

	<!-- 公共查詢 記錄數 -->
	<select id="selectUsers" parameterType="java.util.Map"
		resultMap="userlist">
		select ID,USERNAME,USERPWD from USERINFO where 1=1
		<if test="action == 'login'">
			<if test="userName != null and userPwd != ''">
				and USERNAME = #{userName}
				and USERPWD = #{password}
			</if>
		</if>
	</select>

	<!-- 公共 查詢 記錄集合 -->
	<select id="selectByMap" resultType="java.util.HashMap"
		parameterType="java.util.Map">

	</select>

</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的代碼。

package com.qlzx.dao.basedao;
import java.io.Serializable;
import java.util.List;

import org.apache.ibatis.annotations.Param;

public abstract interface BaseDao<T, E, PK extends Serializable>
{
  public abstract int countByExample(E paramE);

  public abstract List<T> query();

  public abstract int deleteByExample(E paramE);

  public abstract int deleteByPrimaryKey(PK paramPK);

  public abstract int insert(T paramT);

  public abstract int insertSelective(T paramT);

  public abstract List<T> selectByExample(E paramE);

  public abstract T selectByPrimaryKey(PK paramPK);

  public abstract int updateByExampleSelective(@Param("record") T paramT, @Param("example") E paramE);

  public abstract int updateByExample(@Param("record") T paramT, @Param("example") E paramE);

  public abstract int updateByPrimaryKeySelective(T paramT);

  public abstract int updateByPrimaryKey(T paramT);

  public abstract List<T> selectByExampleWithBLOBs(E paramE);

  public abstract int updateByPrimaryKeyWithBLOBs(T paramT);
}

UserDao

package com.qlzx.dao;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.qlzx.bean.Users;
import com.qlzx.dao.basedao.BaseDao;
@Repository
public interface UserDao extends BaseDao<Users, Map<String,?>, BigDecimal> {
	public abstract List<Users> selectUsers(Map<String ,?> paramMap);
	public abstract int insert (Map<String,?>paramMap);
	public abstract int delete(Map<String,?> paramMap);
	public abstract int updateByMap(Map<String,?> paramMap);
}

注意這個Dao只是一個接口。前面說過,因爲具體的查詢已經在xml中配置了,所以這個接口不需要寫實現類,直接調用方法即可。這個dao的包名和xml中的namespace對應,方法名和對應xml中的id對應,包括大小寫

 

Service:

 

UserService

package com.qlzx.service;

import java.util.List;
import java.util.Map;

import com.qlzx.bean.Users;

public abstract class UserService {
	public abstract List<Users> selectUsers(Map<String ,?> paramMap);
	public abstract int insert (Map<String,?>paramMap);
	public abstract int delete(Map<String,?> paramMap);
	public abstract int updateByMap(Map<String,?> paramMap);
}

Service接口,不需要多講。

UserServiceImpl:

package com.qlzx.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.qlzx.bean.Users;
import com.qlzx.dao.UserDao;
import com.qlzx.service.UserService;

@Service
public class UserServiceImpl extends UserService {

	@Resource
	public UserDao dao;

	public void setDao(UserDao dao) {
		this.dao = dao;
	}

	@Override
	public List<Users> selectUsers(Map<String, ?> paramMap) {
		return dao.selectUsers(paramMap);
	}

	@Override
	public int insert(Map<String, ?> paramMap) {
		return 0;
	}

	@Override
	public int delete(Map<String, ?> paramMap) {
		return 0;
	}

	@Override
	public int updateByMap(Map<String, ?> paramMap) {
		return 0;
	}

}

Service實現類,同樣不需要多講。

 

BaseAction

 

package com.qlzx.action.base;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport implements ServletRequestAware,
		ServletResponseAware {
	private static final long serialVersionUID = 7079198825973108720L;
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
}

這個類要說明的是除了繼承ActionSupport以外,還實現了兩個接口:ServletRequestAware,ServletResponseAware 。這兩個接口用於IOC自動注入HttpServletRequest和HttpServletResponse。因爲Action中可能對Session、Response和Request進行操作,所以在BaseAction中實現了這兩個接口。獲取Session、Request和Response除了這個方法以外還可以通過ActionContext獲得。

 

 

PublicController:

package com.qlzx.action;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.qlzx.action.base.BaseAction;
import com.qlzx.bean.Users;
import com.qlzx.service.UserService;
import com.qlzx.utils.RandomPic;
import com.qlzx.utils.Util;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

@Controller
@ParentPackage(value="json-default")
public class PublicController extends BaseAction {

	private static final long serialVersionUID = -1941557452311902440L;
	@Resource
	UserService userService;
	private String userName;
	private String password;
	private String formid;
	private String resultJson;
	private String code;
	private ByteArrayInputStream imageStream;
	
	@Action(value = "login", results = { 
			@Result(name = "success", location = "/message.jsp") ,
			@Result(name = "failed",type="json",params={"root","resultJson"})
	}) 
	public String login() {
		Map<String,Object> paramMap = new HashMap<String,Object>();
		Map<String, ?> session = (Map<String, ?>) ActionContext.getContext()
				.getSession();
		String formid = (String) session.get("formid");
		if (null != formid && this.formid.equals(formid)) {
			resultJson="請勿重複提交";
			return "failed";
		}
		if(!session.get("code").toString().equals(this.code)){
			resultJson = "驗證碼錯誤";
			return "failed";
		}
		paramMap.put("action", "login");
		paramMap.put("userName", userName);
		paramMap.put("password", password);
		List<Users> user = userService.selectUsers(paramMap);
		if (user != null && user.size()>0) {
			String sessionid = Util.getToken();
			resultJson = "登陸成功";
			HttpSession cession = request.getSession(true);
			cession.setAttribute("user", user.get(0));
			cession.setAttribute("sessionId",sessionid);
			return "success";
		} else {
			resultJson = "用戶名或密碼錯誤";
			return "failed";
		}
	}
	@Action(value = "alluser", results = { 
			@Result(name = "success",type="json",params={"root","resultJson"})
	}) 
	public String allUsers() throws IOException {
		Map<String, String> paramMap = new HashMap<String, String>();
		List<Users> userList = userService.selectUsers(paramMap);
		// 將要被返回到客戶端的對象
		// 如果是List類型則使用JsonArray,如果是其他對象類型則使用jsonObject
		JSONArray array = new JSONArray();
		array.addAll(userList);
		this.resultJson = array.toString();
		return "success";
	}
	@Action(value = "logout", results = { @Result(name = "success", location = "/index.jsp") }) 
	public String logout(){
		Map<String, ?> session = (Map<String, ?>) ActionContext.getContext()
				.getSession();
		session.clear();
		return "success";
	}
	@Action(value = "validateCode", results = { 
			@Result(name = "success",type="stream",params={"contentType","image/jpeg","inputName","imageStream"})
	}) 
	public String validateCode() {
		RandomPic pic = new RandomPic();
		BufferedImage image = pic.validatePic();
		String code = pic.getCode();
		System.out.println(code);
		ActionContext.getContext().getSession().put("code", code);
		imageStream = convertImageToStream(image);
		return "success";
	}

	/**
	 * 將BufferedImage轉換成ByteArrayInputStream
	 * @param image 圖片
	 * @return ByteArrayInputStream 流
	 */
	private static ByteArrayInputStream convertImageToStream(BufferedImage image) {

		ByteArrayInputStream inputStream = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(bos);
		try {
			jpeg.encode(image);
			byte[] bts = bos.toByteArray();
			inputStream = new ByteArrayInputStream(bts);
		} catch (ImageFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return inputStream;
	}
	@Action(value = "formid", results = { 
			@Result(name = "success",type="json",params={"root","resultJson"})
	}) 
	public String formid() {
		resultJson = Util.getToken();
		return "success";
	}

	public void setService(UserService service) {
		this.userService = service;
	}


	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setFormid(String formid) {
		this.formid = formid;
	}

	public String getResultJson() {
		return resultJson;
	}

	public ByteArrayInputStream getImageStream() {
		return imageStream;
	}

	public void setCode(String code) {
		this.code = code;
	}

}

首先要說的是,因爲要返回Json,所以我使用了JsonObject。要使用這個傢伙除了代表他自己的json-lib外,還有6個包是必須的,列表如下:



JsonObject可以很方便的將Java對象轉換爲Json字符串。使用過程中有一點需要注意,那就是如果這個java對象是個集合,那麼就要使用JsonArray類,簡單的使用方法在allusers這個方法裏已經有寫。如果是java非集合對象的話,那麼就使用JsonOject類。

另外,不要因爲使用註解配置Action就以爲那些屬性可以使用通過@Autoware或者@Resource註解自動注入。經過我親測這種方法是不行的。我想因爲前臺頁面無法溝通到Spring的原因吧。所以這些屬性必須要手動寫setter和getter。

關於配置Action,因爲使用到註解配置,所以一會兒說到註解的時候一起記錄。


工具類

Util

 

package com.qlzx.utils;

import java.security.MessageDigest;
import java.util.Random;

import sun.misc.BASE64Encoder;

public class Util {
	public static String getToken(){
		String token = System.currentTimeMillis()+new Random().nextInt()+"";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] md5 = md.digest(token.getBytes());
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(md5);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
}

這個類只有一個方法,就是生成一個唯一的Token,這個Token可以用在表單號、sessionid等地方、甚至改寫一下可以爲密碼加密。

 

RandomPic

package com.qlzx.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
 * 產生隨機圖片
 * @author Administrator
 *
 */
public class RandomPic{
	private static final long serialVersionUID = 1L;
	public static final  int WIDTH = 120;	//圖片的寬
	public static final  int HEIGHT = 45;		//圖片高
	private String code = "";
	public BufferedImage validatePic() {
		//創建一個圖像
		BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
		//獲取圖像
		Graphics g = image.getGraphics();
		//1.設置背景色
		setBackground(g);
		//2.設置邊框
		setBorder(g);
		//3.畫干擾線
		drawRandomLine(g);
		//4、生成並畫隨機驗證碼
		drawRandomNum((Graphics2D)g);
		return image;
	}
	private void drawRandomLine(Graphics g) {
		g.setColor(Color.GREEN);
		//畫至少6條幹擾線
		int k = 0;
		while (k < 1){
			k = new Random().nextInt(6);
		}
		for (int i = 0; i < k; i++) {
			//生成干擾線隨機起始座標
			int x1 = new Random().nextInt(WIDTH);
			int y1 = new Random().nextInt(HEIGHT);
			//生成干擾線隨機結束座標
			int x2 = new Random().nextInt(WIDTH);
			int y2 = new Random().nextInt(HEIGHT);
			//畫干擾線
			g.drawLine(x1, y1, x2, y2);
			
			
		}
		
	}
	/**
	 * 寫隨機漢字。因爲 <code> Graphics</code> 沒有旋轉的方法。但默認生成的 <code>Graphics2D</code> 中有旋轉的方法
	 * 所以在傳參時將參數類型強轉成 <code>Graphics2D</code> 
	 * (<code>BufferedImage.getGraphics()</code>方法返回的其實就是<code>Graphics2DGraphics2D</code>)。
	 * @param g
	 */
	private void drawRandomNum(Graphics2D g) {
		code = "";
		g.setColor(Color.RED);
		g.setFont(new Font("微軟雅黑",Font.BOLD,20));
		//常用漢字
		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";
		//寫四個漢字
		for (int i = 0; i < 4; i++) {
			//在字符串範圍內取一個漢字
			String ch = base.charAt(new Random().nextInt(base.length()))+"";
			//將生成的漢字添加到變量中
			code = code+ch;
			//寫字的X座標
			int x = i*30+3;
			//旋轉30度以內
			//因爲也要向左旋轉,所以先生成一個隨機數後再模30即可
			int degree = new Random().nextInt() % 30;
			//旋轉的弧度
			double theta = degree*Math.PI/180;
			//旋轉
			g.rotate(theta, x, 30);
			//寫字
			g.drawString(ch, x, 30);
			//將弧度轉回去
			g.rotate(-theta, x, 30);
		}
		
	}
	private void setBorder(Graphics g) {
		g.setColor(Color.BLUE);
		g.drawRect(0, 0, WIDTH - 2, HEIGHT - 2);
		
	}
	private void setBackground(Graphics g) {
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, WIDTH, HEIGHT);
	}
	public String getCode() {
		return code;
	}
}

這個類用於生成一個漢字驗證碼。代碼很簡單,一看就懂,要說明的是,因爲每次生成的驗證碼不一樣,所以沒有將此類中的變量寫成static,因此對應的方法也就不是static的。使用此類生成驗證碼的時候需要先創建對象。另外,漢字列表可以寫在properties文件中,使用靜態代碼塊加載後使用。


註解。

首先,要使用註解,必須在spring的配置文件中寫上這兩句:

<context:annotation-config/>
<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。如:

@Autowired
@Qualifier("userServiceImpl")
UserService userService;

這樣在使用的時候Spring就會自動尋找所有標記註解的類中的UserServiceImpl這個類去注入。

注意:因爲@AutoWired是按類型注入,所以參數只能是類型名。而因爲bean中的name默認類型名首字母小寫,所以這裏也是首字母小寫。


那麼如果這樣寫行不行呢?

@Resource
@Qualifier("userServiceImpl")
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時候必須用到的註解。

@Action(value = "login", results = { 
			@Result(name = "success", location = "/message.jsp") ,
			@Result(name = "failed",type="json",params={"root","resultJson"})
	})
public String login() {}

以上這段代碼是將login方法通過註解配置成一個名字叫login的action。如果這個方法返回的是success字符串,那麼則跳轉到message.jsp,如果返回的事failed字符串,則返回一個json。@Action是配置Action相關的信息。而@Result這個註解是配置這個Action返回的信息,其中的信息的含義對照一下下面的xml代碼就能看出來。特別要說明的是params這個屬性,他接受的是一個String類型的數組,寫的形式是key、value、key、value這樣的,例如下面:

@Action(value = "validateCode", results = { 
			@Result(name = "success",type="stream",params={"contentType","image/jpeg","inputName","imageStream"})
	}) 

這個是返回一個流,它相當於在struts2的配置文件中加入下面這段代碼:

<action name="validateCode" class="com.qlzx.action.PublicController" method="validateCode">
			<result name="success" type="stream">
				<param name="contentType">image/jpeg</param>
				<param name="inputName">imageStream</param>
			</result>
</action>

當然,因爲返回了Json,所以只有上面那個註解是不行的,還需要在這個方法的類中加一個註解:

@ParentPackage(value="json-default")
public class PublicController extends BaseAction {}

 

上面配置login的註解相當於在Struts中的配置文件寫入瞭如下的代碼:

<package name="User" namespace="/" extends="struts-default,json-default">
		<action name="login" class="com.qlzx.action.PublicController"
			method="login">
			<result name="success" type="redirect">/message.jsp</result>
			<result name="failed" type="json">
				<param name="root">resultJson</param>
			</result>
		</action>
</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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章