Struts + Spring + Hibernate exercises (complete)

Source: Internet
Author: User
With Recommendations:] Struts + Spring + Hibernate upload and download ghost QQ: 71279650 my Email: oksonic@sina.com tools: Eclipse3.1, MyEclipse4.03, Tomcat5.5.9, Properties Editor plug-in, MySql4.1.13 new project: create an index for the Struts framework named login. jsp, add a link pointing to login. jsp press Ctrl + N to create login. jsp and LoginAction. Use the MyEclipse wizard, Remember to select the correct versionOn the ActionForm configuration page, select Dynamic Form as the type and inherit from DynaValidatorForm. Two new attributes are added: username and password. You can hook up the jsp file and change the path to/login. jsp, and then next, change the Input source of LoginAction to/login. jsp, click Finish, press Ctrl + N to create a forwards, Remember to select the correct versionName input indexGo path selection/index. jsp Configure validatorAdd the Struts plug-in first and use the wizard Plugin class: org. apache. struts. validator. validatorPlugInProperty: pathnamesValue:/WEB-INF/validator-rules.xml,/WEB-INF/validation. here, we need two xml files: "validation. the xml file here explains that the validator-rules.xml file is missing in the Struts framework I created using MyEclipse and needs to be dynamically copied to the WEB-INF directory. The file can be downloaded at http://struts.apache.org/as follows: <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> Edit resource files"ApplicationResources. properties" adds the following content: prompt. username = User Name
Prompt. password = User Passworderrors. required = {0} is required. then create the file resource file "ApplicationResources_zh_CN.properties"

Add the following content

Prompt. username = User Name
Prompt. password = logon password errors. required = {0} is required! Modify the struts-config.xml file to add the green font section at the following locations <action-mappings>
<Action
Attribute = "loginForm"
Input = "/login. jsp"
Name = "loginForm"
Path = "/login"
Scope = "request"
Validate = "true"
Type = "com. Test. Struts. Action. loginaction"/> </Action-mappings> it indicates that the submitted data must be verified, and the verification is performed through the validator framework. Modify the execute method of the loginaction. Java file. The content is as follows: public actionforward execute (
Actionmapping mapping,
Actionform form,
Httpservletrequest request,
Httpservletresponse response ){
Dynavalidatorform loginform = (dynavalidatorform) form;
String username = loginform. getstring ("username ");
String Password = loginform. getstring ("password ");
If (username. Equals ("test") | password. Equals ("test ")){
Return Mapping. findforward ("indexgo ");
} Else {
Return Mapping. getinputforward ();
}
} Modify login now. jsp adds the following green font section <% @ page language = "java" contentType = "text/html; charset = UTF-8" %> where charset = UTF-8 is a character encoding that uses a UTF-8, this is also used to support internationalization. Now we can start Tomcat to test http: // localhost/login/. Here we will explain that the port number of my Tomcat has been changed to 80, so you don't have to use http: // localhost: 8080/login. If you directly submit the form without entering any data, you can see the effect. Well, if there is no problem, let's continue to look at it. If there is a problem, we have to go up and read pai_^. Now we have created the Spring framework. Here I load all the Spring packages, because I still don't know which classes are used, add them all to make it easy to select the second one in a single region. In this way, all the class libraries and labels will be copied to the project, this facilitates the subsequent deployment of the next step is to create a configuration file, put the file in the "WebRoot/WEB-INF" directory, the file name is called "applicationContext. xml "configuration struts-config.xml file, add (spring) plug-in <plug-in className =" org. springframework. web. struts. contextLoaderPlugIn ">
<Set-property = "contextConfigLocation" value = "/WEB-INF/applicationContext. xml"/>
</Plug-in>

Modify 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> to: <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 part is the modification content. Here, the spring proxy is used to control the Action. When submitted to/login. do is to assign control to spring, and then spring decides whether to switch back to struts Action to configure spring now <? 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 = "com. test. struts. action. loginAction "singleton =" false "> </bean> </beans> the green font indicates the configuration content attribute singleton =" false "about transfer control ", specifies the Action instance acquisition method to re-create each time. Solve the criticized thread security problem in Struts (in Struts, an Action instance is used to process all requests, which leads to the thread synchronization problem of class public resources in concurrent requests .) (From the spring Development Guide) at this time, if you want to perform a test, you can also, but in order to save time, you will not perform the test.

Create a database inHere I am using mysql4.1.13 CREATE TABLE 'user '(
'Id' int (11) not null auto_increment,
'Username' varchar (50) not null default '',
'Password' varchar (50) not null default '',
Primary Key ('id ')
) Engine = MyISAM default charset = Latin1; add record insert into user (username, password) values ('test', 'test ') Create a Hibernate frameworkIn the configuration page, configure the database connection. It is important to click the link to copy JDBC to the lib directory and use myeclipse's data Database Explorer tool to create a user. HMB. XML, abstractuser. java, user. after the Java ing file is created, you can automatically generate the hibernate. cfg. XML Deletion Create UserDAO. java and UserDAOImp. java

Userdao. Java

Public interface userdao {

Public Abstract Boolean isvaliduser (string username, string password );

}

 

Userdaoimp. Java

Import java. util. List;

Import org. springframework. orm. hibernate3.support. HibernateDaoSupport;

Import com. test. Hibernate. SessionFactory;

Public class UserDAOImp extends HibernateDaoSupport implements UserDAO {

Private SessionFactory sessionFactory;

Private static String hql = "from User u where u. username =? ";

Public boolean isValidUser (String username, String password ){

List userList = this. getHibernateTemplate (). find (hql, username );

If (userList. size ()> 0 ){

Return true;

}

Return false;

}

}

  Modify the loginaction. Java FileUse the userdao method to verify 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 {private userdao; Public userdao getuserdao (){
Return userdao;
} Public void setuserdao (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 used to modify the last spring configuration. <? 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/test </value>
</Property>
<Property name = "username">
<Value> root </value>
</Property>
<Property name = "password">
<Value> root </value>
</Property>
</Bean> <! -- Configure sessionFactory. Note the differences of the packages introduced here -->
<Bean id = "sessionFactory" class = "org. springframework. orm. hibernate3.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"> org. hibernate. dialect. MySQLDialect </prop>
<Prop key = "hibernate. show_ SQL"> true </prop>
</Props>
</Property>
</Bean> <bean id = "transactionManager" class = "org. springframework. orm. hibernate3.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> now you can test it! When writing code with configuration content, be sure to pay attention to hibernate and hibernate3. The names of these two packages are only one word different. Do not make any mistakes; otherwise, it is very difficult to find errors.

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.