Today, we set up an SSH + DWR framework. In fact, the SSH framework configuration is similar to the previous one. It mainly uses annotations to implement the C and M layers. below is the Web. xml configuration.
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"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>nwr-web</display-name><context-param><param-name>contextConfigLocation</param-name><param-value>classpath*:applicationContext*.xml</param-value></context-param><context-param><param-name>log4jConfigLocation</param-name><param-value>/WEB-INF/classes/log4j.properties</param-value></context-param><context-param><param-name>log4jRefreshInterval</param-name><param-value>60000</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><listener><listener-class>org.springframework.web.util.Log4jConfigListener</listener-class></listener><filter><filter-name>struts-prepare</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class><init-param><param-name>actionPackages</param-name><param-value>com.essential.action</param-value></init-param></filter><filter><filter-name>struts-execute</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter</filter-class></filter><servlet><servlet-name>dwr</servlet-name><servlet-class>org.directwebremoting.spring.DwrSpringServlet</servlet-class><init-param><param-name>debug</param-name><param-value>true</param-value></init-param></servlet><filter-mapping><filter-name>struts-prepare</filter-name><url-pattern>/*</url-pattern></filter-mapping><filter-mapping><filter-name>struts-execute</filter-name><url-pattern>/*</url-pattern></filter-mapping><filter><filter-name>characterEncodingFilter</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><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>characterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><servlet-mapping><servlet-name>dwr</servlet-name><url-pattern>/dwr/*</url-pattern></servlet-mapping><welcome-file-list><welcome-file>News.jsp</welcome-file></welcome-file-list><error-page><error-code>500</error-code><location>/error.jsp</location></error-page><error-page><error-code>402</error-code><location>/error.jsp</location></error-page></web-app>
Note that if you want to use the struts2 annotation, you must add the actionpackages parameter When configuring the filter. this parameter is used to set the path of the struts2 container to search for the action package.
The following is the configuration file of Struts. xml:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"><struts><package name="default" extends="struts-default"><global-results><result name="error">error.jsp</result><result name="input">error.jsp</result></global-results></package><constant name="struts.convention.default.parent.package"value="default" /></struts>
I use struts. the Convention plugin defines the parent package of all actions as a custom default package. You can also customize other parent packages, the defined parent package is the default parent package for all actions. You can also use the @ Package label to define different packages for the action class.
The following describes the spring configuration file:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:dwr = "http://www.directwebremoting.org/schema/spring-dwr"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd" > <dwr:annotation-scan scanRemoteProxy="true" base-package="com.essential.dwr"/> <dwr:annotation-scan scanDataTransferObject="true" base-package="com.essential.entity"/><context:component-scan base-package="com.essential" /> <bean id="configurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath*:init.properties</value> </property> </bean><bean id="mainDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> <property name="minPoolSize" value="${jdbc.minPoolSize}"></property> <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property> <property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}"></property> <property name="maxIdleTime" value="${jdbc.maxIdleTime}"></property> <property name="acquireIncrement" value="${jdbc.acquireIncrement}"/> </bean><bean id="dataSource"class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy"><property name="targetDataSource"><ref local="mainDataSource" /></property></bean><bean id="sessionFactory"class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"><property name="dataSource"><ref bean="dataSource" /></property><property name="hibernateProperties"><props><prop key="hibernate.dialect">${hibernate.dialect}</prop><prop key="hibernate.show_sql">${hibernate.show_sql}</prop><prop key="hibernate.format_sql">${hibernate.format_sql}</prop><prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop><prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop></props></property><property name="packagesToScan" value="${hibernate.packagesToScan}" /></bean><bean id="transactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory"><ref local="sessionFactory" /></property></bean><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="upd*" propagation="REQUIRED" read-only="false" /><tx:method name="del*" propagation="REQUIRED" read-only="false" /><tx:method name="add*" propagation="REQUIRED" read-only="false" /><tx:method name="insert*" propagation="REQUIRED" read-only="false" /><tx:method name="find*" propagation="SUPPORTS" read-only="true" /><tx:method name="query*" propagation="SUPPORTS" read-only="true" /><tx:method name="*" propagation="SUPPORTS" read-only="true" /></tx:attributes></tx:advice><aop:config><aop:pointcut id="productServiceMethods"expression="${spring.execution}" /><aop:advisor advice-ref="txAdvice" pointcut-ref="productServiceMethods" /></aop:config></beans>
First, the first two lines of configuration are the integration of DWR and spring. The first is the package name where the remote proxy object of DWR is configured, the second is the package name of the transfer object in DWR.
The following line shows the package name of the spring search bean. The following configurations are unchanged.
Now let's talk about how to implement the struts2 action with annotations:
1. in fact, the annotation is similar to the xml configuration step. First, it must be a configuration package, but we used struts. convention is configured with the default package, so you do not need to configure it any more. Then you must configure the virtual path for access, that is, configure namespace and use @ namespace (value = "/mail ") label configuration. The value attribute is the path for configuring the namespace.
2. after namespace is configured, action is configured. @ action (value = "Sendmail", Results = {@ result (name = success, type = "Redirect ", location = ".. /news. JSP ")}) label, where value is the path of the configured action, results is the page for configuring the processing result of the action, you can also configure multiple pages.
In this way, a complete action is configured. To integrate with spring, we must call Spring bean. To call bean, it is easy to define a private variable, then use the @ resource tag on the variable, but note that the variable name must be consistent with the name in the @ service tag mentioned later, otherwise, the injection fails.
An example is provided below:
Public class activityaction extends baseaction {/*****/Private Static final long serialversionuid = 5488332603981342055l; private long UID; private long eventid; private activityservice; /*** query the activity list ** @ return * @ throws exception */@ action (value = "findactivitylist") Public String findactivitylist () throws exception {list <activityvo> activityvos = activityservice. findactivitylist (); string result = listtojsonstring (activityvos); towrite (result); return NULL ;} /*** participate in the activity ** @ return * @ throws exception */@ action (value = "joinactivity") Public String joinactivity () throws exception {Boolean issucc = activityservice. insertactivityforuser (eventid, UID); towrite (issucc + ""); return NULL ;} /*** search for activity lists based on user IDs ** @ return my activity list * @ throws exception */@ action (value = "findmyactivitylist") Public String findmyactivitylist () throws exception {list <activityvo> activityvos = activityservice. findmyactivitylist (UID); string result = listtojsonstring (activityvos); towrite (result); return NULL ;}@ resourcepublic void setactivityservice (activityservice) {This. activityservice = activityservice;} public void setuid (Long UID) {This. uid = uid;} public void seteventid (long eventid) {This. eventid = eventid ;}}
Next, let's talk about the service configuration. The configuration method is to use the @ Service (value = "servicename") label to set the service. It's very easy, in addition, when Dao is called, you can use the @ resource tag to introduce attributes like the action to call service. The following is the example source code:
@Service(value = "activityService")public class ActivityServiceImpl implements ActivityService {@ResourceActivityDao activityDao;private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@Overridepublic boolean insertActivityForUser(long eventId, long uid) {return activityDao.insertActivityForUser(eventId, uid);}@Overridepublic List<ActivityVo> findActivityList() {List<Activity> list = activityDao.findActivityList();List<ActivityVo> activityVos = new ArrayList<ActivityVo>();for (Activity activity : list) {ActivityVo activityVo = new ActivityVo();activityVo.setId(activity.getId());activityVo.setTitle(activity.getTitle());activityVo.setPublishTime(df.format(activity.getPublishTime()));activityVo.setImagurl(activity.getImagurl());activityVo.setContent(activity.getContent());activityVos.add(activityVo);}return activityVos;}@Overridepublic List<ActivityVo> findMyActivityList(long uid) {List<Activity> list = activityDao.findMyActivityList(uid);List<ActivityVo> activityVos = new ArrayList<ActivityVo>();for (Activity activity : list) {ActivityVo activityVo = new ActivityVo();activityVo.setId(activity.getId());activityVo.setTitle(activity.getTitle());activityVo.setPublishTime(df.format(activity.getPublishTime()));activityVo.setImagurl(activity.getImagurl());activityVo.setDatetime(activity.getDatetime());activityVo.setDescription(activity.getDescription());activityVo.setContent(activity.getContent());activityVos.add(activityVo);}return activityVos;}}
Then, the DaO configuration is similar to the previous one, that is, when the DAO is defined, the @ repository tag is used, and the code can be directly pasted:
@ Repository (value = "activitydao ") public class activitydao extends basedao <activity> {/*** participate in activity ** @ Param eventid * Activity ID * @ Param uid * User ID * @ return success return true, return false */@ suppresswarnings ("unchecked") Public Boolean insertactivityforuser (long eventid, Long UID) {session = getsession (); query = session. createsqlquery ("select au. aid from activity_users au where Au. aid =: aid and AU. uid =: uid "); List list = query. setparameter ("uid", UID ). setparameter ("aid", eventid ). list (); If (list. size ()> 0) {return false;} else {session. createsqlquery ("insert into activity_users (aid, UID) values (: Aid,: UID )"). setparameter ("uid", UID ). setparameter ("aid", eventid0000.exe cuteupdate (); Return true ;}/ *** query activity list ** @ return activity list */@ suppresswarnings ("unchecked ") public list <activity> findactivitylist () {session = getsession (); List <activity> List = session. createquery ("from activity where status = 2 order by publishtime DESC "). setmaxresults (10 ). list (); return list ;} /*** query all activities that a user participates in based on the user ID ** @ Param uid * User ID * @ return activity list */@ suppresswarnings ("unchecked ") public list <activity> findmyactivitylist (final Long UID) {return gethibernatetemplate(cmd.exe cute (New hibernatecallback () {@ overridepublic object doinhibernate (session) throws hibernateexception, sqlexception {list <activity> List = session. createquery ("select a from activity a left join. users u where u. id =: uid order by. publishtime DESC "). setparameter ("uid", UID ). list (); return list ;}});}}
The following is the basedao code:
public class BaseDao<E> extends HibernateDaoSupport {@Resource(name = "sessionFactory")public void setInjectionSessionFacotry(SessionFactory sessionFacotry) {super.setSessionFactory(sessionFacotry);}@PostConstructpublic void injectSessionFactory() {logger.info(super.getSessionFactory());}public Serializable save(E entity) {return getHibernateTemplate().save(entity);}public void update(E entity) {getHibernateTemplate().update(entity);}public void delete(E entity) {getHibernateTemplate().delete(entity);}public User query(long id) {return getHibernateTemplate().get(User.class, id);}}
Inject the sessionfactory object into this class.
The following describes the configuration of DWR, to configure the DWR remote proxy object, use the @ remoteproxy method in the @ remoteproxy class on the class to directly call the method using the class name + method name in Javascript. If you want to call the bean of spring, just like the above, let's not talk about it much. If Java objects are required for data transmission between DWR and JSP pages, use the @ datatransferobject label on the object class to be transferred to convert the Data Type correctly. Otherwise, an exception is reported. The following is an example:
@ Remoteproxypublic class testdwr implements serializable {/***/Private Static final long serialversionuid =-2060851629180328131l; @ remotemethodpublic string testdwr () {return "test .";}}
You can define a class as needed in the Entity example. If you add a label, it will be OK and will not be listed here.
Three JSPs must be introduced for using DWR in JSP:
<script type="text/javascript" src="<%=path %>/dwr/engine.js"></script><script type="text/javascript" src="<%=path %>/dwr/util.js"></script>
<script type="text/javascript" src="<%=path %>/dwr/interface/TestDwr .js"></script>
The first two are the two JS packages that DWR must use, and the next one is the class you defined in Java. In this way, you can call the methods in it.
I have finished all the work here. Please add more to the shortcomings.
All jar packages have been uploaded, you can download http://download.csdn.net/detail/yaoyeyzq/4516689 as needed