struts2 + hibernate3.2 + spring2.0 instance configuration + Getting Started

sponsored links
eclipse3.2, myeclipse5.0, Jboss4.0.3, sql server2000 sp3

Principle of

In the java enterprise applications, ejb powerful ejb configuration with the complex and difficult to learn as well known. But in the past and what we do? Just bite the bullet and came to learn ejb. Really a bit "knowingly mountain tiger, bias difficult path" spirit. Optimistic about the present situation has changed, java open source continued popularity, allowing developers to java enterprise-class applications are no longer confined to the area ejb. The following briefly describe how to use open source, Spring, Hibernate, and Struts to build a lightweight structure.

1, the overall architecture describes the software engineering field, in order to reduce module coupling and improve the reusability of modules, hierarchical has been widely adopted method. In fact, layering also allow developers to focus on a particular layer developed, making software development division of thinning, to improve production efficiency.
An enterprise-class java applications, usually divided into the following layers: UI layer, business logic layer, data persistence layer, the domain object layer. The following briefly describes each of these layers:

The domain object layer: a specific entity classes, such as teachers, students, and so these specific classes (Note: the database needs to correspond to a particular table), by the persistence layer classes to complete.

Data persistence layer: is mainly responsible for dealing with the underlying database. Spring package Hibernate used here to simplify the operation of the actual encoding. The major operation for the CRUD (create, read, update, delete), completed by the DAO.

Business Logic Layer: The main charge of specific business processes. Spring's IOC and AOP through the various functions to achieve the coupling connected to, the business logic from the service to complete, service to operate the database by calling the DAO to achieve business logic. service from the Struts-Action class to invoke.

UI layer: responsible for user interaction, including: receiving a user's request, the processing results back to the user. Present mainly uses struts to do UI layer, although these events compared to Tapestry and JSF-driven technology, the presentation layer, Struts design a bit old-fashioned, but it is still the de facto standard performance level, so we still use it .

Content

Hibernate table users through the establishment and the class corresponding to Users.

In the Struts framework to create the index.jsp form of user name and password, action through the class methods determine whether the input information in the database a record of information consistent. If so, the go next.jsp page shows all the user information. If you are inconsistent with each record, they are required to re-enter.

Steps

1, the preparatory work: using sql server 2000 to create a test database, then create a users table that contains two fields username and password. The script is as follows
CREATE DATABASE test;
USE test;

CREATE TABLE users (
id int (11) NOT NULL idntity (1,1),
username varchar (20) NOT NULL default'',
password varchar (20) default'',
PRIMARY KEY (id)
)

Open the myeclipse perspective of the database explore

Figure 5-1 Open Database Browser perspective right-click an empty area of the left, click the new button

Figure 5-2 Open Database Connectivity (1)

Figure 5-3 Open Database Connectivity (2)

Test database configuration was successful.

2, create a myeclipse web-project, named aaa

Figure 5-4 to create web project

3, the introduction of Spring Package

Right Project Name

Figure 5-5 is intended to increase Spring Package

Figure 5-6 selected to increase the Spring Package Note: This can then add the spring in order to save the relevant packages, so a one-off all of the packages selected. Select the Copy option, it will copy these packages into the / WebRoot / WEB-INF / lib directory to facilitate the subsequent actual deployment. Then click "Next".

Figure 5-7 Select Spring configuration file (applicationContext.xml) Path

4, add the hibernate package

Figure 5-8 Adding hibernate package

The system detects that the project has added a Spring package, choose to use Spring's configuration file (ApplicationContext.xml)

Figure 5-9 Select hibernate configuration file (1)

Figure 5-10 Select hibernate configuration file and SessionFactory ID

Figure 5-11 Set Bean Id and select the DB Profile

Figure 5-12 Do not create SessionFactory class

Finally click the Finish button, you can in the final.

5, modify the library file

What's different, Spring2.0 not put all the packages can be added to the lib directory to run the project, but all the packages added to the lib directory will be conflict. As MyEclipse5.5 right Spring2.0 support is not yet mature, it will join the Spring components do not need to add into the package. Therefore need to manually right lib directory of the package to increase, delete, change.

(1) Delete the file

Into the project Webroot / WEB-INF / lib directory in order to "details" approach to sort all the files, locate and delete the following six documents: asm-2.2.2.jar, asm.jar, asm-commons-2.2.2 . jar, asm-util-2.2.2.jar, asm-attr.jar, cglib-2.1.3.jar.

Figure 5-13-1 delete unneeded files

(2) to increase the file

To the MyEclipse installation directory, enter the eclipse / plugins folder, use the search function to find commons-pool.jar file, there may be multiple results, only one can put it into the lib directory.

6, add Struts2.0 package

Struts2.0 downloaded from www.apache.org package, under normal circumstances is the struts-version-all.zip, open inside the lib folder, as shown in the figure below the package to add to the project's lib directory.

Figure 5-14 Add struts2.0 Package

Refresh project is completed.

7, build engineering framework, write log4j.properties file

In the project src directory of several new packages, and methods for the src folder, right-click, and then shown:

Figure 5-15 Create a new package

Figure 5-16 completed the package structure

Of which:

Com.action package stored in various action file.

Com.service bag storage service interface

Com.service.impl package to achieve service interface.

Com.filter packet stored filter files, write these files in order to solve the Chinese problem.

Com.hibernate package store and the mapping file hibernate persistent classes.

Com.util package into public documents, such as BaseService.java, BaseObject.java, BaseAction.java, if different service calls the same method, these methods can be written in the BaseService.java, the below details.

First create BaseObject class BaseObject.java:

Right-click com.util package, select new-> Class, as shown:

Figure 5-17 Create a new class

Figure 5-18

package com.util;

import java.io.Serializable;

import java.text.SimpleDateFormat;

import java.util.Date;

import org.apache.commons.lang.builder.EqualsBuilder;

import org.apache.commons.lang.builder.HashCodeBuilder;

import org.apache.commons.lang.builder.ToStringBuilder;

import org.apache.commons.lang.builder.ToStringStyle;

public class BaseObject implements Serializable (

public String toString () (

return ToStringBuilder.reflectionToString (this, ToStringStyle.MULTI_LINE_STYLE);

)

public boolean equals (Object o) (

return EqualsBuilder.reflectionEquals (this, o);

)

public int hashCode (Object o) (

return HashCodeBuilder.reflectionHashCode (this);

)

protected String showDatetime (Date pidate) (

return getFormateDate (pidate, "yyyy-MM-dd HH: mm");

)

protected String showDate (Date pidate) (

return getFormateDate (pidate, "yyyy-MM-dd");

)

protected String showTime (Date pidate) (

return getFormateDate (pidate, "HH: mm");

)

private String getFormateDate (Date pidate, String formate) (

if (pidate == null) (

return null;

)

else (

return (new SimpleDateFormat (formate)). format (pidate);

)

)

)

Re-establishing BaseService.java

Figure 5-18 specify the class name

In the pop-up dialog box to specify the class name BaseService, click to select the parent category "Browse" button.

Then came the pop-up dialog box, select super-class called HibernateDaoSupport, as shown:

Figure 5-19 select the parent class

Double-click the selected parent class (no points, "OK" button), then "Finish" to complete BaseService.java creation. Eclipse will automatically jump to the next file. Temporarily add the following code to BaseService.java:

package com.util;

import java.io.Serializable;

import java.util.List;

import org.springframework.dao.DataAccessException;

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

public class BaseService extends HibernateDaoSupport (

public Serializable insert (BaseObject obj) throws DataAccessException (

return getHibernateTemplate (). save (obj);

)

public void update (BaseObject obj) throws DataAccessException (

getHibernateTemplate (). update (obj);

)

public void delete (BaseObject obj) throws DataAccessException (

getHibernateTemplate (). delete (obj);

)

public Object load (Class cls, Serializable id) throws DataAccessException (

return getHibernateTemplate (). load (cls, id);

)

public List getAll (String hql, Object objs []) throws DataAccessException (

if (objs == null)

return getHibernateTemplate (). find (hql);

else

return getHibernateTemplate (). find (hql, objs);

)

public Object getFirstObject (String hql, Object objs []) throws DataAccessException (

Object ret = null;

List tmp = getAll (hql, objs);

if (tmp! = null & & tmp.size ()> 0)

ret = tmp.get (0);

return ret;

)

)

Note: In the BaseService.java defined in several ways, including insert, modify, delete, query, if necessary you can call directly.

In a similar way to a new BaseAction.java file, select the parent category ActionSupport, attention is com.opensymphony.xwork2.ActionSupport, the other two are the Struts1.

Then, write log4j.properties file, which the main role is to back every step of the operation of the console to display the corresponding log information to facilitate the program debugging.

Right-click on the src directory and select new-> File, pop-up dialog box as shown below, specify a file named log4j.properties. And then "Finish".

Figure 5-20 to establish log4j.properties file

Puts inside the following code:

log4j.rootLogger = INFO, CONSOLE

log4j.appender.CONSOLE = org.apache.log4j.ConsoleAppender

log4j.appender.CONSOLE.layout = org.apache.log4j.PatternLayout

log4j.appender.CONSOLE.layout.ConversionPattern =% d [% t]%-5p% c -% m% n

# Print only messages of level WARN or above in the package com.foo.

# Log4j.logger.com.foo = WARN

# log4j.logger.au.gov.sa.health.oacis = DEBUG

# log4j.logger.org.apache.struts2 = DEBUG

# log4j.logger.org.apache = INFO

# log4j.logger.org.hibernate = INFO

# log4j.logger.ca.uhn = INFO

# # # Log HQL query parser activity

# log4j.logger.org.hibernate.hql.ast.AST = debug

# # # Log just the SQL

log4j.logger.org.hibernate.SQL = debug

# # # Log JDBC bind parameters # # #

log4j.logger.org.hibernate.type = INFO

# log4j.logger.org.hibernate.type = debug

# # # Log schema export / update # # #

log4j.logger.org.hibernate.tool.hbm2ddl = DEBUG

# # # Log cache activity # # #

# log4j.logger.org.hibernate.cache = debug

# # # Log transaction activity

# log4j.logger.org.hibernate.transaction = debug

# # # Log JDBC resource acquisition

# log4j.logger.org.hibernate.jdbc = debug

# # # Enable the following line if you want to track down connection # # #

# # # Leakages when using DriverManagerConnectionProvider # # #

# log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider = trace

After the start so that when the service will show a more detailed log information.

8, in order to solve the problem written in Chinese filter paper

Right-click on the com.filter package, create a new Class, named NewFilterDispatcher, select its parent category FilterDispatcher, puts inside the following code:

public class NewFilterDispatcher extends FilterDispatcher (

private static String encoding = "GB2312";

public void init (FilterConfig filterConfig) throws ServletException (

super.init (filterConfig);

String encodingParam = filterConfig.getInitParameter ( "encoding");

if (encodingParam! = null & & encodingParam.trim (). length ()! = 0) (

encoding = encodingParam;

)

)

public void doFilter (ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException, ServletException (

request.setCharacterEncoding (encoding);

super.doFilter (request, response, chain);

)

)

Write a filter class, named SetCharacterEncodingFilter, attention to the selection of its interface javax.Servlet.Filter, override the appropriate method, the code is as follows:

public class SetCharacterEncodingFilter implements Filter (

protected String encoding;

public SetCharacterEncodingFilter () (

super ();

this.encoding = "GB2312";

)

public void destroy () (

)

public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException (

try

(

request.setCharacterEncoding (this.encoding);

)

catch (UnsupportedEncodingException e)

(

throw new ServletException ( "Can't set incoming encoding to" + this.encoding);

)

chain.doFilter (request, response);

)

public void init (FilterConfig filterconfig) throws ServletException (

this.encoding = filterconfig.getInitParameter ( "encoding");

)

)

9, write web.xml file

In the web.xml in the project need to run the configuration file described in a certain order clear, which is located Webroot / WEB-INF directory, the code is as follows:

<? xml version = "1.0" encoding = "UTF-8"?>

<web-app version = "2.4"

xmlns = "http://java.sun.com/xml/ns/j2ee"

xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"

xsi: schemaLocation = "http://java.sun.com/xml/ns/j2ee

http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd ">

<context-param>

<param-name> contextConfigLocation </ param-name>

<param-value> / WEB-INF/classes/applicationContext.xml </ param-value>

</ context-param>

<filter>

<filter-name> struts </ filter-name>

<filter-class>

com.filter.NewFilterDispatcher

</ filter-class>

<init-param>

<param-name> encoding </ param-name>

<param-value> GB2312 </ param-value>

</ init-param>

</ filter>

<filter-mapping>

<filter-name> struts </ filter-name>

<url-pattern> / * </ url-pattern>

</ filter-mapping>

<filter>

<filter-name> encodingFilter </ filter-name>

<filter-class> org.springframework.web.filter.CharacterEncodingFilter

</ filter-class>

<init-param>

<param-name> encoding </ param-name>

<param-value> GB2312 </ param-value>

</ init-param>

</ filter>

<filter-mapping>

<filter-name> encodingFilter </ filter-name>

<url-pattern> / * </ url-pattern>

</ filter-mapping>

<filter>

<filter-name> CharacterEncoding </ filter-name>

<filter-class> com.filter.SetCharacterEncodingFilter </ filter-class>

<init-param>

<param-name> encoding </ param-name>

<param-value> GB2312 </ param-value>

</ init-param>

</ filter>

<filter-mapping>

<filter-name> CharacterEncoding </ filter-name>

<url-pattern> / * </ url-pattern>

</ filter-mapping>

<listener>

<listener-class> org.springframework.web.context.ContextLoaderListener </ listener-class>

</ listener>

<! - Servlet>

<servlet-name> SpringContextServlet </ servlet-name>

<servlet-class>

org.springframework.web.context.ContextLoaderServlet

</ servlet-class>

<load-on-startup> 2 </ load-on-startup>

</ servlet ->

<welcome-file-list>

<welcome-file> index.jsp </ welcome-file>

</ welcome-file-list>

</ web-app>

Note that one section is a comment, because Struts2 needs Spring's listener to initialize Context, rather than SpringContextServlet. But the later version may require Servlet, so it is not removed.

10, resulting in persistent classes

Switch to the database explore view, right-click the users table "Hibrnate Reverse Engineering"

Figure 5-21 ready to produce O / R Mapping

The following pop-up window, pay attention to the generated mapping file specifies the location of the com.hibernate package. Also note that "Base Persistence Class" option BaseObject class.

Figure 5-22 Set O / R mapping to be the result of

Click "next", the pop-up dialog box to select the primary key is generated attention to the type of "identity", different database primary key generation method is not the same, because here are using a SQL Server, so I chose to use the "identity".

Figure 5-23 Set ID method created

Direct Point "Finish" can be. The view from the package can be seen in more than three com.hibernate package file, which is the Users.hbm.xml mapping file, the other two are mapped classes. Also note that in the Spring configuration file named applicationContext.xml in the sessionFactory the bean has been added to relevant content on the mapping file.

11, increasing transaction management configuration

In the applicationContext.xml, in the id, "sessionFactory" the Bean after the increase:

<bean>

<property name="sessionFactory"> <ref local="sessionFactory"/> </ property>

</ bean>

<bean lazy-init="true" abstract="true">

<property name="transactionManager"> <ref bean="transactionManager"/> </ property>

<property name="transactionAttributes">

<props>

<prop key="*"> PROPAGATION_REQUIRED </ prop>

<! - Prop key = "get *"> PROPAGATION_REQUIRED, readOnly </ prop ->

</ props>

</ property>

</ bean>

12, establishing service layer code is

Right-click com.service package, select new-> Interface, named UserService, inside the definition of two methods, add the following code:

package com.service;

import java.util.List;

import org.springframework.dao.DataAccessException;

public interface UserService (

public abstract boolean validate (String username, String password) throws DataAccessException;

public abstract List showAllUsers () throws DataAccessException;

)

Then com.service.impl bag to create a new class, called UserServiceImpl achieve UserService interface and inherit BaseService class.

In the class to implement interface methods defined in the code is as follows:

public class UserServiceImpl extends BaseService implements UserService (

public boolean validate (String username, String password)

throws DataAccessException (

/ / TODO Auto-generated method stub

String hql = "from com.hibernate.Users where username =? And password =?";

if (getFirstObject (hql, new String [] (username, password))! = null)

return true;

else

return false;

)

public List showAllUsers () throws DataAccessException (

/ / TODO Auto-generated method stub

return getHibernateTemplate (). find ( "from com.hibernate.Users");

)

At the same time in the Spring configuration file to add the following configuration item applicationContext.xml

<bean parent="baseProxy">

<property name="target"> <ref local="userServiceImpl" /> </ property>

</ bean>

<bean autowire="byName" />

13, configure Struts2 Action

(1) Write struts.properties file

struts.properties content of the document:

# # # START SNIPPET: complete_file

# # # Struts default properties

# # # (can be overridden by a struts.properties file in the root of the classpath)

# # #

# # # Specifies the Configuration used to configure Struts

# # # One could extend org.apache.struts2.config.Configuration

# # # To build one's customize way of getting the configurations parameters into Struts

# Struts.configuration = org.apache.struts2.config.DefaultConfiguration

# # # This can be used to set your default locale and encoding scheme

struts.locale = zh_CN

struts.i18n.encoding = GB2312

# # # If specified, the default object factory can be overridden here

# # # Note: short-hand notation is supported in some cases, such as "spring"

# # # Alternatively, you can provide a com.opensymphony.xwork2.ObjectFactory subclass name here

struts.objectFactory = spring

# # # Specifies the autoWiring logic when using the SpringObjectFactory.

# # # Valid values are: name, type, auto, and constructor (name is the default)

struts.objectFactory.spring.autoWire = name

# # # Indicates to the struts-spring integration if Class instances should be cached

# # # This should, until a future Spring release makes it possible, be left as true

# # # Unless you know exactly what you are doing!

# # # Valid values are: true, false (true is the default)

struts.objectFactory.spring.useClassCache = true

# # # If specified, the default object type determiner can be overridden here

# # # Note: short-hand notation is supported in some cases, such as "tiger" or "notiger"

# # # Alternatively, you can provide a com.opensymphony.xwork2.util.ObjectTypeDeterminer implementation name here

# # # Note: if you have the xwork-tiger.jar within your classpath, GenericsObjectTypeDeterminer is used by default

# # # To disable tiger support use the "notiger" property value here.

# struts.objectTypeDeterminer = tiger

# struts.objectTypeDeterminer = notiger

# # # Parser to handle HTTP POST requests, encoded using the MIME-type multipart / form-data

# Struts.multipart.parser = cos

# Struts.multipart.parser = pell

struts.multipart.parser = jakarta

# Uses javax.servlet.context.tempdir by default

struts.multipart.saveDir =

struts.multipart.maxSize = 2097152

# # # Load custom property files (does not override struts.properties!)

# Struts.custom.properties = application, org/apache/struts2/extension/custom

# # # How request URLs are mapped to and from actions

struts.mapper.class = org.apache.struts2.dispatcher.mapper.DefaultActionMapper

# # # Used by the DefaultActionMapper

# # # You may provide a comma separated list, eg struts.action.extension = action, jnlp, do

struts.action.extension = action

# # # Used by FilterDispatcher

# # # If true then Struts serves static content from inside its jar.

# # # If false then the static content must be available at <context_path> / struts

struts.serve.static = true

# # # Used by FilterDispatcher

# # # This is good for development where one wants changes to the static content be

# # # Fetch on each request.

# # # NOTE: This will only have effect if struts.serve.static = true

# # # If true -> Struts will write out header for static contents such that they will

# # # Be cached by web browsers (using Date, Cache-Content, Pragma, Expires)

# # # Headers).

# # # If false -> Struts will write out header for static contents such that they are

# # # NOT to be cached by web browser (using Cache-Content, Pragma, Expires

# # # Headers)

struts.serve.static.browserCache = true

# # # Set this to false if you wish to disable implicit dynamic method invocation

# # # Via the URL request. This includes URLs like foo! Bar.action, as well as params

# # # Like method: bar (but not action: foo).

# # # An alternative to implicit dynamic method invocation is to use wildcard

# # # Mappings, such as <action name="*/*" method="{2}">

struts.enable.DynamicMethodInvocation = true

# # # Use alternative syntax that requires% () in most places

# # # To evaluate expressions for String attributes for tags

struts.tag.altSyntax = true

# # # When set to true, Struts will act much more friendly for developers. This

# # # Includes:

# # # - Struts.i18n.reload = true

# # # - Struts.configuration.xml.reload = true

# # # - Raising various debug or ignorable problems to errors

# # # For example: normally a request to foo.action? SomeUnknownField = true should

# # # Be ignored (given that any value can come from the web and it

# # # Should not be trusted). However, during development, it may be

# # # Useful to know when these errors are happening and be told of

# # # Them right away.

struts.devMode = false

# # # When set to true, resource bundles will be reloaded on _every_ request.

# # # This is good during development, but should never be used in production

struts.i18n.reload = false

# # # Standard UI theme

# # # Change this to reflect which path should be used for JSP control tag templates by default

struts.ui.theme = xhtml

struts.ui.templateDir = template

# sets the default template type. Either ftl, vm, or jsp

struts.ui.templateSuffix = ftl

# # # Configuration reloading

# # # This will cause the configuration to reload struts.xml when it is changed

struts.configuration.xml.reload = true

# # # Location of velocity.properties file. Defaults to velocity.properties

# Struts.velocity.configfile = velocity.properties

# # # Comma separated list of VelocityContext classnames to chain to the StrutsVelocityContext

# Struts.velocity.contexts =

# # # Used to build URLs, such as the UrlTag

struts.url.http.port = 80

struts.url.https.port = 443

# # # Possible values are: none, get or all

struts.url.includeParams = get

# # # Load custom default resource bundles

# Struts.custom.i18n.resources = testmessages, testmessages2

# # # Workaround for some app servers that don't handle HttpServletRequest.getParameterMap ()

# # # Often used for WebLogic, Orion, and OC4J

struts.dispatcher.parametersWorkaround = false

# # # Configure the Freemarker Manager class to be used

# # # Allows user to plug-in customised Freemarker Manager if necessary

# # # MUST extends off org.apache.struts2.views.freemarker.FreemarkerManager

# struts.freemarker.manager.classname = org.apache.struts2.views.freemarker.FreemarkerManager

# # # See the StrutsBeanWrapper javadocs for more information

struts.freemarker.wrapper.altMap = true

# # # Configure the XSLTResult class to use stylesheet caching.

# # # Set to true for developers and false for production.

struts.xslt.nocache = false

# # # A list of configuration files automatically loaded by Struts

struts.configuration.files = struts-default.xml, struts-plugin.xml, struts.xml

# # # END SNIPPET: complete_file

(2) spring2.0 Integration

In the applicationContext.xml named dataSource before the addition of the following elements of the Bean

<bean init-method="initObjectFactory" />
(3) write action file

The com.action package to add a class called UserManage, so that it inherits BaseAction class. Its code is as follows:

package com.action;

import com.service.UserService;

import com.util.BaseAction;

public class UserManage extends BaseAction (

private UserService userService;

private String message;

private String username;

private String password;

private List userList;

public String checkUser () throws Exception (

/ / TODO Auto-generated method stub

if (username == null) username = "";

if (password == null) password = "";

if (userService.validate (username, password)) (

setMessage ( "successful login!");

return SUCCESS;

)

else (

setMessage ( "Login Failed!");

return INPUT;

)

)

public String showAll () throws Exception (

setUserList (userService.showAllUsers ());

return SUCCESS;

) Then generate a member variable of the get, set methods, as shown below:

Figure 5-24 generation get, set methods

In the following dialog box pops up to select all of the member variables, point "OK" can be.

ApplicationContext.xml and then add the following:

<bean scope="prototype" autowire="byName" />

An increase in the Webroot directory next.jsp page, after the jump as the correct login page.

In the src directory to increase struts.xml file, the code is as follows:

<! DOCTYPE struts PUBLIC

"- / / Apache Software Foundation / / DTD Struts Configuration 2.0 / / EN"

"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<package name="default" extends="struts-default">

<action name="Login" method="checkUser">

<result name="success" type="chain"> ShowAllUser </ result>

<result name="input"> / index.jsp </ result>

</ action>

<action name="ShowAllUser" method="showAll">

<result name="success"> / next.jsp </ result>

</ action>

</ package>

</ struts>

Modify the index.jsp, add a form in which the specific code is as follows:

<% @ Page language = "java" import = "java.util .*" pageEncoding = "GB2312"%>

<% @ Taglib prefix = "s" uri = "/ struts-tags"%>

"%

String path = request.getContextPath ();

String basePath = request.getScheme ()+"://"+ request.getServerName ()+":"+ request.getServerPort () + path +"/";

% "

<! DOCTYPE HTML PUBLIC "- / / W3C / / DTD HTML 4.01 Transitional / / EN">

<html>

<head>

<base href ="<%= basePath%> ">

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

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

"! --

<link rel="stylesheet" type="text/css" href="styles.css">

- "

</ head>

<body>

<h2 align="center"> Login </ h2>

<br>

<form name="loginForm" action="Login.action" method="post">

<div align="center">

User Name <input type="text" name="username" /> <br>

Password <input type="password" name="password" /> <br>

<input type="submit" value="Submit" /> <input type="reset" value="Reset" /> <br>

<p align="center"> <font color="red"> <s:property value="message" /> </ font> </ p>

<p> </ p>

</ div>

</ form>

</ body>

</ html>

Note: One with <s:> label is Struts2.0 label, if you want to reference the label, need to add in the page head:

<% @ Taglib prefix = "s" uri = "/ struts-tags"%>

Next.jsp reads as follows:

<% @ Page language = "java" import = "java.util .*" pageEncoding = "GB2312"%>

<% @ Taglib prefix = "s" uri = "/ struts-tags"%>

"%

String path = request.getContextPath ();

String basePath = request.getScheme ()+"://"+ request.getServerName ()+":"+ request.getServerPort () + path +"/";

% "

<! DOCTYPE HTML PUBLIC "- / / W3C / / DTD HTML 4.01 Transitional / / EN">

<html>

<head>

<base href ="<%= basePath%> ">

<title> My JSP 'next.jsp' starting page </ title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

"! --

<link rel="stylesheet" type="text/css" href="styles.css">

- "

</ head>

<body>

<p>

Welcome, <s:property value="username" />

</ p>

<div align="center">

<h3> User Information list </ h3> <br>

<table border="1">

<tr>

<th> ID </ th>

<th> User Name </ th>

<th> Password </ th>

</ tr>

<s:iterator value="userList">

<tr>

<td> <s:property value="id" /> </ td>

<td> <s:property value="username" /> </ td>

<td> <s:property value="password" /> </ td>

</ tr>

</ s: iterator>

</ table>

</ div>

</ body>

</ html>

Note: At this point a complete applicationContext.xml as follows:

<? xml version = "1.0" encoding = "UTF-8"?>

<beans

xmlns = "http://www.springframework.org/schema/beans"

xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"

xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<bean init-method="initObjectFactory" />

<bean

class = "org.apache.commons.dbcp.BasicDataSource">

<property name="driverClassName">

<value> net.sourceforge.jtds.jdbc.Driver </ value>

</ property>

<property name="url">

<value> jdbc: jtds: sqlserver: / / localhost: 1433/test </ value>

</ property>

<property name="username">

<value> sa </ value>

</ property>

<property name="password">

<value> sa </ value>

</ property>

</ bean>

<bean

class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<property name="dataSource">

<ref bean="dataSource" />

</ property>

<property name="hibernateProperties">

<props>

<prop key="hibernate.dialect">

org.hibernate.dialect.SQLServerDialect

</ prop>

</ props>

</ property>

<property name="mappingResources">

<list>

<value> com / hibernate / Users.hbm.xml </ value> </ list>

</ property>

</ bean>

<! - Transaction Manage Bean ->

<bean>

<property name="sessionFactory"> <ref local="sessionFactory"/> </ property>

</ bean>

<bean lazy-init="true" abstract="true">

<property name="transactionManager"> <ref bean="transactionManager"/> </ property>

<property name="transactionAttributes">

<props>

<prop key="*"> PROPAGATION_REQUIRED </ prop>

<! - Prop key = "get *"> PROPAGATION_REQUIRED, readOnly </ prop ->

</ props>

</ property>

</ bean>

<! - Business Logic Bean ->

<bean parent="baseProxy">

<property name="target"> <ref local="userServiceImpl" /> </ property>

</ bean>

<bean autowire="byName" />

<! - Struts2 Action Bean ->

<bean scope="prototype" autowire="byName">

</ bean>

</ beans>

Released running

Use the users table in the user information registry, if the login is successful, jump to next.jsp page, and displays all user information.

This article comes from CSDN blog, reproduced please indicate source: http://blog.csdn.net/haoxing272/archive/2007/11/23/1899628.aspx
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb
Tags:

Related Posts of struts2 + hibernate3.2 + spring2.0 instance configuration + Getting Started

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries