Hibernate + Struts application's JavaWebStudio 2005 fast, visual development

xiaoxiao2021-03-06  40

Rel = "file-list" href = "http://www.javawebstudio.com/html/j2005/j05_new_7.files/filelist.xml">

How to implement hibernate_struts

Hibernate Struts application's JavaWebStudio 2005 fast, visual development

Struts Chinese Forum: http://www.javawebstudio.com/ JavaWebStudio 2005 Download Address: http://www.javawebstudio.com/bbs/dispbbs.asp? BoardId = 5 & ID = 3 & Page = 1

[aims]

The goal of this example is to implement a simple Struts database application. Its function is to read data from SQL Server 2000 and displayed in the output page in the form of a table.

Define a field named "Test" table:

Enter some test data:

[effect]

(1) All shows:

Enter the page:

Output page:

(2) Query display:

[background knowledge]

[step]

1. Open the Visual Struts development environment:

Start JavaWebStudio.exe files from the desktop JavaWebstudio fast or bin directory launched the Visual Struts development environment of JavaWebStudio.

2. Create an "empty hibernate_struts project template" application:

Select the menu "File" - "New" - "New Project", pop up the new project dialog, as shown in Figure 3-1:

Select "Empty Struts Database Application Template" in the dialog box, enter "MyHibernate", Package, Package (Path "in the project name, using the default value, and certainly can be changed as needed. Finally, click the "OK" button to complete the establishment of the new project.

From the file manager, you can see that the file structure of the MYHIBERNATE project is as follows:

In the MyHibernate project root directory contains four subdirectories and two files, this is the standard structure of the JavaWebstudio project, it is best not to change their default names, otherwise there will be problems.

3. Use the Struts Database Application File Wizard to establish a new application:

In the JavaWebStudio file manager, click the right mouse button. In the pop-up menu, select "Hibernate" - "Hibernate_Struts File Wizard" into the Struts File Wizard dialog, or select the Menu File Wizard - "Hibernate_Struts File Wizard" Enter the Hibernate File Wizard Dialog. As shown below:

(1) Enter the file name:

(2) Import the field information of the SQL statement and the data table from the data source (field name, and field type):

(3) Select the desired table "Test" from the data table.

It is important to note that the "Field information of the SQL statement and data table from the data source" and "Select the table from the data table" is merely generated to automatically generate SQL statements and read field information, here Complete can be manually entered directly, unrelated to the configuration of the database connection pool, below, and then configure the database connection pool separately.

DAO file, enter the JSP file, an actionform file, Action file, etc. Select by default, mainly to set up a jspout file, let it automatically pagin, 4 records per page, select delete, edit, link, and add new records.

Next, configure the database connection pool, and other property pages can be used by default, and the data connection configuration property page is directly turned directly. (4) Configure the database connection pool:

It is important to pay special attention to the Hibernate's database connection pool configuration file is hibernate.properties, and the DIALECT class name is org.hibernate.diaalect.sqlserverDiact.

4, project file structure

Project catalog structure analysis See "How to achieve the simplest struts program", this Hibernate file wizard automatically generates eight files, where the web directory is input, output two JSP files, the SRC directory is a Java file. All program source code is automatically generated by the file wizard except that the file name is automatically generated, and all configurations are also automatically completed.

Refresh the JavaWebStudio file manager, then the two files are automatically generated in the web directory, named.jsp.jsp, testinsert.jsp, and test.jsp.jsp, are query conditions Enter JSP files, new records Add JSP files, new records And the table output JSP file; five files automatically generated in the src / emptyprj directory, which are TestAction.java and Testform.java, the former is an action file, the latter is a formaction file; there is a database operation file Test.java and TestDao .java, the former is used to save the bean recorded by the data sheet, the latter is the database operation DAO file; special attention is to note that there is another XML file, which is Test.hbm.xml, which is used for the Hibernate object and the database mapping.

TEST.JSP file:

TestInsert.jsp file:

TESTOUT.JSP file:

5, compile, start the server, run:

Compile the project and start the server by the button on the toolbar, then turn Test.jsp and run Test.jsp through the "Run" button on the toolbar.

Here, the mode of operation is used in the commissioning state:

(1) Show debugging tools:

Note: Single-step execution can track the original function execution; single procedure execution according to statement tracking, generally selecting a single procedure execution.

(2) Select "Compilation" in the debug state:

Output in the output column The following prompt information:

C: / Documents and Settings / Administrator / Desktop> F:

F: /> cd f: / javawebstudio / javawebstudioWorkdir / MyHibernate

F: / javawebstudio / javawebstudioWorkdir / MyHibernate> Ant -BuildFile Build.xml

Buildfile: build.xml

Prepare:

[COPY] COPYING 1 File to f: /javawebstudio/jakarta-tomcat-5.5.4/webapps/myhibernate/web-inf/classes

Compile:

[javac] compiling 5 Source Files to f: /javawebstudio/jakarta-tomcat-5.5.4/webapps/myhibernate/web-inf/classes

[javac] f: /javawebstudio/javawebstudioWorkDir/myHibernate/src/emptyprj/testaction.java: 68: setUserid (int) in emptyprj.test cannot beapplied to (java.lang.string)

[javac] m_test.setUserid (expression); [javac] ^

[javac] 1 Error

Build Failed

F: /javawebstudio/javawebstudioWorkDir/myHibernate/build.xml: 34: compile failed; see the compiler error output for details.

Total Time: 9 seconds

An error occurs because we set up userid as an integer type, and the expression is a string type, so you want to modify the testAction.java file:

Package EmptyPRJ;

Import emptyprj.testdao;

Import java.lang.reflect.InvocationTargeTexception;

Import java.util.locale;

Import javax.servlet.servletException;

Import javax.servlet.http.httpsession;

Import javax.servlet.http.httpservletRequest;

Import javax.servlet.http.httpservletResponse;

Import org.apache.commons.beanutils.propertyUtils;

Import org.apache.commons.logging.log;

Import org.apache.commons.logging.logfactory;

Import org.apache.struts.Action.action;

Import org.apache.struts.Action.Actionerror;

Import org.apache.struts.Action.Actionerro;

Import org.apache.struts.Action.actionform;

Import org.apache.struts.Action.actionForward;

Import org.apache.struts.action.actionmapping;

Import org.apache.struts.action.ActionServlet;

Import org.apache.struts.util.moduleException;

Import org.apache.struts.util.MessageResources;

Import java.io.ioException;

Import java.sql.connection;

Import java.sql.sqlexception;

Import java.util.collection;

Public Final Class TestAction Extends Action

{

// Variable definitions:

Private log log = logfactory.getlog ("org.apache.struts.Webapp.example");

Public TestAction () {

}

// Function definition:

Public ActionForward Execute (ActionMapping Mapping,

Actionform Form,

HTTPSERVLETREQUEST REQUEST,

Httpservletresponse response

Throws Exception

{

// Extract Attributes and Parameters WE WILL NEED

Locale locale = getLocale (request); MessageResources message = getResources (Request);

HttpSession session = request.getations ();

Testform m_testform = (testform) form;

TestDao M_TestDao = TestDao.getInstance (); // Defines Hibernate__dao objects to implement various operations of the database.

String action = Request.getParameter ("action"); // action type

String Search = Request.getParameter ("Search"); // Database Find Mode

String Expression = Request.getParameter ("Expression"); // Parameter, here to save record (row) ID data

IF (Action == Null) action = "find";

IF (search == null) Search = "unsearch";

IF (Expression == NULL) Expression = "";

Expression = toCHINESE (Expression); // Processing Chinese issues, implementing coding conversion

/

IF ("delete" .equals (action) // Delete record operation

{

Test m_test = new test ();

//

m_test.setUserid (Expression);

//

m_testdao.removeid (m_test);

}

IF ("Update" .Equals (action) || "insert" .Equals (action)) // update, add a record operation

{

Test m_test = new test ();

//

m_test.setUserid (m_testform.getuserid ());

m_test.setusername (m_testform.getuserName ());

m_test.setpassword (m_testform.getpassword ());

m_test.setrole (m_testform.getrole ());

//

IF ("Update" .Equals (action) // Call DAO object update record

m_testdao.update (m_test, expression);

IF ("INSERT" .Equals (action) // Call DAO object Add Record

m_testdao.create (m_test);

}

/// HQL_ Find Database

String SQL = "from EmptyPrj.test Test";

SQL character processing, mainly to join query conditions, if all displayed, you can delete this part of the code.

IF ("Search" .equals (search))

{

String selectsql;

//

SQL = "Where";

SQL = "UserID";

SQL = "=";

IF ("NULL" .Equals (expression) || "" "" "". Equals (express)) {

SQL = m_testform .getuserid ();

}

Else

{

SQL = Expression;

}

SQL = "";

//

}

//

m_testdao.setlength (4); // Set the number of records per page

INT ipage; // current page

Try

{

String Page = Request.getParameter ("Page"); // Pedestrian Parameters, read the current page of the request

ipage = java.lang.integer.parseint (page, 10);

}

Catch (Exception E)

{

ipage = m_testform.getpage ();

}

IPAGE = 1;

Collection col = m_testdao.findsql ("SELECT TEST" SQL, "Select Count" SQL, IPAGE); // Query data via DAO object

Request.setttribute ("Test", COL); // Save Data

String PageStr = m_testdao.getpagestr (ipage); // Page string, pagination content

String s_find, str;

IF (! "Search" .Equals (search) // lookup and all display two different operations, which are different, which is handled here. If all it is displayed, remove "Search = Search &"

{

s_find = "Search = SEARCH &";

While (PageStr.Indexof (s_find)! = - 1)

{

Str = pageStr.Substring (0, PageStr.Indexof (s_find));

Str = pageStr.substring (PageStr.Indexof (s_find) s_find.length (), pageStr.Length ());

PageStr = STR;

}

}

m_testform.setpagestr (PageStr);

m_testform.setAction;

Request.setttribute ("Testform", M_TestForm);

//

Return mapping.findforward ("Success");

}

Public String tochinese (String SS) {

// Problem in Chinese issues, implement coding conversion

IF (ss! = null) {

Try {

String temp_p = ss;

BYTE [] TEMP_T = Temp_p.getbytes ("ISO8859-1");

ss = new string (TEMP_T);

}

Catch (Exception E) {

System.err.Println ("ToChinese Exception:" E.getMessage ());

System.err.Println ("THE STRING IS:" SS);

}

}

Return ss;

}

}

Put the above TestAction.java files 68:

M_test.setUserid (Expression); Modified to:

m_test.setUserid (java.lang.integer.Parseint (Expression, 10));

(3) Start the server in the debug state:

Output in the output column The following prompt information:

C: / Documents and Settings / Administrator / Desktop> F:

F: /> cd f: /javawebstudio//jakarta-tomcat-5.5.4/bin/

F: /javawebstudio/jakarta-tomcat-5.5.4/bin> Startup_jpda.bat

Using catalina_base: f: /javawebstudio/jakarta-tomcat-5.5.4

Using catalina_home: f: /javawebstudio/jakarta-tomcat-5.5.4

Using catalina_tmpdir: f: /javawebstudio/jakarta-tomcat-5.5.4/temp

USING JAVA_HOME: F: / JavaWebstudio / JDK

The server is successful.

(4) Start the debug status:

Output in the output column The following prompt information:

The command will be executed below is: jdb -attach jdbconn

Set uncaught java.lang.throwable

Set deferred uncaught java.lang.throwable

Initializing JDB ...

>

(5) Set breakpoints:

Open the TestAction file, set two breakpoints in 127, 136, respectively. Output in the output column The following prompt information:

The command will be executed below is: jdb -attach jdbconn

Set uncaught java.lang.throwable

Set deferred uncaught java.lang.throwable

Initializing JDB ...

> The input parameters that will be performed below are: stop at EmptyPRJ.TestAction: 127

Deferring BreakPoint EmptyPrj.testaction: 127.

IT Will Be set after the class is loading.

> The input parameters that will be executed are: Stop at EmptyPrj.TestAction: 136

Deferring BreakPoint EmptyPrj.testaction: 136.

IT Will Be set after the class is loading.

>

(6) Open Test.jsp files and run:

operation result:

Try all the display function, click the "All Display" button, if shown below:

It can be seen that running to the breakpoint 128, then click on the single procedure execution in the debug toolbar. At this time, the variable value can be seen from the output prompt bar:

HTTP-8080-Processor25 [1] The input parameters will be performed below: locals

The input parameters that will be executed are: Next

Method Arguments:

Mapping = instance of org.apache.struts.action.actionmapping (id = 1701)

Form = instance of emptyprj.testform (id = 1702)

Request = instance of org.apache.catalina.connector.RequestFacade (id = 1703) response = instance of org.apache.catalina.connector.responseFacade (ID = 1704)

Local Variables:

Locale = instance of java.util.locale (id = 1705)

Messages = instance of org.apache.struts.util.propertyMessageResources (id = 1706)

Session = instance of org.apache.catalina.Session.standardSessionFacade (ID = 1707)

m_testform = instance of emptyprj.testform (id = 1702)

m_testdao = instance of emptyprj.testdao (id = 1708)

Action = "Search"

Search = "unsearch"

Expression = "NULL"

SQL = "from EMPTYPRJ.TEST TEST"

IPAGE = 1

HTTP-8080-Processor25 [1]>

Step Completed: "Thread = HTTP-8080-Processor25", EMPTYPRJ.TESTACTION.EXECUTE (), line = 128 bci = 509

HTTP-8080-Processor25 [1]

Try a single step now:

HTTP-8080-Processor25 [1] The input parameters will be performed below: locals

The input parameters that will be performed below are: STEP

Method Arguments:

Mapping = instance of org.apache.struts.action.actionmapping (ID = 1752)

Form = instance of emptyprj.testform (id = 1753)

Request = instance of org.apache.catalina.connector.RequestFacade (ID = 1754)

Response = instance of org.apache.catalina.connector.responsefacade (ID = 1755)

Local Variables:

Locale = instance of java.util.locale (id = 1756)

Messages = instance of org.apache.struts.util.propertyMessageResources (id = 1757)

Session = instance of org.apache.catalina.Session.standardSessionFacade (id = 1758)

m_testform = instance of emptyprj.testform (id = 1753)

m_testdao = instance of emptyprj.testdao (id = 1759)

Action = "Search"

Search = "unsearch"

Expression = "null" sql = "from emptyprj.test test"

IPAGE = 1

Col = instance of java.util.ArrayList (ID = 2326)

HTTP-8080-Processor25 [1]>

Step completed: "thread = http-8080-processor25", org.apache.catalina.connector.RequestFacade.setttribute (), line = 346 bci = 0

HTTP-8080-Processor25 [1]

At this time, it was executed to org.apache.catalina.connector.RequestFacade.setttribute (), the 246th line of the RequestFacade.java file.

Click "Perform to the next breakpoint" in the debug toolbar, execute it 137.

Then click on "Perform to the next breakpoint" in the debug toolbar, and output the last result, as shown below.

Through the above steps, the estimated target function is achieved.

[Program source code]

ConnectionFactory.java file:

Package EmptyPRJ;

Import org.hibernate.hibernateException;

Import org.hibernate.mappingexception;

Import Org.Hibernate.Session;

Import Org.Hibernate.SessionFactory;

Import Org.Hibernate.cfg.configuration;

Public Class ConnectionFactory

{

PRIVATE Static ConnectionFactory Instance = NULL;

Private sessionFactory sessionFactory = NULL;

Private connectionFactory ()

{

Try

{

// Install the screen from here

Configuration CFG = New Configuration ().

AddClass (EMPTYPRJ.TEST.CLASS);

SESSIONFACTORY = cfg.buildsessionFactory ();

}

Catch (MAPPINGEXCEPTION E)

{

System.err.Println ("Mapping Exception" E.getMessage ());

Throw new runtimeException (e);

}

Catch (HibernateException E)

{

System.err.Println ("Hibernate Exception" E.GetMessage ());

Throw new runtimeException (e);

}

}

Public static synchronized connectionFactory getInstance ()

{

IF (instance == null)

{

Instance = new connectionFactory ();

}

Return Instance;

}

Public session getsession ()

{

Try

{

Session s = sessionFactory.openSession ();

Return S;

}

Catch (HibernateException E)

{

System.err.Println ("Hibernate Exception" E.GetMessage ()); Throw New RuntimeException (e);

}

}

}

Test.hbm.xml file:

"- // Hibernate / Hibernate mapping DTD 2.0 // en"

"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

Hibernate.properties database connection pool configuration file:

Hibernate.diaforct = org.hibernate.diaalect.sqlserverdiaforct

Hibernate.Connection.driver_class = com.microsoft.jdbc.sqlserver.sqlserverdriver

Hibernate.Connection.url = JDBC: Microsoft: SQLServer: // localhost: 1433; DatabaseName = EDB

Hibernate.dbcp.min_size = 5

Hibernate.dbcp.max_size = 20

Hibernate.dbcp.timeout = 1800

Hibernate.dbcp.max_statements = 50

Hibernate.Connection.userName = SA

Hibernate.connection.password = sa

///

Test.java file:

This defines a bean for saving data table data, its variables are completely corresponding to the fields of the database table, that is, the fields to find with the SQL statement in the Database Application File Wizard.

Package EmptyPRJ;

Import java.io.serializable;

Public Class Test Implements Serializable

{

PRIVATE STRING ROLE;

Private string password; private string username;

Private int userid;

// myfiledata;

Public int getUserid ()

{

Return (this.userid);

}

Public Void SetUserId (int UserID)

{

THIS.USERID = UserId;

}

Public string getUsername ()

{

Return (this.username);

}

Public void setusername (String Username)

{

THIS.USERNAME = UserName;

}

Public string getpassword ()

{

Return (this.password);

}

Public void setPassword (String Password)

{

this.password = password;

}

Public String getRole ()

{

Return (this.Role);

}

Public void setrole (String Role)

{

THIS.ROLE = Role;

}

}

TestDao.java file:

Here, a DAO class is defined to implement functions such as data plus, delete, update, add, and generate zone strings.

Package EmptyPRJ;

Import EmptyPrj.test;

Import org.hibernate.hibernateException;

Import org.hibernate.ObjectNotFoundException;

Import Org.Hibernate.Query;

Import Org.Hibernate.Session;

Import java.util.list;

Import java.util.iterator;

Public class testdao {

PRIVATE INT ROWCOUNT;

PRIVATE INT pageCOUNT;

PRIVATE INT Length;

PRIVATE STRING PAGESTR;

Public int getLength () {return (this.Length);

Public void setlength (int length) {this.Length = Length;}

Private static testdao instance = null;

Private testdao ()

{

}

Public static synchronized testdao getInstance ()

{

IF (instance == null)

{

Instance = new testdao ();

}

Return Instance;

}

Public Test Gettest (long id)

{

SESSION session = connectionFactory.getInstance (). Getsession ();

Try

{

Return (Test) session.load (TEST.CLASS, ID);

}

Catch (ObjectNOTFoundException Onfe)

{

Return NULL;

}

Catch (HibernateException E)

{

System.err.Println ("Hibernate Exception" E.GetMessage ());

Throw new runtimeException (e);

}

Finally

{

IF (session! = null) {

Try

{

session.close ();

}

Catch (HibernateException E)

{

System.err.Println ("Hibernate Exception" E.GetMessage ());

Throw new runtimeException (e);

}

}

}

}

Public void update (Test Test, String KeyID)

{

SESSION session = connectionFactory.getInstance (). Getsession ();

Try

{

Session.Update (TEST);

Session.flush ();

}

Catch (HibernateException E)

{

System.err.Println ("Hibernate Exception" E.GetMessage ());

Throw new runtimeException (e);

}

Finally

{

IF (session! = NULL)

{

Try

{

session.close ();

}

Catch (HibernateException E)

{

System.err.Println ("Hibernate Exception" E.GetMessage ());

Throw new runtimeException (e);

}

}

}

}

Public Void RemoveId (Test Test) {

SESSION session = connectionFactory.getInstance (). Getsession ();

Try

{

Session.delete (test);

Session.flush ();

}

Catch (HibernateException E)

{

System.err.Println ("Hibernate Exception" E.GetMessage ());

Throw new runtimeException (e);

}

Finally

{

IF (session! = NULL)

{

Try

{

session.close ();

}

Catch (HibernateException E)

{

System.err.Println ("Hibernate Exception" E.GetMessage ());

Throw new runtimeException (e);

}

}

}

}

Public List Findsql (String SQL, String Countsql, INT iPAge)

{

SESSION session = connectionFactory.getInstance (). Getsession ();

Try

{

// Extract the total number of records

Iterator Results = session.createQuery (countsql) .Ist ();

While (results.hasnext ()) {

// Object [] row = results.next ();

// rowcount = (integer) row [0];

Rowcount = (Integer) Results.next ();

}

// rowcount = 10;

INT offset = 1;

INT PAGESIZE = GetLength ();

IF (getLength () <1)

{

PageSize = rowcount;

PageCount = 1;

}

Else

{

PageCount = rowcount / getLength () ((RowCount% getLength ())> 0? 1: 0);

OFFSET = (ipage-1) * getLength () 1;

IF (Offset <1) OFFSET = 1;

IF (offset> rowcount) OFFSET = RowCount;

}

//Extract data

Query Query = session.createQuery (SQL);

Query.setFirstResult ((ipage-1) * getLength ());

Query.SetMaxResults (PageSize);

Return query.list ();

}

Catch (HibernateException E)

{

System.err.Println ("Hibernate Exception" E.GetMessage ());

Throw new runtimeException (e);

}

Finally

{

IF (session! = NULL)

{

Try

{

session.close ();

}

Catch (HibernateException E)

{

System.err.Println ("Hibernate Exception" E.GetMessage ());

Throw new runtimeException (e);

}

}

}

}

// Add a new record

Public Void Create (Test Test)

{

SESSION session = connectionFactory.getInstance (). Getsession ();

Try

{

Session.save (test);

Session.flush ();

}

Catch (HibernateException E)

{

System.err.Println ("Hibernate Exception" E.GetMessage ());

Throw new runtimeException (e);

}

Finally

{

IF (session! = NULL)

{

Try

{

session.close ();

}

Catch (HibernateException E)

{

System.err.Println ("Hibernate Exception" E.GetMessage ());

Throw new runtimeException (e);

}

}

}

}

// Sub-page string processing

Public String getpageStr (int ipage)

{

String strpage = ""

IF (getLength ()> 0)

{

STRPAGE = "Total";

StrPage = String.Valueof (Rowcount);

STRPAGE = "Strip record, total";

StrPage = String.Valueof (pagecount);

STRPAGE = "page, currently the first";

StrPage = String.Valueof (ipage);

STRPAGE = "page,";

INT iStart, IEND;

iStart = ipage-5;

IF (iStart <0) {iStart = 0;}

IEND = ISTART 10;

Ie (IEND> PageCount) {IEND = pageCount;} iStart = IEND-10;

IF (iStart <0) {iStart = 0;}

For (INT i = iStart; i

{

STRPAGE = "";

STRPAGE = String.Valueof (i 1);

STRPAGE = "";

STRPAGE = ""

}

}

this.pageStr = STRPAGE;

Return strpage;

}

}

TESTFORM.JAVA file:

Here, an ActionForm bean is defined, in addition to the full corresponding variable with the field of the database table (for example, the value of the variable of the corresponding fields can be used to save the corresponding fields, and the data of a row record is also included, and variables related to the paging For example, a variable such as a current page number, a page string.

Package EmptyPRJ;

Import javax.servlet.http.httpservletRequest;

Import org.apache.struts.Action.Actionerror;

Import org.apache.struts.Action.Actionerro;

Import org.apache.struts.Action.actionform;

Import org.apache.struts.action.actionmapping;

Public Final Class Testform Extends ActionForm

{

PRIVATE STRING ROLE;

PRIVATE STRING Password;

PRIVATE STRING UserName;

Private int userid;

Private int page;

PRIVATE STRING PAGESTR;

PRIVATE STRING ACTION;

PRIVATE STRINGMEBEANVARIABLE1

// myfiledata;

Public string getMyBeanvariable11 ()

{

Return (this.mybeanvariable1);

}

Public void setMyBeanvariable1 (String MyBeanvariable1)

{

THIS.MYBEANVARIABLE1 = MyBeanVariable1;

}

Public String getAction ()

{

Return (this.Action);

}

Public void setArt (String action)

{

THIS.ACTION = Action;

}

Public String getpageStr ()

{

Return (this.pageStr);

}

Public void setpagestr (String PageStr)

{

This.pageStr = PageStr;

}

Public int getpage ()

{

Return (this.page);

}

Public void setpage (int page)

{

THIS.PAGE = Page;

}

Public int getUserid () {

Return (this.userid);

}

Public Void SetUserId (int UserID)

{

THIS.USERID = UserId;

}

Public string getUsername ()

{

Return (this.username);

}

Public void setusername (String Username)

{

THIS.USERNAME = UserName;

}

Public string getpassword ()

{

Return (this.password);

}

Public void setPassword (String Password)

{

this.password = password;

}

Public String getRole ()

{

Return (this.Role);

}

Public void setrole (String Role)

{

THIS.ROLE = Role;

}

}

TestAction.java file:

Here, an Action class is defined to implement the forwarding function of the page, and additional operations of different request types are also included. The Action variable represents an operation type, which is equivalent to the event type. Through this variable, the "Event Drive" in the .NET is implemented.

Package EmptyPRJ;

Import emptyprj.testdao;

Import java.lang.reflect.InvocationTargeTexception;

Import java.util.locale;

Import javax.servlet.servletException;

Import javax.servlet.http.httpsession;

Import javax.servlet.http.httpservletRequest;

Import javax.servlet.http.httpservletResponse;

Import org.apache.commons.beanutils.propertyUtils;

Import org.apache.commons.logging.log;

Import org.apache.commons.logging.logfactory;

Import org.apache.struts.Action.action;

Import org.apache.struts.Action.Actionerror;

Import org.apache.struts.Action.Actionerro;

Import org.apache.struts.Action.actionform;

Import org.apache.struts.Action.actionForward;

Import org.apache.struts.action.actionmapping;

Import org.apache.struts.action.ActionServlet;

Import org.apache.struts.util.moduleException;

Import org.apache.struts.util.MessageResources;

Import java.io.ioException;

Import java.sql.connection;

Import java.sql.sqlexception;

Import java.util.collection;

Public Final Class TestAction Extends Action

{

// Variable definitions:

Private log log = logfactory.getlog ("org.apache.struts.WebApp.example"); public testression () {

}

// Function definition:

Public ActionForward Execute (ActionMapping Mapping,

Actionform Form,

HTTPSERVLETREQUEST REQUEST,

Httpservletresponse response

Throws Exception

{

// Extract Attributes and Parameters WE WILL NEED

Locale locale = getLocale (request);

MessageResources Messages = GetResources (Request);

HttpSession session = request.getations ();

Testform m_testform = (testform) form;

TestDao M_TestDao = TestDao.getInstance (); // Defines Hibernate__dao objects to implement various operations of the database.

String action = Request.getParameter ("action"); // action type

String Search = Request.getParameter ("Search"); // Database Find Mode

String Expression = Request.getParameter ("Expression"); // Parameter, here to save record (row) ID data

IF (Action == Null) action = "find";

IF (search == null) Search = "unsearch";

IF (Expression == NULL) Expression = "";

Expression = toCHINESE (Expression); // Processing Chinese issues, implementing coding conversion

/

IF ("delete" .equals (action) // Delete record operation

{

Test m_test = new test ();

//

m_test.setUserid (java.lang.integer.Valueof (Expression));

//

m_testdao.removeid (m_test);

}

IF ("Update" .Equals (action) || "insert" .Equals (action)) // update, add a record operation

{

Test m_test = new test ();

//

m_test.setUserid (m_testform.getuserid ());

m_test.setusername (m_testform.getuserName ());

m_test.setpassword (m_testform.getpassword ());

m_test.setrole (m_testform.getrole ());

//

IF ("Update" .Equals (action) // Call DAO object update record

m_testdao.update (m_test, expression);

IF ("INSERT" .Equals (action) // calls the DAO object Add Record m_testdao.create (m_test);

}

/// HQL_ Find Database

String SQL = "from EmptyPrj.test Test";

SQL character processing, mainly to join query conditions, if all displayed, you can delete this part of the code.

IF ("Search" .equals (search))

{

String selectsql;

//

SQL = "Where";

SQL = "UserID";

SQL = "=";

IF ("NULL" .Equals (expression) || "" "" "Equals (expression))

{

SQL = m_testform .getuserid ();

}

Else

{

SQL = Expression;

}

SQL = "";

//

}

//

m_testdao.setlength (4); // Set the number of records per page

INT ipage; // current page

Try

{

String Page = Request.getParameter ("Page"); // Pedestrian Parameters, read the current page of the request

ipage = java.lang.integer.parseint (page, 10);

}

Catch (Exception E)

{

ipage = m_testform.getpage ();

}

IPAGE = 1;

Collection col = m_testdao.findsql ("SELECT TEST" SQL, "Select Count" SQL, IPAGE); // Query data via DAO object

Request.setttribute ("Test", COL); // Save Data

String PageStr = m_testdao.getpagestr (ipage); // Page string, pagination content

IF (! "Search" .Equals (search) // lookup and all display two different operations, which are different, which is handled here. If all it is displayed, remove "Search = Search &"

{

PageStr = PageStr.ReplaceAll ("Search = Search &", ");

}

m_testform.setpagestr (PageStr);

m_testform.setAction;

Request.setttribute ("Testform", M_TestForm);

//

Return mapping.findforward ("Success");

}

Public String tochinese (String SS) {

// Problem in Chinese issues, implement coding conversion

IF (ss! = null) {

Try {

String temp_p = ss;

BYTE [] TEMP_T = Temp_p.getbytes ("ISO8859-1");

ss = new string (TEMP_T);

}

Catch (Exception E) {

System.err.println ("tochinese exception:" E.GetMessage ()); System.err.Println ("THE STRING IS: SS);

}

}

Return ss;

}

}

Web.xml file:

Here, in addition to the general Struts project configuration, it includes the configuration of the database connection pool, see the code of the dark body part.

PUBLIC "- // Sun microsystems, Inc.//dtd Web Application 2.2 // en"

"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

Action

org.apache.struts.Action.ActionServlet

1

Set Character Encoding

javawebstudio.struts_db.setcharacterencodingfilter

Encoding

GB2312

ignore

True

Set Character Encoding

Action

Action

*. do

Index.jsp

/ bean /Web-inf/struts-bean.tld

/ html

/web-inf/struts-html.tld

/ logic

/web-inf/struts-logic.tld

/ Template

/web-inf/struts-template.tld

Struts-config.xml file:

"- // Apache Software Foundation // DTD Struts Configuration 1.0 // En"

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

TYPE = "EMPTYPRJ.TESTFORM" />

TYPE = "EMPTYPRJ.TESTACTION"

Name = "testform"

Scope = "request"

INPUT = "/ Test.jsp">

转载请注明原文地址:https://www.9cbs.com/read-61474.html

New Post(0)