Use the Struts Action to increase, delete, change, check, check four operations via Hibernate

xiaoxiao2021-03-06  14

Foreword

After two articles, I believe that everyone has a preliminary understanding of Hibernate and Structs. In the environment of Hibernate Development Guide, we explained the use and related principles of the development of Hibernate and Struts, and wrote a simple Hibernate small example. In the Plugin to Struts of Hibernate Development Guide, we made some discussions in the initialization of Hibernate's sessionFactory, let everyone have a certain understanding of Struts's Plugin, and also understand the use model of Hibernate's sessionFactory. . This article will enter an example with strong operability, we use the Struts Action to increase, delete, change, and check four operations for the database via Hibernate. I hope that you will learn about the following knowledge through this article:

Struts Action and Development Method / Mode Hibernate's Database Increase, Delete, Change, Strike Struts Actionform Bean and Hibernate Maping Bean Internationalization The Internationalization of Struts Content This article will not involve Tag LIB in in-depth Struts The application, this content can be referred to the related documentation in the CHINESE STRUTS project of the technology sky.

First, please prepare a Web Project that contains Hibernate and Struts in accordance with the environment of the Hibernate Development Guide. The name of this Web Project is: dbwebdemo. You can download this empty Web Project from here, from this project to start the following work together. You can import this project from the ZIP file using the Eclipse import function.

Internationalized resource documents First we prepare an international resource document for the site. This resource file will be the language used by the site user. If Struts cannot find a corresponding language resource file, the default resource file will be used. Here we will build a TXT file first, write all Chinese information, and turn the TXT to the resource file used by Struts by a batch or shell script. This method is not very good, but I still don't know if there is a better international plugin in Eclipse. If you know, please tell me that I will add the associated use after I tried it.

Create a new folder in the Web-INF folder of the DBWebDemo project, named RES, and establish a new file in it, named res_zh.txt, and create a batch file name GenRES. Bat and a shell script file named genres.sh:

Here we give GenRes.bat content:

Native2ascii -Encoding GBK C: /.../ Web / Web-INF / RES / RES_ZH.TXT> C: /.../ dbwebdemo / src /.../ ApplicationResources_zh_cn.properties Please use your file path to replace The path before Workspace. If you have multiple language resource files, add multiple rows, prepare an Encode parameter for each file, and use the suffix of this language to name ApplicationResources.

To set the language used in the site, we use a servlet's filter to set the language used by the site, we can exist in the language used by the site, or exist in the session, and secure the user must use Chinese. Here we first fix the language used by the user is Chinese.

Establishing the STENCODEFILTER class First we create a new class name to setencodefilter:

The Filter interface will require the implementation class to implement the following methods:

Init: Initializing the work DOFILTER hours when Filter: Destroy Filter DoFilter: When there is a SERVET, the method of filtering, we don't write these three methods first, first configure this filter to the web application. Configuring a web application Using Filter First We open Web.xml, add Filter's declaration in the web-app content:

Set Web Application Character Encoding com.huangdong.dbwebdemo.SetEncodeFilter defaultencoding GB2312 Here we set the name of the filter and the class of specific implementation, and it is configured for this class. A parameter, the parameter name is defaultencoding, and its value is GB2312.

In order to use this filter, we also have to set the scope of the filter, add the following after the Filter declaration:

set web application character encoding / * We use / * this wildcard, meaning This filter will be used by all servlet requests. Next, let's write the implementation code of the Filter.

Implementation Language Content Filter The following is the code content:

Package com.huangdong.dbwebdemo;

Import java.io.ioException;

import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse;

/ ** * @Author hd * / public class setEncodefilter imports filter {

/ ** * Configuration information of this filter * / protected filterconfig filterconfig = NULL;

/ ** * System default language code * / protected string defaultencoding = null;

/ ** * initialize filter * / public void init (FilterConfig filterConfig) throws ServletException {this.filterConfig = filterConfig; // Get the system default language code this.defaultencoding = filterConfig.getInitParameter ( "defaultencoding");}

/ * ** filtration system requests, coding language setting request * / public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {request.setCharacterEncoding (selectEncoding (request)); chain.doFilter (request, response }

/ ** * Filter destroy * / public void destroy () {this.defaultencoding = null; this.filterconfig = null;}

/ ** * Select the language code used by this filter * @Param Request This time servlet request user request instance * @return Select language code * / protected string selectencoding (servletRequest request) {// can join from here SESSION is obtained in the requestion and obtain the encode // selected by the user from the session can also join the eNCode from Request to get the encode (this.defaultencoding);}}.

The code will not explain one by one, and the comments inside are also very clear.

Join Hibernate Configuration SessionFactory's initialization Struts plugin Specific addition method This is no longer explained, please refer to the description of the Plugin to Struts in the Hibernate Development Guide, here is just listing code:

Package com.huangdong.dbwebdemo;

Import javax.naming.context; import javax.naming.initialcontext; import javax.naming.namingexception; import javax.servlet.servletException;

Import net.sf.hibelption; import net.sf.hibernate.SessionFactory; import net.sf.hibernate.cfg.configuration;

Import org.apache.struts.action.actionServlet; import org.apache.struts.action.plugin; import org.apache.struts.config.Moduleconfig;

/ ** * @Author hd * / public class inithibernateplugin implements plugin {

/ ** * Plug-in container context instance * / private context ctx; / ** * Hibernate initializes good sessionFactory * / private meansionFactory sessionFactory;

/ * * Plug-in destruction method * / public void destroy () {if (ctx! = Null) {Try {// unbind jndi node ctx.unbind ("HibernateSessionFactory");} catch (namingexception e) {E.PrintStackTrace () }}} If (this.SessionFactory! = Null) {Try {// Close sessionFactory sessionFactory.Close ();} catch (hibernateException e) {E.PrintStackTrace ();} this.SessionFactory = null;}} / * * the method of plug-in initialization * / public void init (ActionServlet servlet, ModuleConfig config) throws ServletException {try {// Get an instance of SessionFactory this.sessionFactory = new Configuration () configure () buildSessionFactory ();..} catch (HibernateException ex) { throw new RuntimeException ( "Exception building SessionFactory:" ex.getMessage (), ex);} try {// container made context ctx = new InitialContext (); // sessionFactory bind to the JND tree ctx.bind ( "HibernateSessionFactory ", This.SessionFactory;} catch (namingexception ex) {throw new runtimeexception (" Exception Binding SessionFactory to JNDI: " EX.g EtMessage (), EX);}}

} The session gain tool class In addition to configuring the use of Plugin, we still use a class named DBUTIL class with the same function as HibernateUTilPlus, the following is its code:

Package com.huangdong.dbwebdemo;

Import javax.naming.context; import javax.naming.initialcontext; import javax.naming.namingexception;

Import net.sf.hibelnate.hibernateException; import net.sf.hibernate.Session; import net.sf.hibernate.SessionFactory;

/ ** * @Author hd * / public class dbutil {

PRIVATETIC sessionFactory sessionFactory = NULL; public static final threadlocal session = new threadlocal ();

public static Session currentSession () throws HibernateException {if (sessionFactory == null) {// If sessionFactory instance is null if acquired from the JNDI (getSystemSessionFactory () == false) {throw new HibernateException ( "Exception geting SessionFactory from JNDI" );}} Session s = (session) session.get (); if (s == null) {s = sessionFactory.opensesis (); session.set (s);} returnis} public static void CloseSession () THROWS HibernateException {session s = (session) session.get (); session.set (null); if (s! = null) s.close ();} private static boolean getSystemSessionFactory () {Try {// From JNDI to obtain a SessionFactory, if an error return false Context inttex = new InitialContext (); sessionFactory = (SessionFactory) inttex.lookup ( "HibernateSessionFactory");} catch (NamingException e) {return false;} return true;}} Hibernate configuration Don't forget that we have to write Hibernate's configuration files (here you can see the environment preparations in the Hibernate Development Guide):

net.sf.hibernate.dialect.Oracle9Dialect oracle.jdbc.driver.OracleDriver hd ABC JDBC: Oracle: Thin: @HDIBM: 1521: HDORC 1 25 50 30 true

Settings Data Table Subject Map The Oracle Database of We are still using a few articles. So the connection configuration is almost almost. Our increase, delete, change, and check or use the sysuser table, so use the original MAP file. The following is the source code for the SYSUser class:

Package com.huangdong.dbwebdemo.da;

Import java.io.serializable; import java.text.SIMPLEDATEFORMAT;

Import org.apache.commons.lang.builder.equalsbuilder; import org.apache.commons.lang.builder.hashcodebuilder; import org.apache.commons.lang.builder.tostringbuilder;

/ ** @Author Hibernate codeGenerator * / public class sysuser imports serializable {

/ ** iDentifier Field * / private string userid;

/ ** Persistent Field * / private string username

/ ** Persistent Field * / Private string UserPasword;

/ ** Nullable Persistent Field * / private java.util.calendar LastLogin

/ ** full constructor * / public SysUser (java.lang.String username, java.lang.String userpasword, java.util.Calendar lastlogin) {this.username = username; this.userpasword = userpasword; this.lastlogin = lastlogin; }

/ ** default constructor * / public sysuser () {}

/ ** minimal constructor * / public sysuser (java.lang.string username, java.lang.string userpasword) {this.username = username; this.userPasword = UserPasword;}

Public Java.lang.String getUserid () {return this.userid;}

Public void setuserid (java.lang.string userid) {this.userid = userid;}

Public java.lang.string getUsername () {return this.username;

Public void setusername (java.lang.string username) {this.username = usrname;}

Public java.lang.string getUserpasword () {return this.userpasword;}

Public void setUserPasword (java.lang.string userpasword) {this.userpasword = userpasword;}

Public java.util.calendar getlastlogin () {return this.lastlogin;

Public String getLastLoginstr () {SimpleDateFormat DF = New SimpleDateFormat ("YYYY-MM-DD HH: MM: SS"); return df.format (this.lastlogin);}

Public void setlastlogin (java.util.calendar LastLogin) {this.lastlogin = lastlogin;

Public string toString () {Return New TostringBuilder (this) .append ("userid", getUserid ()) .tostring ();

public boolean equals (Object other) {if return false ((other instanceof SysUser)!); SysUser castOther = (SysUser) other; return new EqualsBuilder () .append (this.getUserid (), castOther.getUserid ()) .isEquals ();

Public Int hashcode () {return new hashcodebuilder (). append (). tohashcode ();

} There is also a mapped XML file:

Creating Struts Action FormBean Creating FormBean is very simple in MyEclipse and Easy Struts, first opening Struts -config.xml file, select Form-Beans in the Outline, New: Then press the image in the form:

This way we have created a new Sysuserform class in a com.huangdong.dbwebdemo.form packet. Let's join the relevant properties and set geter and set, the following is the code:

Package com.huangdong.dbwebdemo.form;

Import org.apache.struts.action.validatorform;

Public class sysuserform extends validatorform {

/ / -------------------------------------------------------------------------------------------- --------- Instance variables / ** User ID, read-only * / private string userid;

/ ** User Name * / Private String UserName;

/ ** User Password * / Private string UserPasword;

/ ** Last login time * / private string lastlogin; public sysuserform () {super ();}

Public sysuserform (Sysuser sysuser) {this.newsysuserform (sysuser.getuserid (), sysuser.getuserPasword (), sysuser.getLastLoginstr ());}

Public sysuserform (String Userid, String User, String UserPasword, String LastLogin) {this.newsysuserform (userid, username, userpasword, lastlogin);} // -------------------------------------------------------------------------------------------- --------------------------------------METHODS / ** * is filled for a new Sysuserform data * / private void newSysuserForm (String userid, String username, String userpasword, String lastlogin) {this.userid = userid; this.username = username; this.userpasword = userpasword; this.lastlogin = lastlogin;} / ** * @ RETURN Last login time * / public string getLastLogin () {return LastLogin;}

/ ** * @return user ID * / public string getUserid () {return userid;}

/ ** * @return username * / public string getUsername () {return username;}

/ ** * @Return user password * / public string getUserPasword () {return UserPasword;}

/ ** * @Param String Last login time, format YYYY-MM-DD HH: mm: ss * / public void setlastlogin (string string) {LastLogin = String;}

/ ** * @Param String User Name * / Public Void SetUserName (String String) {username = string;}

/ ** * @param string User Password * / public void setUserpasword (String string) {userpasword = string;} / ** * of the form submission check * / public ActionErrors validate (ActionMapping mapping, HttpServletRequest request) {ActionErrors errors = Super.validate (mapping, request); return errors;

Here we see that our FORMBEAN has joined the functionality of the data check, and will be carefully described below. At the same time, in order to convert related constructors and private methods for transformations with Hibernate's database.

Establish the first Action to join the definition of Action in Struts-Config.xml, as follows:

Here we explain that Name and Attribute illustrate the name of the FORMBEAN used in this action, and the PATH specifies the URL header that calls action. TYPE indicates the action. The implementation of the specific class, Scope illustrates the area survived by FormBean, and INPUT illustrates the address of the VIEW of the input data (substantially the VIEW referring to the question). In the final Forward definition, a series of action may be used for a VIEW point that may be used, here we only specify one, and will join one by one. Then the new Sysuseraction class in the com.huangdong.dbwebdemo.Agdong-packet:

Package com.huangdong.dbwebdemo.Action;

Import java.util.locale;

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 .MessageResources;

Import com.huangdong.dbwebdemo.form.sysuserform;

Public class sysuseraction extends action {

/ / -------------------------------------------------------------------------------------------- --------- Instance Variables

/ / -------------------------------------------------------------------------------------------- --------- Methods

/ ** * Method execute * @param ActionMapping mapping * @param ActionForm form * @param HttpServletRequest request * @param HttpServletResponse response * @return ActionForward * @throws Exception * / public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse Response) throws exception {

// Initialization System Language Resource Locale Locale = getLocale (Request); MessageResources message = getResources; // This action Default Receive request to create a new Sysuser string action = "create"; return (mapping.findforward) Action));}} The two sentences here are the local message resource file language code used to set the VIEW. The data of the relationship VO to the PO association VO to the PO is represented by the data of the traffic layer, and the PO is the data of the persistent layer. VO will use a lot of usage when viewing and business processing, that is, all data before entering the library will be stored in a VO. And Po is the persistent data structure of the database in Java.

Many people like to combine the Struts's VO with Hibernate's PO, I don't agree, there are many reasons, the most important thing is:

Vo has its own data properties, and due to the differences in the framework, there may be our own structure and method. I like to use FormBean in Struts, which is also a large number of business operations in a class Vo of the ACTIONForm. Such as verification, automatic generation, etc., the relationship between the dataset is included, such as the relationship in the database, also reflects one-to-one, more-to-many, one-on-one, etc. in the PO, but not necessarily in VO. Pay attention to this detail, I prefer to use one or more associated classes to map VO and PO in business logic, implement VO to PO conversion, and the removal of VO in PO.

The operation of all VO to PO and PO operations is basically deposited or changed (deleted) of the persistent layer data. Such an operation will definitely involve transaction operations of the database. On the other hand, the data of PO to VO involves the buffer, paging, and other techniques such as data sets. So we declare two abrasions for these two situations:

The AbsbaseMap class mainly completes data operations of VO to PO:

Package com.huangdong.dbwebdemo.db;

Import net.sf.hibelption; import net.sf.hibernate.Session; import net.sf.hibernate.transaction;

Import com.huangdong.dbwebdemo.dbutil;

/ ** * System VO and PO Operation Map Class, complete database transaction and connection initialization and database transaction submission and database connection close * @Author hd * / public abstract class absbasemap {// database connection session private SESSION session; // Database transaction processor Private Transaction Transaction;

/ * ** * initialize database connectivity transaction database connection initialization completion @return * @throws HibernateException * / public Session beginTransaction () throws HibernateException {session = DBUtil.currentSession (); transaction = session.beginTransaction (); return session;}

/ ** * Complete a database transaction * @Param commit is submitted to transaction, True Submit, False Time Database hair rollback (ROLLBACK) * @Throws HibernateException * / public void endTransaction (Boolean commit) throws HibernateException {if (commit) {Transaction.commit ();} else {transaction.rollback ();} DBUTIL.CLOSESSESSSION ();}} AbsqueryMap class is mainly provided with an abstract method for queries for persistent layer data: package com.huangdong.dbwebDemo.db ;

/ ** * System VO and PO's query mapping abstract class, add query paging related settings * @Author hd * / public class absquerymap {/ ** * Database connection session ** / session session;

// Page 20 INT Pagesize = 20; // Current page INT PAGENO = 1;

/ ** * @return page number size (default is 20) * / public int getpageSize () {return Pagesize;}

/ ** * @Param i sets the number of page numbers * / public void setpagesize (INT i) {pageSize = i;} / ** * @return Returns the current page number, the initial value is 1 * / public int getPageno () { Return Pageno;

/ ** * @Param i set the current page number * / public void setpageno (int i) {PAGENO = i;

/ ** * Setting query * / public void setQueryPage (query query) {// Set Pipement Start Record Number Query.setFirstResult ((this.pageno - 1) * this.pageSize); // Setting the page Data Queue Query .SETMAXRESULTS (this.pageSize);

/ ** * Open the current database connection * @Return * @Throws HibernateException * / public void initssis () THROWS HibernateException {this.Session = dbutil.currentSession ();}

/ ** * Close the current database connection * @throws hibernateException * / public void closesession () throws hibernateException {dbutil.closesession () after (), all our database update operations inherit the AbsbaseMap class, and the database query operation will inherit AbsqueryMap class.

Database increasing, deletion, and change Operation Map Once you have the features provided by the AbsbaSemap abstract class and Hibernate provided, we only need to know a little bit of Java's knowledge to complete complex database updates.

First, create a new class named SysuserMap in com.huangdong.dbwebdemo.db package and extend the ABSBaseMap class:

Package com.huangdong.dbwebdemo.db;

Import com.huangdong.dbwebdemo.form.sysuserform; public class sysusermap extends absbasemap {

} Firstly, an increased method, in the VO layer, the data class we use is SYSUSERFORM, so the parameter of the increase method must be SYSUSERFORM:

public void createSysUser (SysuserForm sysuerForm) throws HibernateException {// attributes related to the use of the new sysuser sysuerForm Examples SysUser sysuser = new SysUser (sysuerForm.getUsername (), sysuerForm.getUserpasword (), Calendar.getInstance ()); // start transaction Session Session = this.begintransaction (); try {// Add this instance into the database session.save (sysuser); // Commit this.endtransaction (true);} catch (hibernateException E) {// rollback this.endtransaction False); throw e;}} This method is very simple, and the writing is completely unreasonable.

Then we will write updated code, compared to the same simple:

/ * ** Update contains a sysuser * @param sysuerForm updated content sysuser form bean * @throws HibernateException * / public void updateSysUser (SysuserForm sysuerForm) throws HibernateException {// use the relevant attributes sysuerForm sysuser new instance SysUser sysuser = new SysUser ( Sysuerform.getuserName (), sysuerform.getuserPasword (), Calendar.GetInstance ()); // Start transaction session session = this.begintransaction (); try {// Add this instance into the database session.Update (sysuser); // Commit this.endTransaction (TRUE);} catch (hibernateException e) {// rollback this.endtransaction (false);}} Let's write a content more code - delete. Delete is generally deleted using the user ID, so the parameter can be a FORMBEAN with a user ID or a user ID, we use two ways to implement deletion:

Form Bean * @throws HibernateException / ** * based on a user to remove the sysuser formbean * @param sysuerForm containing the user information * / public void deleteSysUser (SysuserForm sysuerForm) throws HibernateException {String userid = sysuerForm.getUserid (); this. deleteSysUser (userid);} / ** * based on the user ID of the user to delete * @param userid user ID * @throws HibernateException * / public void deleteSysUser (String userid) throws HibernateException {Session session = this.beginTransaction (); try { // Query if there is this user sysuser sysuser = (sysuser.class, userid); // kill it! Session.delete (Sysuser); this.endTransaction (TRUE);} catch (hibernateException e) {this.endtransaction (false);}}} The database is relatively complex, we start from simplicity, do not use it first Any spare parts, query all records in the database. Create a sysuserqueMap class in com.huangdong.dbwebdemo.db, which extends AbsqueryMap Class: package com.huangdong.dbwebdemo.db;

Import java.util.iterator;

Import net.sf.hibelnate.hibernateException; import net.sf.hibernate.query;

/ ** * @Author hd * / public class sysuserQuerymap extends absqurymap {public sysuserQuerymap () throws hibernateException {this.initssession ();}

public Iterator findAllSysUser () throws HibernateException {// query String querystr = "from SysUser"; // Create a query Query query = this.session.createQuery (querystr); // set page this.setQueryPage (query); // returns The result set return query.iterate ();}} Here we have written a way to query all users, its first sentence:

String queryStr = "from sysuser"; here's query statement uses Hibernate's HQL syntax, other we don't need to manage, here Sysuser is case sensitive, we define the Sysuser database map class, here must be exactly the same, this Hibernate An instance of all Sysuser classes will be removed from the database.

Next, we also need a method to return to the user corresponding to the user's ID.

/ ** * * Examples of queries that a user UserID @return * @param user UserID example of a user UserID, if no corresponding record database returns null * @throws HibernateException * / public SysuserForm getSysuserByID (String UserID) throws HibernateException {SysuserForm sysuerform = null; try {sysuerform = new sysuserform ((sysuser) this.Session.Load (sysuser.class, userid));} catch (hibernateException e) {throw e;} return sysuerform;} With this method, we can specify The user is inquiry or modifies the information he has.

Creating the first View New JSP page We first set a JSP page for adding records, which provides a VIEW that adds records.

<bean: message key = "title.register" /> </ title> <meta http-equiv = "pragma" content = "no-cache"> <meta http- Equiv = "cache-control" content = "no-cache"> <meta http-equiv = "expires" content = "0"> </ head> <body> <Logic: Notempty Name = "sysuserform" Property = "Username "Scope =" request "> <html: errors /> </ logic: Notempty> <html: form action =" / sysuser.do "method =" post "focus =" login "οnsubmit =" Return Validatesysuserform (this); "> <Table Border =" 0 "> <TR> <TD> <bean: Message Key =" Prompt.Login "/> </ td> <TD> <HTML: Text Property =" UserName "Size =" 16 " MaxLength = "16" /> </ td> <bean: message key = "prompt.password" /> </ td> <td> <html: password property = "userpasword" /> </ Td> </ tr> <logic: Notempty Name = "sysuserform" proty = "lastlogin" scope = "request"> <td> <html: hidden protety = "L ASTLOGIN "WRITE =" true "/> </ td> </ logic: NOTEMPTY> <TR> <TD colspan =" 2 "align =" center "> <logic: Empty name =" sysuserform "Property =</p> <p>"userid" scope = "request"> <input type = "hidden" name = "act" value = "add" /> </ logic: EMPTY> <logic: Notempty Name = "sysuserform" property = "userid" scope = "Request"> <input type = "hidden" name = "act" value = "update" /> </ logic: NOTEMPTY> <html: submit> <bean: message key = "button.submit" /> </ html : Submit> </ td> </ tr> </ table> </ html: form> <html: javascript formname = "sysuserform" Dynamicjavascript = "true" staticjavascript = "false" /> <script language = "JavaScript1.1 "Src =" ../ staticjavascript.jsp "/> </ script> </ body> </ html: html> For the use of various Taglib in this JSP page, we will not explain here, you can go to technology The CHINESE STRUTS project website in the sky understands the use of these TAGs. We only do some instructions for some of our concern. First we use HTML: Errors this tag to display the possible error message, in the following wee Action Process we will join our data check, the error generated by the background operation, here is displayed here. . The action = "/ sysuser.do" illustrates submitted to the Sysuser this action, because the specific increase method is completed in this action. The properties of the form are finally a οnSubmit = "Return Validatesysuserform (this);" is used to verify the correctness of each input entry, and the definition of each entry will be described later. At the end of the form, we use the Logic this tag to determine if the userid in the sysuserform exists, where the default value of the ACT parameter in the form is Add or Edit. The reason for this is that we will also use this JSP for editing of user information. At the end of the entire page, we used HTML: JavaScript TAG generated the check javascript used by Sysuserform. To optimize the use of resources, we put all the verbs JavaScript in a JSP and will be incorporated in the last reference label of JavaScript.</p> <p>VIEW public check JavaScript code page below We list the contents of StaticJavaScript.jsp:</p> <p><% @ Page language = "java"%> <% - set document type to javascript (addresses a bug in netscape agent (addresses a bug in netscape accounting to a web resource -%> <% @ Page ContentType = "Application / X-javascript"%> <% @ Taglib URI = "/ Web-INF / STRUTS-HTML.TLD" prefix = "html"%></p> <p><HTML: JavaScript DynamicJavaScript = "false" staticjavascript = "true" /> This JSP is the use of the check components belled by the Struts to generate all JavaScript used by the check.</p> <p>Associating business logic to an Action adding This action will process all the operations associated with Sysuser, so the requests received by the Action will have multiple requests, and we add the following code in the Execute method:</p> <p>IF ("create")) {// If the processing request type is CREATE Request.setttribute ("sysuserform", new sysuserform ()); action = "create";} else if (action.equals ("add ")) {// If the processing request type is add sysusermap sysusermap = new sysusermap (); try {sysusermap.createsysuser (sysuser); // Join success, let us first add a user request.settribute (" sysuserform ", New sysuserform ()); action = "create";} catch (hibernateException e) {// Data stock = new actionerrors errors = new actionerrors (); errors.add (actionerrors.global_ERror, new actionerror ("error.database.save ", E.tostring ()); this.saveErRors (Request, Errors); // Display the current data back and display to re-enter Request.settribute (" sysuserform ";" sysuserform "; action =" create "; } This business operation is very simple, mainly calling MAP to store VO into PO, complete a function of adding a record to the database. Our specific implementation is to create a new FormBean to store the user's input, then place the data in the FORMBEAN into the database. If an error occurs while depositing, we turn the contents of this Exception into the error in the JSP (you can look back to see the content in the JSP).</p> <p>Next, we complete deletion, change, check, and these operations are also very simple.</p> <p>IF (action == null || action.equals ("list")) {// If the processing request type is list sysuserQuerymap sqm = new sysuserQueryMap (); iterator sysuserlist = sqm.findallsysuser (); request.settribute ("sysuserlist" , Sysuserlist); action = "list";} This code is defined when the following is the operation of all users when the List operation is requested. It is actually called the FindallSysuser in the previously completed SysuserQueryMap to remove all users from the database. The user list then pressed into the bean. if (action.equals ( "edit")) {// request type edit SysUserQueryMap sqm = new SysUserQueryMap (); String uid = request.getParameter ( "userid"); request.setAttribute ( "sysuserForm", sqm.getSysuserByID ( UID);} else if ("Update")) {// Request type is update sysusermap sysusermap = new sysusermap (); sysusermap.UpdateSysuser (sysuser); action = "list";} This code is completed Edit the work of user data. We can see that the first need to complete an Edit work, the role of this operation is to acquire this user information from the database, and then press this user information into the FORMBEAN to display. After the user changes the information, complete the UPDATE operation, update the database entry.</p> <p>IF ("delete")) {// If the processing request type is delete sysusermap sysusermap = new sysusermap (); string uid = request.getParameter ("userid"); try {sysusermap.deletesysuser (uid);} catch (HibernateException e) {ActionErrors errors = new ActionErrors (); errors.add (ActionErrors.GLOBAL_ERROR, new ActionError ( "error.database.delete", e.toString ())); this.saveErrors (request, errors); } An action = "list";} This code completes the deleted function. Delete the specified entry. If an error is pressed, it is incorrect to a global error.</p> <p>Data input to forms is verified in Struts with a data check frame called Validator in Jakarta Commons. It is also very simple to use.</p> <p>First put the profile of the Validator-Rules.xml provided by Struts in web-infers.</p> <p>Then add the Validation of Validation in Struts-Config.xml:</p> <p><plug-in classname = "org.apache.struts.validator.validatorPlugin"> <set-protety property = "pathnames" value = "/ web-inf / validator-rules.xml, / web-inf / value.xml" /> </ plug-in> We will see that there is also a validator.xml file does not exist, in the newly built XML file in Web-INF, we need to join your own verification information: <? XML Version = "1.0 "Encoding =" ISO-8859-1 "?></p> <p><! Doctype form-validation public "- // Apache Software Foundation // DTD Commons Validator Rules Configuration 1.0 // En" "http://jakarta.apache.org/commons/dtds/Validator_1_0.dtd"></p> <p><form-validation> <formset></p> <p><form name = "sysuserform"></p> <p><Field Property = "Username" depends = "Required, minlength, maxlength"> <arg0 key = "prompt.login" /> <arg1 key = "$ {var: minlength}" name = "minlength" resource = "false" /> <Arg2 key = "$ {var: maxlength}" name = "maxlength" resource = "false" /> <var> <var-name> maxlength </ var-name> <var-value> 16 </ var -Value> </ var> <var> <var-name> minlength </ var-name> <var-value> 3 </ var-value> </ var> </ field></p> <p><Field Property = "UserPasword" Depends = "Required, MINLENGTH, MAXLENGTH"> <arg0 key = "prompt.password" /> <arg1 key = "$ {var: minlength}" name = "minlength" resource = "false" /> <Arg2 key = "$ {var: maxlength}" name = "maxlength" resource = "false" /> <var> <var-name> maxlength </ var-name> <var-value> 16 </ var -Value> </ var> <var> <var-name> minlength </ var-name> <var-value> 3 </ var-value> </ var> </ field> </ form> </ formset> </ form-validation> Carefully look at this XML file content will find that it explains the table named SysuserForm to verify and do a check method for the specified fields in this form. Description. For details of the specific Validator, please refer to the relevant documentation of it belts and the relevant instructions for Struts.</p> <p>Note: If you check the form using the default check rule, you need to pay attention to a few critical places, otherwise you may take a long time to check the reason for the JS script that cannot be applied. First of all, the formbean you use cannot be the original Actionform, you need to change to ValidatorForm. There must be a validate method similar to this form:</p> <p>Public ActionerRors Validate (ActionMapping Mapping, HttpServletRequest Request) {ActionerRors Errors = Super.Validate (Mapping, Request); Return Errors;</p> <p>} Secondly, you need to declare the use of JavaScript at the end of the page.</p> <p><html: javascript formname = "sysuserform" DynamicjavaScript = "true" staticjavascript = "false" /> DynamicJavascript property is whether the dynamic JS script is generated in the page. This property must be true if you want to check the form. StaticJavaScript property represents whether a static JS script is generated in the page. If you are set to true, the rule check JS in the validator-rules.xml file will be filled in this page. The effect of this is not very good, because it will make the page very large and consume a lot of additional resources. The usual approach is to set this option to false, populate the JS in Validator-Rules.xml to a specified JSP page. Such a plurality of forms can use a static page simultaneously to save a lot of resources. If we do this, we need to be referenced in the statement on this static page. <script language = "JavaScript1.1" src = "../ staticjavascript.jsp" /> </ script> should also pay attention to this sentence, try to use the relative path. It is difficult to accurately locate this static page when using an absolute path.</p> <p>The last thing to pay attention to is to reference this JS check.</p> <p><html: form action = "/ sysuser.do" method = "post" focus = "login" οnsubmit = "Return Validatesysuserform (this);"> Return Validatesysuserform (this); the name of this function is based on the form you check The name is changed. For example, the form we check is called Sysuserform, the name of the generated check function is Validatesysuserform. You need to modify it to the function name corresponding to the form you need to check, otherwise the JS check is to be inexposed.</p> <p>The appendix finally we provide the complete items of our examples to download. You can easily import this project into your Eclipse.</p> <p>Transfer from http://bsd.huangdongdong.com/dev/hib/HIBERNATE/StrutsAction/index.html</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-50334.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="50334" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.052</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'wZfPC2WEpoRK07e8TjxKbp61Zock1G7QXu19n0Ty3erltTvXoc9rg9ssBPWY_2Bs4yQZe6T3dw9HZsxkyqmgAvDA_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>