Struts+hibernate+spring Simple Example

Source: Internet
Author: User
Tags stub xsl
Environment: windows2003& jdk1.5.05& eclipse3.1+myeclipse4.03 do a login exercise.

The Struts section of login has been completed, which realizes dynamic actionform and dynamic validator verification, and details all the following files:

Struts-config.xml

<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE struts-config Public "-//apache software foundation//dtd struts Configuration 1.1//en" "/http Jakarta.apache.org/struts/dtds/struts-config_1_1.dtd ">

<struts-config>
<data-sources/>
<form-beans >
<form-bean name= "LoginForm" type= "Org.apache.struts.validator.DynaValidatorForm" >
<form-property name= "Password" type= "java.lang.String"/>
<form-property name= "username" type= "java.lang.String"/>
</form-bean>

</form-beans>

<global-exceptions/>
<global-forwards >
<forward name= "Indexgo" path= "/index.jsp"/> </global-forwards>

<action-mappings >
<action
Attribute= "LoginForm"
input= "/login.jsp"
Name= "LoginForm"
Path= "/login"
Scope= "Request"
Validate= "true"
Type= "Com.test.struts.action.LoginAction"/> </action-mappings>

<message-resources parameter= "Com.test.struts.ApplicationResources"/>
<plug-in classname= "Org.apache.struts.validator.ValidatorPlugIn" >
<set-property property= "pathnames" value= "/web-inf/validator-rules.xml,/web-inf/validation.xml"/>
</plug-in>
</struts-config>

login.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "%>
<%@ taglib uri= "Http://jakarta.apache.org/struts/tags-bean" prefix= "Bean"%>
<%@ taglib uri= "http://jakarta.apache.org/struts/tags-html" prefix= "html"%>

<title>jsp for LoginForm form</title>
<body>
Username: Password: </body>

index.jsp

<title>my JSP ' index.jsp ' starting page</title>

<body>
<a href= "login.jsp" >Login</a>
</body>

Loginaction.java

Created by MyEclipse Struts
XSL Source (default): Platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.0.1/xslt/javaclass.xsl

Package com.test.struts.action;

Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import org.apache.struts.action.Action;
Import Org.apache.struts.action.ActionForm;
Import Org.apache.struts.action.ActionForward;
Import org.apache.struts.action.ActionMapping;
Import Org.apache.struts.validator.DynaValidatorForm;

/**
* MyEclipse Struts
* Creation date:10-27-2005
*
* XDoclet Definition:
* @struts. Action path= "/login" name= "LoginForm" input= "login.jsp" scope= "Request" validate= "true"
*/
public class Loginaction extends Action {

---------------------------------------------------------Instance Variables

---------------------------------------------------------Methods

/**
* Method Execute
* @param mapping
* @param form
* @param request
* @param response
* @return Actionforward
*/
Public Actionforward Execute (
Actionmapping Mapping,
Actionform form,
HttpServletRequest request,
HttpServletResponse response) {
Dynavalidatorform loginform = (dynavalidatorform) Form;
TODO auto-generated Method Stub
String Username= (String) loginform.get ("username");
String password= (String) loginform.get ("password");
Loginform.set ("password", null);
if (Username.equals ("Sonic") | | Password.equals ("Sonic")) {
System.out.println ("AAA");
Return Mapping.findforward ("Indexgo");
}
else {
System.out.println ("BBB");
return Mapping.getinputforward ();
}
}

}

applicationresources.properties

Prompt.username=user Name
Prompt.password=user Password

ERRORS.REQUIRED={0} is required.

applicationresources_zh_cn.properties

Prompt.username= User Name
prompt.password= Login Password

ERRORS.REQUIRED={0} is required.

Validation.xml

<form-validation>
<formset>
<form name= "LoginForm" >
<field property= "username" depends= "required" >
<arg0 key= "Prompt.username"/>
</field>
<field property= "password" depends= "required" >
<arg0 key= "Prompt.password"/>
</field>
</form>
</formset>
</form-validation>

All the code has been completed to this.

Now create the Spring framework

Configure the Struts-config.xml file to add (Spring) plugins

<plug-in classname= "Org.springframework.web.struts.ContextLoaderPlugIn" >
<set-property property= "contextconfiglocation" value= "/web-inf/applicationcontext.xml"/>
</plug-in>

Modifying the Loginaction configuration

Original:

<action
Attribute= "LoginForm"
input= "/login.jsp"
Name= "LoginForm"
Path= "/login"
Scope= "Request"
Validate= "true"
Type= "Com.test.struts.action.LoginAction"/> </action-mappings>

Switch

<action
Attribute= "LoginForm"
input= "/login.jsp"
Name= "LoginForm"
Path= "/login"
Scope= "Request"
Validate= "true"
Type= "Org.springframework.web.struts.DelegatingActionProxy"/>

</action-mappings>

The Green Font section is for modifying content

This will use the spring Proxy to control the action

When submitted to/login.do, the control is given to spring, which is then determined by spring to return to the struts action

Now to configure Spring

<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE beans Public "-//spring//dtd bean//en" "Http://www.springframework.org/dtd/spring-beans.dtd" >

<beans>
<bean name= "/login" class= "Net.xiaxin.action.LoginAction" singleton= "false" ></bean>
</beans>

The green font is about handing over control of the configuration content property singleton= "False", indicating that an instance of the action is acquired for each re-creation. Resolves a notorious thread-safety problem in struts (struts, where all requests are processed by an action instance, which results in thread synchronization problems for the class common resources in concurrent requests.) ) (excerpt from the Spring Development Guide)

Build a database here, I'm using mysql4.1.1x.

CREATE TABLE ' user ' (
' ID ' int (one) not NULL auto_increment,
' USERNAME ' varchar (not NULL default ' '),
' PASSWORD ' varchar (not NULL default ' '),
PRIMARY KEY (' ID ')
) Engine=myisam DEFAULT charset=latin1;

Creating Hibernate frames

Create User.hmb.xml, Abstractuser.java, User.java mapping files using the MyEclipse Data Explorer tool

Auto-generated hibernate.cfg.xml can be deleted after creation is complete

Create Userdao.java, Userdaoimp.java

Modify the Loginaction.java file and use the Userdao method for user authentication

Package com.test.struts.action;

Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import org.apache.struts.action.Action;
Import Org.apache.struts.action.ActionForm;
Import Org.apache.struts.action.ActionForward;
Import org.apache.struts.action.ActionMapping;
Import Org.apache.struts.validator.DynaValidatorForm;

Import Com.test.UserDAO;
public class Loginaction extends Action {public Userdao Getuserdao () {
return Userdao;
}

public void Setuserdao (Userdao Userdao) {
This.userdao = Userdao;
}

Public Actionforward Execute (actionmapping mapping, Actionform form,
HttpServletRequest request, HttpServletResponse response) {
Dynavalidatorform loginform = (dynavalidatorform) Form;
TODO auto-generated Method Stub
String username = (string) loginform.get ("username");
String password = (string) loginform.get ("password");
Loginform.set ("password", null);
if (Userdao.isvaliduser (Username,password)) {
Return Mapping.findforward ("Indexgo");
} else {
return Mapping.getinputforward ();
}
}

}
The green font is the modified part

Now the last spring is configured

<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE beans Public "-//spring//dtd bean//en" "Http://www.springframework.org/dtd/spring-beans.dtd" >

<beans>
 <bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" Destroy-method = "Close",
  <property name= "Driverclassname";
   <value> Com.mysql.jdbc.driver</value>
  </property>
  <property name= "url" >
   <value>jdbc:mysql://localhost:3306/test</value>
  </property
  <property name= "username";
   <value>root</value>
  </property>
  <property name= "password";
   <value ></value>
  </property>
 </bean>

 <bean id= "sessionfactory" class= "Org.springframework.orm.hibernate.LocalSessionFactoryBean";
  <property name= "DataSource",
   <ref local= "DataSource"/>
   </property>
  <property name= "mappingresources";
   <list
    <value>com/test/hibernate/user.hbm.xml</value>
    </list>
  </property>
  <property name= "HibernateProperties" >
   <props>
    <prop key= "Hibernate.dialect" > Net.sf.hibernate.dialect.mysqldialect</prop>
    <prop key= "Hibernate.show_sql" >true</prop>
   </props>
  </property>
 </bean >

<bean id= "TransactionManager" class= "Org.springframework.orm.hibernate.HibernateTransactionManager" >
<property name= "Sessionfactory" >
<ref local= "Sessionfactory"/>
</property>
</bean>

<bean id= "Userdao" class= "COM.TEST.USERDAOIMP" >
<property name= "Sessionfactory" >
<ref local= "Sessionfactory"/>
</property>
</bean>

<bean id= "Userdaoproxy" class= "Org.springframework.transaction.interceptor.TransactionProxyFactoryBean" >
<property name= "TransactionManager" >
<ref bean= "TransactionManager"/>
</property>
<property name= "Target" >
<ref local= "Userdao"/>
</property>
<property name= "Transactionattributes" >
<props>
<prop key= "insert*" >PROPAGATION_REQUIRED</prop>
<prop key= "get*" >PROPAGATION_REQUIRED,readOnly</prop>
<prop key= "is*" >PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean> <bean name= "/login" class= "Com.test.struts.action.LoginAction" singleton= "false" >
<property name= "Userdao" >
<ref bean= "Userdaoproxy"/>
</property>
</bean>
</beans>

It is now possible to test it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.