Struts + Hibernate Template Development Notes

xiaoxiao2021-03-06  38

Struts Hibernate Template Development Notes

Author: sharp knife prodigal son (section Hongjie)

First, establish a database link pool

Second, establish a test database

Third, establish Hibernate configuration

Fourth, map the table of the database to the class

Five, the package definition in the template

Six, design mode: single case

Seven, design mode: facade

Eight, design mode: DAO

Nine, design mode: MVC

Ten, custom label

11. Solve Chinese character encoding problems

First, establish a database link pool

1. Copulate the database driver into the common / lib directory of Tomcat5.0.

Such as: Oracle9i copy ojdbc14.jar

2. Modify the Tomcat configuration file conf / server.xml. Add the following code before :

factory org.apache.commons.dbcp.basicDataSourceFactory driverclassname < Value> Oracle.jdbc.driver.racledriver URL jdbc: Oracle: Thin: @ 192.168.3.200: 1521: Demo < / parameter> username demo password demo < Parameter> maxactive 20 maxidle 10 maxwait -1 2 Establish a test database

1. Establish a database user name DEMO password DEMO

2. Establish a test table

Establish test table Demo

Field Description ID Char (100) Primary Key Name VARCHAR2 (50) Name Image_id Number (10) Image ID System_Date Date System Date User_Date Date Entry Date

Create a picture index table image

Field Description ID Char (100) Primary Key Title Varchar2 (50) Picture Title Message Varchar2 (2000) Image ORIGINAL_IMAGE_PATH VARCHAR (200) Original Picture Save Path Small _Image_path varchar (200) Small picture Save Path Image_id Number (10) Image ID System_Date Date System date ID index table SINGLETON_ID

Field Description ID Char (100) Primary Key Name Varchar2 (50) Index Name (need to build an index for this field) Value Number (10) Index ID

Third, establish Hibernate configuration

1. Copy Oracle9i Database Driver Ojdbc14.jar to the Lib Directory of the JBuilder9 installation directory. Use JBuilder9.0 to establish Project Project.

2. Put the following Hibernate-2.0.3 must be included in the project.

Hibernate2.jar

Commons-beanutils.jar

Commons-Collects.jar

Commons-dbcp.jar

Commons-lang.jar

Commons-logging.jar

Commons-pool.jar

Dom4j.jar

CGLIB-asm.jar

CONNECTOR.JAR

3. Establish a hibernate.cfg.xml file and copy to the src directory

java: comp / env / jdbc / demo TRUE < / proty> true net.sf.hibernate.diaalect.racle9DiaAlact

Fourth, map the table of the database to the class

Download Hibernate-Extensions Compressed Pack. Modify the environment variables in the setEnv.bat file. Mainly modify the Hibernate directory and database driver file name.

E.g:

@echo off rem ---------------------------------------------------------------------------------------------------------------------- -------------------- Rem Setup Environment for Hibernate ToolsRem ----------------------- ------------------------------------------- set jdbc_driver = .. / ../../lib/ojdbc14.jarset hibernate_home = .. / .. / .. / Hibernate-2.0.3

SET CORELIB =% hibernate_Home% / libset lib = .. / libset props =% hibernate_Home% / srcset CP =% jdbc_driver%;% PROPS%;% hibernate_home% / hibernate2.jar;% CoreLib% / Commons-logging.jar;% Corelib%;% corelib% / commiss-lang.jar;% corelib% / cglib.jar;% Corelib% / Dom4j.jar;% Corelib% / odmg.jar;% Corelib% / XML-APIS .jar;% Corelib% / Xerces.jar;% Corelib% / Xalan.jar;% lib% / jdom.jar;% lib% / .. / hibernate-tools.jar

Run DDL2HBM.BAT, set parameters as follows:

[Connection] Driver Class: Oracle.jdbc.driver.OracleDriver (org.gjt.mm.mysql.driver) Connection URL: JDBC: Oracle: Thin: @ 192.168.3.200: 1521: Demo (JDBC: mysql: // localhost / Authority) User: Demopassword: Demo

[Mapping] Key Field: IDSChemaexport: uuid.hex

[Code] package name: com.company.demo.jdo

[OUTPUT] F: / J_WORK / WORKING / DEMO / SRC

Other use of default, click [Tables] Tables .. Select Table, Program Generate Class and XML

The generated files are as follows:

(1) Image.java

package com.company.demo.jdo; import java.io.Serializable; 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;

/ ** @Author hibernate codeGenerator * / public class image imports serializable {

/ ** iDentifier Field * / private string id;

/ ** Nullable persistent Field * / private string Title

/ ** Nullable Persistent Field * / private string message;

/ ** Nullable Persistent Field * / Private String OriginalImagePath;

/ ** Nullable Persistent Field * / Private String SmallImagePath; / ** Nullable Persistent Field * / Private Long ImageId;

/ ** Nullable Persistent Field * / Private Date SystemDate;

/ ** full constructor * / public Image (String title, String message, String originalImagePath, String smallImagePath, long imageId, Date systemDate) {this.title = title; this.message = message; this.originalImagePath = originalImagePath; this.smallImagePath = SmallImagePath; this.imageId = imageid; this.systemdate = systemdate;}

/ ** Default constructor * / public image () {}

Public string getId () {returnim.

Public void setid (string id) {this.id = id;}

Public string gettitle () {return this.title;

Public void settitle (string title) {this.title = Title;}

Public string getMessage () {return this.Message;

Public void setmessage (string message) {this.Message = message;}

Public String getoriginalImagePath () {return this.originalImagePath;

Public void setORIGINALIMAGEPATH (String OriginalImagePath) {this.originalImagePath = OriginalImagePath;}

Public string getsmallimagepath () {return this.smallimagepath;}

Public void setsmallImagePath {this.smallImagePath = smallimagepath;

Public long getImageId () {return this.imageId;

Public void setImageId (long meansid) {this.imageId = imageid;

Public Date getSystemDate () {return this.systemdate;}

Public void setsystemdate (date systemdate) {this.systemdate = systemdate;}

Public string toString () {Return New TostringBuilder (this) .append ("id", getId ()). Tostring ();}

public boolean equals (Object other) {if return false ((other instanceof Image)!); Image castOther = (Image) other;.. return new EqualsBuilder () append (this.getId (), castOther.getId ()) isEquals (); public int.come () {return new hashcodebuilder (). append (getId ()). tohashcode ();

}

(2) Image.hbm.xml

Other generated files!

Five, the package definition in the template

Com.company.Demo.dataModule data model com.Company.DEMO.DAO DAO model com.Company.Demo.exception exception com.Company.Demo.jdo hibernate class map com.Company.Demo.start launching JSP service When you load COM.Company.Demo.tags Custom Tag Class COM.Company.Demo.thread thread class com.Company.Demo.util tool class com.Company.Demo.Web struts class com.company.demo.facade facade called class six , Design mode: single case

Data model

Interface (DataModule.java)

Package com.Company.Demo.dataModule; package com.company.demo.dataModule

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

Import net.sf.hibrnate.SessionFactory; import net.sf.hibrnate.cfg.configuration;

/ ***

Title: Struts Hibernate Development Template *

Description: General Development Template *

Copyright: CopyRight (C) 2003 *

Company: Advantage Technology * @Author Duan Hongjie * @version 1.0 * /

Public interface DataModule {public sessionFactory getsessionFactory ();}

Data model (DATAMODULEIMPL.JAVA)

Package com.company.demo.dataModule;

/ ***

Title: Struts Hibernate Development Template *

Description: General Development Template *

Copyright: CopyRight (C) 2003 *

Company: Advantage Technology * @Author Duan Hongjie * @version 1.0 * /

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

Import net.sf.hibrnate.SessionFactory; import net.sf.hibrnate.cfg.configuration;

/ *** Establish sessionFactory * /

Public Class DataModuleImpl Implements DataModule {

Private sessionFactory sessionFactory;

Public DataModuleImpl () throws hibernateException {sessionFactory = new configuration (). configure (). buildsessionFactory ();} / *** SedionsFactory * / from DataModule * /

Public sessionFactory GetSessionFactory () {return this.SessionFactory;}} 2. Produced parent class

Singletoniddao.java

Package com.Company.Demo.dao; / ***

Title: struts hibernate development template *

description: General Development Template *

Copyright: CopyRight (c) 2003 *

Company: Advantage Technology * @Author Duan Hongjie * @version 1.0 * /

Public interface singletoniddao {}

ID parent class (SingletonidDaoImpl.java)

Package com.Company.Demo.da;

Import java.util.list; import com.company.demo.dataModule. *; import com.company.demo.jdo.singletonid;

Import net.sf.hibinal.SessionFactory; import net.sf.hibernate.hibernateException; import net.sf.hibernate.Session; import net.sf.hibernate.Transaction; import net.sf.hibernate.query;

/ *** Generate a unique ID ** database structure (Oracle9i): * Name Singleton_ID * Field ID (Char) Name Varchar2 (50) Value Number (10.0) ***

Title: Struts Hibernate Development Template < / p> *

Description: General Development Template *

Copyright: Copyright (C) 2003 *

Company: Advantages Technology * @Author Duan Hongjie * @version 1.0 *** /

Public Class SingletonidDaoImpl Implements Singletonidda {

Private sessionFactory sessionFactory; private datamodule DataModule;

/ *** Set data model * /

Public void setDataModule {this.dataModule = DATAModule; this.SessionFactory = DATAMODULE.GETSESSIONFACTORY ()

The following business logic private SingletonId findByName (String name) throws HibernateException, Exception {Transaction transaction = null; SingletonId singletonId = new SingletonId (); Session session = sessionFactory.openSession (); String queryString = "select g from SingletonId as g where g .name =: name order by g.value desc "; try {transaction = session.begintransaction (); query query = session.createQuery (queryString); Query.setString (" name ", name); // q.setfirstresult ( 20000); // q.setMaxResults (100); query.setMaxResults (1); list list = query.list (); singletonid = (singletonid) list.get (0); transaction.commit ();} catch (Exception EX) {if (transaction! = null) {transaction.rollback ();} // throw ex;} finally {session.close ();} return singletonid;} / ** gaining value * @Param Name produced unique ID Type name * @Return Value * @throws HibernateException * /

protected long getValue (String name) throws HibernateException, Exception {SingletonId singletonId = findByName (name); return singletonId.getValue ();} / ** set value * @param name Name Type yield unique ID * @throws HibernateException * /

protected void setValue (String name) throws HibernateException, Exception {Session session = sessionFactory.openSession (); SingletonId singletonId = findByName (name); singletonId.setName (name); singletonId.setValue (singletonId.getValue () 1); Transaction transaction = null; try {transaction = session.beginTransaction (); session.saveOrUpdate (singletonId); transaction.commit ();} catch (HibernateException he) {if (transaction = null!) {transaction.rollback ();} throw HE;} finally {session.close ();}}}

3. Single case image ID (ImageSingletonid.java)

package com.company.demo.dao.count; import net.sf.hibernate.HibernateException; import com.company.demo.dao.SingletonIdDAOImpl; import com.company.demo.datamodule.DataModule; / ***

Title : Struts Hibernate Development Template *

Description: General Development Template *

Copyright: Copyright (C) 2003 *

Company: Advantage Technology * @Author Duan Hongjie * @version 1.0 * /

Public class imageSingletonid Extends SingletonidDaoImpl {

Private static imageashletonid iMageSingletonid = NULL;

/ *** private constructor * / private ImageSingletonId () {} / *** static factory pattern, made ImageSingletonId instance * / public static synchronized ImageSingletonId getInstance () {if (imageSingletonId == null) {imageSingletonId = new ImageSingletonId () Return ImageSingletonId;}

/ *** Take a graphic unique id * / public synchronized long getimagevalval () throws hibernateException, Exception {long value; setValue ("image"); value = getValue ("image"); return value;}

}

4. Picture ID test file (TestimageSingletonid.jsp)

<% @ Page ContentType = "Text / HTML; Charset = GB2312"%> <% @ page import = "Net.sf.hibernate. *"%> <% @ Page Import = "Net.sf.hibernate.cfg. * "%> <% @ page import =" com.company.demo.dataModule. * "%> <% @ page import =" com.company.demo.dao.count. * "%> <%! DataModule DataModule; ImageSingletonid imageSingletonId;%> <% try {imageSingletonId = ImageSingletonId.getInstance (); imageSingletonId.setDataModule (new DataModuleImpl ());} catch (Exception ex) {ex.toString ();} for (int i = 0; i <100 i ) {OUT.PRINT ("Test .........
"); out.print (imageSingletonid.getImageValue ()); out.print ("-------- --------
");}%>

5. SinglePageSingletonid.java package com.company.demo.dao.count; import net.sf.hibernate.hibernateException; import com.company.demo.dao.singletonidDaoImpl; import com.company. Demo.dataModule.DataModule;

/ ***

Title: Struts Hibernate Development Template *

Description: General Development Template *

Copyright: CopyRight (C) 2003 *

Company: Advantage Technology * @Author Duan Hongjie * @version 1.0 * /

Public class mainpageSingletonid Extends SingletonidDaoImpl {

Private static mainpageSingletonid mainpageSingletonid = NULL

/ *** private constructor * / private MainPageSingletonId () {} / *** static factory pattern, made MainPageSingletonId instance * / public static synchronized MainPageSingletonId getInstance () {if (mainPageSingletonId == null) {mainPageSingletonId = new MainPageSingletonId () Return MainpageSingletonid;}

/ *** Take a unique ID * / public synchronized long getMainPageValue () throws hibernateException, Exception {long value; setValue ("mainpage"); value = getValue ("mainpage"); return value;}

}

6. Music ID Test File (TestMainPageSingletonid.jsp)

<% @ Page ContentType = "Text / HTML; Charset = GB2312"%> <% @ page import = "Net.sf.hibernate. *"%> <% @ Page Import = "Net.sf.hibernate.cfg. * "%> <% @ page import =" com.company.demo.dataModule. * "%> <% @ page import =" com.company.demo.dao.count.mainpageSingletonid "%> <%! DataModule DataModule; mainpageSingletonid mainPageSingletonId;%> <% try {mainPageSingletonId = MainPageSingletonId.getInstance (); mainPageSingletonId.setDataModule (new DataModuleImpl ());} catch (Exception ex) {ex.toString ();} for (int i = 0; i <100 ; i ) {OUT.PRINT ("Test .........
"); out.print (MainpageSingletonid.getMainPageValue ()); Out.print ("-------- --------
");}%> 7. Comprehensive single sample test (omitted)

Seven, design mode: facade

1. Tune "Session Facade" class in JSP

Insert the following tags in the JSP file:

2.SessionBean class

Package com.company.demo.meb;

Import com.company.demo.datamodule.demo.thread. *; import com.company.demo.facade. *; / ***

Title: struts hibernate development template *

Description: General Development Template *

Copyright: Copyright (C) 2003 *

Company: Advantage Technology * @Author Duan Hongjie * @version 1.0 * /

Public class sessionBean {private damodule data model; // Data Model Private Auth; // Logic User Information Private Business Business; // Service Logic Mainline Private Line Line; / / Save Module / *** structure function, initializes the business logic class (singleton) * / public SessionBean () {try {dataModule = SessionBeanSingletonFactory.getDataModule (); auth = SessionBeanSingletonFactory.getAuth (); business = SessionBeanSingletonFactory.getBusiness (); line = SessionBeanSingletonFactory. GetLine ();} catch (exception ex) {ex.printStackTrace ();}} / *** Facade mode called public application module * @return utility * / public utility get1ility () {return sessionBeanfactory.getILITILITILITILITILITY () } 3.SessionBeanFactory class

Package com.company.demo.dataModule.Demo.dataModule.Demo.dataModule.Demo.thread. *; import com.company.demo.facade. *; import net.sf.hibernate.hibernateException / *** SessionBean facade pattern Abstract factory class *

Title: struts hibernate development template *

Description: General Development Template *

Copyright: CopyRight (c) 2003 *

Company: Advantage Technology * @Author Duan Hongjie * @version 1.0 * /

public class SessionBeanFactory {/ *** service logic state of the instance generation (facade) * @return LineImpl * @throws HibernateException * / private SessionBeanFactory () {} public final static Utility getUtility () {return new UtilityImpl ();}

}

4.SessionBeansingletonFactory class

Package com.company.demo.dataModule.Demo.dataModule.Demo.dataModule.Demo.thread. *; import com.company.demo.facade. *; import net.sf.hibernate.hibernateException ;

/ ***

Title: Struts Hibernate Development Template *

Description: General Development Template *

Copyright: CopyRight (C) 2003 *

Company: Advantage Technology * @Author Duan Hongjie * @version 1.0 * /

Public class sessionBeansingletonFactory {/ *** Generate user authentication instance (single case) * @Return Authimpl * @throws hibernateException * / private sessionBeansingletonFactory () {}

public final static Auth getAuth () throws HibernateException {return new AuthImpl ();} / *** generated business logic instance (singleton) * @return BusinessImpl * @throws HibernateException * / public final static Business getBusiness () throws HibernateException {return New businessimpl ();} / *** Generate data model instance (Sample) * @Return DataModuleImpl * @throws hibernateException * /

Public final static datamodule getDataModule () throws hibernateException {return new dataModuleImpl ();} / *** Generate business logic status instance (single case) * @return lineImpl * @throws hibernateException * /

Public final static line getLine () throws hibernateException {return new lineImpl ();

}

Eight, design mode: DAO

Using Data Access Objects (DAO) allows us to separate the underlying data access logic to business logic. We build a DAO class that provides GRUD (creation, reading, update, delete) for each data source.

Below is a DAO instance of a data source GRUD.

1. Demodao.java

Package com.Company.Demo.da;

Import net.sf.hibernate.hibernateException; import com.company.demo.jdo.demo; import com.company.demo.datamodule. *; / ***

Title: struts hibernate development template *

description: General Development Template *

Copyright: Copyright (C) 2003 *

Company: Advantage Technology * @Author Duan Hongjie * @version 1.0 * /

Public interface demodao {

/ ** Set data model ** / public void setDataModule (DATAMODULE DATAMODULE); / ** Establish an object ** / public void createDemo (Demo Demo) HibernateException, Exception

}

2. Abstract factory (DemodaOfactory.java)

Package com.Company.Demo.dao; / ***

Title: struts hibernate development template *

description: General Development Template *

Copyright: CopyRight (c) 2003 *

Company: Advantage Technology * @Author Duan Hongjie * @version 1.0 * /

Public class demodaofactory {

PRIVATE DEMODAOFACTORY ()} public final static demodao getdemodao () {Return New DemodaoImpl ();}} 3.DAO class (DEMODAOIMPL.JAVA)

Package com.company.demo.dao; import java.util.list; import com.company.demo.dataModule.DataModule.Demo.do.demo;

Import net.sf.hibinal.SessionFactory; import net.sf.hibernate.hibernateException; import net.sf.hibernate.Session; import net.sf.hibernate.Transaction; import net.sf.hibernate.query;

/ ***

Title: Struts Hibernate Development Template *

Description: General Development Template *

Copyright: CopyRight (C) 2003 *

Company: Advantage Technology * @Author Duan Hongjie * @version 1.0 * /

Public Class DemodaoImpl Implements Demodao {

Private sessionFactory sessionFactory; private datamodule DATAMODULE DATAMODULE

/ *** Set Data Model * @Param DataModule * / Public Void SetDataModule {this.DataModule = DATAModule; this.SessionFactory = DataModule.GetSessionFactory ();

/ *** establish DEMO * @param demo * @throws HibernateException * @throws java.lang.Exception * / public void createDemo (Demo demo) throws HibernateException, Exception {Transaction transaction = null; Session session = sessionFactory.openSession (); Try {Transaction = session.begintransaction (); session.save (demo); transaction.commit ();} catch (hibernateException he) {i (transaction! = null) {= i (transaction! = null);} throw he;} finally {session.close ();

}

Nine, design mode: MVC

1. Representation layer (Application Template)

JSP file (Template / BasicTemplate.jsp)

<% @ Page ContentType = "Text / HTML; Charset = GB2312"%> <% @ Taglib Uri = '/ Web-INF / STRUTS-TEMPLATE.TLD' Prefix = 'Template'%> <template: get name = 'title' /> </ title> <meta http-equiv = "content-type" content = "text / html; charSet = GB2312"> <meta http-equiv = "content-language" CONTENT = "zh-CN"> <META name = "vs_targetSchema" content = "http://schemas.microsoft.com/intellisense/ie5"> <META name = "keywords" content = "extreme programming, extreme projects, design Pattern, J2EE, Forum, Chinese> <link href = "default.css" type = "text / css" rel = "stylesheet"> </ head> <body TopMargin = '0'> <table width = "95% "border =" 0 "align =" center "> <tr> <td width =" 17% "rowspan =" 3 "> <! - start of navbar -> <template: get name = 'navbar' /> <! - end of navbar -> </ td> <td width = "83%" Valign = "TOP"> <! - start of header -> <template: get name = 'header' /> < ! - End of header -> </ td> </ tr> <tr> <td value = "top"> <! - start of content -> <template: get name = 'content' /> < ! - End of content -> </ td> </ tr> <tr> <td valign = "top"> <! - start of footer -> <templ Ate: get name = 'footer' /> <! - End of footer -> </ td> </ tr> </ table> </ body> </ html> JSP file (addDemo.jsp)</p> <p><% / *** <p> Title: Struts Development Test 1.0 </ P> * <P> Description: Item Description </ P> * <P> Copyright: Copyright (C) 2003-2008 </ P> * < P> Company: Advantage Technology </ P> * @Author Duan Hongjie * @version 1.0 * @time [October 22, 2003] ** /%> <% @ Page ContentType = "Text / HTML; Charset = GB2312 "%> <% @ Taglib URI = '/ Web-inf / struts-template.tld' prefix = 'template'%> <template: insert template = '/ template / BasicTemplate.jsp'> <template: Put Name = 'Title' Content = 'Struts Development Test 1.0' Direct = 'True' /> <Template: Put Name = 'Navbar' Content = '/ Content / NavBar.jsp' /> <Template: Put Name = 'Header' Content = '/ content / header.jsp' /> <template: put name = 'content' content = '/ content / adddemo.jsp' /> <template: put name = 'footr' content = '/ content / footer.jsp '/> </ template: insert></p> <p>JSP file (Content / AddDemo.jsp)</p> <p><% / *** <p> Title: Struts Development Test 1.0 </ P> * <P> Description: Item Description </ P> * <P> Copyright: Copyright (C) 2003-2008 </ P> * < P> Company: Advantage Technology </ P> * @Author Duan Hongjie * @version 1.0 * @time [October 22, 2003] ** /%></p> <p><% @ Page ContentType = "Text / HTML; Charset = GB2312"%> <% @ Taglib URI = "/ Web-INF / STRUTS-HTML.TLD" prefix = "HTML"%> <% @ Taglib URI = "/ WEB-INF / IMAGETAG.TLD "prefix =" image "%> <% @ Taglib URI =" / Web-inf / datetag.tld "prefix =" date "%> <jsp: usebean id =" sessionbean "scope =" Session "class =" com.Company.Demo.Web.SessionBean "/> <html: errors /> <form method =" post "action =" adddemoaction.do> <p> name (Name): <input name = "name" type = "text"> </ p></p> <p><p> Date: <date: InputButton type = "date" name = "userdate" /> </ p></p> <p><p> Date: <date: inputbutton type = "datetime" name = "userdatetime" /> </ p> <p> <image: uploadbutton savepath = "saveImagepath" /> </ p> <p> < Input type = "submit" name = "submit" value = "Submit"> <input type = "reset" name = "submit2" value = "reset"> </ p> </ form></p> <p>Struts-config.xml</p> <p><? XML Version = "1.0" Encoding = "UTF-8"?> <! doctype struts-config public "- // Apache Software Foundation // DTD Struts Configuration 1.0 //" http: //jakarta.apache. ORG / STRUTS / DTDS / STRUTS-CONFIG_1_0.DTD "> <struts-config> <form-beans> <form-bean name =" demoactionform "type =" com.company.demo.demoactionform "/> <form- Bean name = "imageuploadactionform" type = "com.company.demo.demo.demo.im" /> </ form-beans> <global-forwards> <forward name = "unknown-error" path = "/ error.jsp" / > <forward name = "success" path = "/ success.jsp" /> </ global-forwards> <action-mapings> <action name = "demoactionform" type = "com.company.demo.demoAddemoAdition" input = "/ addDemo.jsp" scope = "request" path = "/ addDemoAction" /> <action name = "imageUploadActionForm" type = "com.company.demo.web.ImageUploadAction" input = "/ content / imageUpload.jsp" Scope = "request" path = "/ imageupload" /> </ action-mappings> </ struts-config> file (DemoActionform.java)</p> <p>Package com.company.demo.meb; import org.apache.struts.action. *; import javax.servlet.http. *;</p> <p>public class DemoActionForm extends ActionForm {private String name; private String userDate; private String userDateTime; public String getName () {return name;} public void setName (String name) {this.name = name;} public String getUserDate () {return Userdate;} public void setuserdate (string userdate) {this.userdate = userdate;</p> <p>public String getUserDateTime () {return userDateTime;} public void setUserDateTime (String userDateTime) {this.userDateTime = userDateTime;} public ActionErrors validate (ActionMapping actionMapping, HttpServletRequest httpServletRequest) {/ ** @ todo: finish this method, this is just the (} public void reset) {}}}</p> <p>Application logic layer (AddDemoAction.java)</p> <p>Package com.company.demo.meb; import org.apache.struts.action. *; import javax.servlet.http. *; import java.util.date; import java.text.dateFormat; import java.text.SIMPLEDATEFORMAT;</p> <p>Import com.company; import com.company.demo.dao.demodao; import com.company.demo.dao.demodaofactory; import com.company.demo.dao.demodaoIMPL;</p> <p>public class AddDemoAction extends Action {public ActionForward perform (ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {/ ** @ todo:. complete the business logic here, this is just a skeleton * / DemoActionForm demoActionForm = (DemoActionForm) actionForm ; SessionBean httpServletRequest.getSession sessionBean = (SessionBean) () getAttribute ( "sessionBean");. if (sessionBean == null) {httpServletRequest.setAttribute ( "message", "system timed out, please sign in again !!!"); return actionMapping.findForward ( "unknown-error");} else {try {Demo demo = new Demo (); demo.setName (demoActionForm.getName ()); DateFormat dateTimeFormat = new SimpleDateFormat ( "yyyy-MM-dd hh: ss : mm "); Date userDateTime = dateTimeFormat.parse (demoActionForm.getUserDateTime ()); demo.setSystemDate (userDateTime); DateFormat dateFormat = new SimpleDateFormat (" yyyy-mM-dd "); Date userDate = dateFormat.parse (demoActionForm. GetUserDate ()); demo.setUserdate; Demodao Demodao = DEMODAOF actory.getDemoDAO (); demoDAO.setDataModule (sessionBean.getDataModule ()); demoDAO.createDemo (demo);} catch (Exception ex) {httpServletRequest.setAttribute ( "message", ex.toString ()); return (actionMapping. Findforward ("Unknown-Error");} httpservletRequest.setttribute ("Message", "success!"); return ("success"));}}} 10, custom label</p> <p>1. Custom Label (DateTag.TLD)</p> <p><? XML Version = "1.0" Encoding = "GB2312"?> <! doctype taglib public "- // sun microsystems, Inc.//dtd jsp tag library 1.2 // en" http://java.sun.com /J2EE/dtds/web-jsptaglibrary_1_2.dtd">< Taglibian (TLIBVERSION>1.0</TLIBVERSION> "jspition "1.2</jspitionang> <SHORTNAMEDATE TAG LIBRARY </ ShortName> <info> Date entry label Info> <tag> <name> InputButton </ name> <tagclass> com.company.deemo.tags.datetag </ tagclass> <bodycontent> EMPTY </ bodycontent> <attribute> <name> name </ name> <requestd > true </ required> <rtexprvalue> true </ rtexprvalue> </ attribute> <attribute> <name> type </ name> <required> true </ required> <rtexprvalue> true </ rtexprvalue> </ attribute> < / TAG (/taglib )2.tag class (datetag.java)</p> <p>Package com.company.demo.tags; import javax.servlet.jsp. *; import javax.servlet.jsp.tagext. *;</p> <p>Import javax.servlet. *;</p> <p>/ *** <p> Title: </ p> * <p> Description: </ p> * <p> Copyright: Copyright (C) 2003 </ P> * <p> Company: </ p> * @ Author Duan Hongjie * @version 1.0 * Generate Date Record Box * /</p> <p>Public class datetag extends tagsupport {string type, name; // type and parameter name</p> <p>Public void settype (String Type) throws jspexception {this.type = type;}</p> <p>Public void setname (String name) throws jspexception {this.name = name;}</p> <p>public int doStartTag () throws JspException {String string, dialogHeight, dialogWidth, size; if (type == "date") {dialogHeight = "290"; dialogWidth = "240"; size = "10";} else if (type == "DATETIME") {DIALOGHEIGHT = "315"; DialogWidth = "240"; size = "18";} else {throw new jsptagexception ("type parameter error, only Date or DateTime!");} String = <Script language = javascript> " " Function SelectDate " Name " {" " Window.showModalDialog ('content / dtpicker.jsp? Rn =' math.random (), OSource, 'Dialogheight: " Dialogheight "PX; DialogWidth:" Dialogwidth "PX; Center: YES; Help: NO; Resizable: NO; Scroll: NO; Status: NO; ')" "}" "</ script>" "< Input readonly size = " size " name = " name " DATATYPE = / "DATE ​​/" Comparer = / "comparetolastusedon /" DateTimetyPE = " Type "> "<img src = /" images / select.gif / "width = /" 23 / "height = /" 23 / "align = absmiddle" "οnclick = selectdate" name "(THIS.SOURCEIDEX-1))></p> <p>Try {jspwriter out = pageContext.get (); out.println (string);} catch (exception ex) {throw new jsptagexception ("error:" EX.GetMessage ();} Return Skip_body;} Public int doendtag () THROWS JSPEXCEPTION {Return Eval_page;}}</p> <p>11. Solve Chinese character encoding problems</p> <p>1. Modify the web.xml file, add the following after the <web-app> tag.</p> <p><filter> <filter-name> set character encoding </ filter-name> <filter-class> com.company.demo.util.setencodingfilter </ filter-class> <init-param> <param-name> Encoding </ PARAM-NAME> <param-value> GB2312 </ param-value> </ init-param> <filter-name> set character encoding </ filter-name> <url-pattern> / * </ url-pattern> </ filter-mapping> <servlet> 2. Create a class file (SetENCodingFilter.java)</p> <p>package com.company.demo.util; 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; import javax.servlet.unavailableException;</p> <p>/ *** SET All httprequest encoding</p> <p>* / public class setEncodingfilterIMplements filter {/ *** The default character encoding to set for reviews That pass throgh * this filter. * / protected string encoding = null;</p> <p>/ *** The filter configuration Object We are associated with. If this value * is null, this filter instance is not currently configured. * / Protected filterconfig filterconfig = null;</p> <p>/ *** SHOULD a CHARACTER ENCODING SPECIFIED BY THE CLIENT BE IGNORED? * / Protected boolean ignore = true;</p> <p>/ *** Take this filter out of service. * / Public void destroy () {this.encoding = null; this.filterconfig = NULL;}</p> <p>/ *** Select and set (if specified) the character encoding to be used to * interpret request parameters for this request. ** @param request The servlet request we are processing * @param result The servlet response we are creating * @param chain The filter chain we are processing ** @exception IOException if an input / output error occurs * @exception ServletException if a servlet error occurs * / public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {if ( ignore || (request.getCharacterEncoding () == null)) {request.setCharacterEncoding (selectEncoding (request));} chain.doFilter (request, response);} / *** Place this filter into service * @param filterConfig. The filter configuration Object * / public void inflicment "THROWS servletexception {</p> <p>this.filterConfig = filterConfig; this.encoding = filterConfig.getInitParameter ( "encoding"); String value = filterConfig.getInitParameter ( "ignore"); if (value == null) this.ignore = true; else if (value.equalsIgnoreCase ("True") || Value.Equalsignorecase ("YES")) this.Ignore = true; elsethis.ignore = false;}</p> <p>/ *** Select an appropriate character encoding to be used, based on the * characteristics of the current request and / or filter initialization * parameters. If no character encoding should be set, return * <code> null </ code>. * <p> * The default implementation unconditionally returns the value configured * by the <strong> encoding </ strong> initialization parameter for this * filter. ** @param request The servlet request we are processing * / protected String selectEncoding (ServletRequest request) {Return (this.encoding);} / *** Returns the filterconfig. * @return filterconfig * / public filterconfig getfilterconfig () {Return FilterConfig;</p> <p>/ *** sets the filterconfig. * @Param filter to set * / public void setfilterconfig (thermostfig filter) {this.filterconfig = filterconfig;}</p> <p>}</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-118445.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="118445" 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.049</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 = 'PPDrZ_2FlMHipwlOSx2r0dzR1Ad7mizwdmc086pqZNARB1aZcT8xMDXlvuVMyfCCuzdyDR_2BYOfIdAH6P_2FQKj3L_2FA_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>