Installation
1. Download and install j2sdk1.4 (www.sun.com) or above and set classpath and java_home.
2. Download the server. The free version includes tomcat, resin, and of course Weblogic and other giants, but it depends on whether your computer's configuration is sufficient!
Here, only resin is used to describe. Other configurations are similar. You can view the instruction files provided by each server.
The Resin server can be downloaded from caucho.com. Select the appropriate version and download and decompress it directly.
Here, resin has a resin-ee version, which is mainly supported by the EJB function. If EJB is not used, it is generally enough.
3. There are many database products to choose from, such as DB2, Oracle, MSSQL, and MySQL. Here I chose MySQL not only because it is free, but also its 4.0 version integrates the InnoDB (http://www.innodb.com) Advanced Transaction processing mechanism on the basis of inheriting the fast and stable previous versions. I believe that with the growth of Linux, it will take a place in the commercial database market. However, as far as the database itself is concerned, it still lacks support for powerful features such as subqueries.
There is not much to say about the installation. Configure the user name and password. Then you can download mysql-front to operate the database visually.
4. in Java programming, the functions of an IDE are obviously indispensable. Many popular ides include JBuilder, Eclipse, intellij idea, and jcreator, relying on powerful plug-in functions, JBuilder is hailed as the most promising tool. JBuilder has always been the most powerful Java tool, but as large as my computer, it cannot run, poor, no money for new computers. Therefore, I still like jcreator, Which is compact and has good functions and is more than enough to deal with small-scale applications. To get prompt support during compilation and development, you must import the JAR file in configure -- option -- JDK profiles.
5. The front-end interface development of a website is certainly inseparable from the famous Dreamweaver. It supports the development of JSP, ASP, and many other languages. In particular, the recent Dreamweaver MX 2004 enhancement of the site function allows you to easily control a site. In the face of struts foreground custom labels, there is an mxp plug-in that can be used to display sturts labels. Before use, you must import the. TLD file in the edit -- tag library. Currently, only HTML and bean tags are supported.
Configuration
1. Resin Virtual Site Configuration
<Host ID = 'yourweb: 8080 'app-Dir = 'e:/blog/'class-Update-interval = '2'> <Web-app id = '/'> <Directory-servlet id = 'false'/> </Web-app> <Error-log ID = 'Log/web-error.log '/> <Host> |
Create a site under the defined directory.
2. The configuration of the Dreamweaver site will not be discussed much.
3. Struts Configuration
Here we use struts1.1 to download and decompress it to a Temporary Folder. Assume It is the TEM folder.
First, copy all the following in TEM/lib. TLD file to the site/WEB-INF/directory, and then copy all. JAR file to the/WEB-INF/lib/directory, finally web. the configuration in the XML file is similar to the following:
<? XML version = "1.0" encoding = "ISO-8859-1"?> <! Doctype web-app Public "-// Sun Microsystems, Inc. // DTD web application 2.2 // en" Http://java.sun.com/j2ee/dtds/web-app_2_2.dtd><Web-app> <Servlet> <Servlet-Name> action </servlet-Name> <Servlet-class> org. Apache. Struts. Action. actionservlet </servlet-class> <Init-param> <Param-Name> config </param-Name> <Param-value>/WEB-INF/struts-config.xml </param-value> </Init-param> <Init-param> <Param-Name> debug </param-Name> <Param-value> 2 </param-value> </Init-param> <Init-param> <Param-Name> detail </param-Name> <Param-value> 2 </param-value> </Init-param> <Load-on-startup> 2 </load-on-startup> </Servlet> <Servlet-mapping> <Servlet-Name> action </servlet-Name> <URL-pattern> *. DO </url-pattern> </Servlet-mapping> <! -- The usual welcome file list --> <Welcome-file-List> <Welcome-File> index. jsp </welcome-File> </Welcome-file-List> <! -- Struts tag library descriptors --> <Taglib> <Taglib-Uri>/tags/Struts-bean </taglib-Uri> <Taglib-location>/WEB-INF/struts-bean.tld </taglib-location> </Taglib> <Taglib> <Taglib-Uri>/tags/Struts-HTML </taglib-Uri> <Taglib-location>/WEB-INF/struts-html.tld </taglib-location> </Taglib> <Taglib> <Taglib-Uri>/tags/Struts-logic </taglib-Uri> <Taglib-location>/WEB-INF/struts-logic.tld </taglib-location> </Taglib> <Taglib> <Taglib-Uri>/tags/Struts-nested </taglib-Uri> <Taglib-location>/WEB-INF/struts-nested.tld </taglib-location> </Taglib> <Taglib> <Taglib-Uri>/tags/Struts-tiles </taglib-Uri> <Taglib-location>/WEB-INF/struts-tiles.tld </taglib-location> </Taglib> </Web-app> |
Iv. hibernate Configuration
Download and copy
Hibernate2.jar Commons-beanutils.jar Commons-collections.jar Commons-dbcp.jar Commons-lang.jar Commons-logging.jar Commons-pool.jar Dom4j. Jar Cglib-asm.jar Connector. Jar |
Go to the/lib directory of the application site. Next, configure the hibernate. cfg. xml file.
<? XML version = '1. 0' encoding = 'utf-8'?> <! Doctype hibernate-Configuration Public "-// hibernate/hibernate configuration DTD // en" Http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd> <Hibernate-configuration> <Session-factory><Property name = "hibernate. Connection. url"> JDBC: mysql: // localhost: 3306/yourdatabase </Property> <Property name = "hibernate. Connection. driver_class"> Org. gjt. Mm. MySQL. Driver </Property> <Property name = "hibernate. Connection. username"> Yourname </Property> <Property name = "hibernate. Connection. Password"> Youyrpassword </Property> <!? -Whether to output SQL statements generated during runtime to logs for debugging --> <Property name = "show_ SQL"> false </property> <! -- Dialect, each database has its corresponding dialet to match its platform features --> <Propertyname = "dialect"> net. SF. hibernate. dialect. mysqldialect </property> <!? -Transaction management type. Here we use JDBC transaction --> <Property name = "transaction. factory_class"> Net. SF. hibernate. transaction. jdbctransactionfactory </property> <Property name = "JDBC. batch_size"> 10 </property> <Property name = "JDBC. use_scrollable_resultset"> true </property> <!? Ing file configuration. Note that the configuration file name must contain its full path relative to the root --> <Mapping Resource = "net/seerlog/HBM/cat. HBM. xml"/> </Session-factory> </Hibernate-configuration> |
The address, user name, and password used for database connection are configured above. For more information about the parameters, see the official documentation.
The content of the ing file can be manually written or automatically generated using some tools.
Two types of files are required :. HBM. xml configuration file and. java persistence object, the two are interrelated ,. HBM. XML ing to the database is also required. java Bean. Therefore, we need to first design the database, then export the. HBM. xml file based on the database, and then export the. Java file. There are many tools to implement this project. Here we use middlegen-hibernate to implement the database. HBM. XML file conversion is implemented using hbm2java in the hibernate-extension toolkit. HBM. XML. conversion of java files!
Search Keyword "! Entity ", get:
<! Doctype project [ <! Entity Database System "File:./config/database/HSQLDB. xml"> ]> |
B) Application name
<Property name = "name" value = "Airline"/> |
C) output directory
Find the keyword "name =" build. gen-src.dir "" And get:
<Property name = "build. gen-src.dir" value = "$ {build. dir}/Gen-Src"/> |
D) package name of the Code
<Hibernate Destination = "$ {build. gen-src.dir }" Package = "$ {name}. hibernate" Genxdoclettags = "false" Genintergratedcompositekeys = "false" Javatypemapper = "middlegen. plugins. hibernate. hibernatejavatypemapper" /> |
After the configuration is complete, run ant in the middlegen root directory, and the middlegen interface will appear:
Select the expected table and click Generate at the top of the window. middlegen generates the hibernate ing file corresponding to these database tables.
The following work is completed through hibernate extension. The tools/bin directory of hibernate extension contains three tools:
1. hbm2java. bat
Generate the corresponding pojo Based on the ing file. We have obtained the ing file through middlegen. The next step is to generate the corresponding pojo through the hbm2java. Bat tool.
2. class2hbm. bat
This tool is rarely used to generate a ing File Based on pojo class, so we will not detail it here.
3. ddl2hbm. bat
The database exports the warehouse table structure and generates the ing file and pojo. This function overlaps with the middlegen function, but because it is not mature enough (in fact it has been deprecated and is not maintained), it provides limited functions, so we still use middlegen to generate a ing file, then, hbm2java generates pojo Based on the ing file.
Here we use the first hbm2java. BAT and use the. HBM. xml file generated just now to automatically generate a Java file.
To use this tool, first we need to configure some parameters to open tools/bin/setenv. modify the jdbc_driver and hibernate_home environment variables to point them to the actual JDBC driver file and hibernate directory. Check whether each project in the environment variable CP exists, especially the JAR file under % corelib %, in some release packages, the file name in the default configuration is different from the actual file name (for example, % corelib %/commons-logging.jar, In the hibernate release package, the actual file name may be a commons-logging-1.0.3.jar, and so on ).
Use hbm2java to generate Java code based on the miing file generated by middlegen:
Open command window and run the following command in the tools/bin directory:
Hbm2java C:/sample/org/hibernate/sample/*. xml -- output = C:/sample/
After the preceding steps, all the basic configuration files are generated. Then you can initialize these configurations.
Practice
In this section, we need to configure a complete application configuration. In fact, every one of them can write a book, but I only focus on my own summary. In the future, I will continue to write down the lessons learned.
1. log4j Initialization
Configure log4j. Properties
### Direct log messages to stdout ### # Log4j. appender. stdout = org. Apache. log4j. leleappender # Log4j. appender. stdout. Target = system. Out # Log4j. appender. stdout. layout = org. Apache. log4j. patternlayout % C {1 }:% L-% m % N # Log4j. appender. stdout. layout. conversionpattern = %-5 p % d {yyyy-mm-dd hh: mm: SS} % L % N % m % N Log4j. Logger. seerlog = debug, A2 Log4j. appender. A2 = org. Apache. log4j. dailyrollingfileappender Log4j. appender. a2.file = D: // log // applog.txt Log4j. appender. a2.datepattern = '. 'yyyy-mm-dd Log4j. appender. a2.layout = org. Apache. log4j. patternlayout Log4j. appender. a2.layout. conversionpattern = %-5 p % d {yyyy-mm-dd hh: mm: SS} % m % N# Log4j. Logger. All = debug, A1 Log4j. appender. A1 = org. Apache. log4j. dailyrollingfileappender Log4j. appender. a1.file = D: // log // All. Log Log4j. appender. a1.datepattern = '. 'yyyy-mm-dd Log4j. appender. a1.layout = org. Apache. log4j. patternlayout Log4j. appender. a1.layout. conversionpattern = %-5 p % d {yyyy-mm-dd hh: mm: SS} % L % N % m % N ### Direct messages to file hibernate. Log ### # Log4j. appender. File = org. Apache. log4j. fileappender # Log4j. appender. file. File = hibernate. Log # Log4j. appender. file. layout = org. Apache. log4j. patternlayout # Log4j. appender. file. layout. conversionpattern = % d {absolute} % 5 P % c {1}: % L-% m % N ### Set log levels-for more verbose logging change 'info' to 'debug '### ### Log4j. rootlogger = warn, stdout Log4j. rootlogger = info, A1 # The following configurations are required for hibernate APIs: Log4j.logger.net. SF. hibernate = info ### Log just the SQL # Log4j.logger.net. SF. hibernate. SQL = debug ### Log JDBC bind parameters ### Log4j.logger.net. SF. hibernate. type = info ### Log schema export/update ### Log4j.logger.net. SF. hibernate. tool. hbm2ddl = debug ### Log cache activity ### # Log4j.logger.net. SF. hibernate. cache = debug ### Enable the following line if you want to track down connection ### ### Leakages when using drivermanagerconnectionprovider ### # Log4j.logger.net. SF. hibernate. Connection. drivermanagerconnectionprovider = TRAC |
After the configuration is called, first initialize the configuration file. This process only takes one time, so we can do it in servletcontextlistener.
String prefix = context. getrealpath ("/"); Propertyconfigurator. Configure (prefix + "/WEB-INF/classes/log4j. properties "); |
Here, you need the path of your configuration file for initialization.
After Initialization is complete, we can call it in future actions as follows:
Static logger log = logger. getlogger ("seerlog "); Log. Warn ("It's log4j warn "); Log.info ("It's log4j Info "); |
The full use of log4j will be explained in detail later!
Ii. hibernate Initialization
First, we need to put hibernate. cfg. XML in the application's classes directory, and then we can use the example provided in the hibernate reference document to encapsulate the background usage.
Public class Hi { Private Static final sessionfactory; Private Static connection conn; Static { Try { Sessionfactory = new configuration (). Configure (). buildsessionfactory (); } Catch (hibernateexception ex ){ Throw new runtimeexception ("exception building sessionfactory:" + ex. getmessage (), Ex ); } } Public static final threadlocal session = new threadlocal (); Public static session getsession () throws hibernateexception { Session S = (Session) Session. Get (); // If no thread is available, start a new session, If (S = NULL ){ Conn = dbconnectionmanager. getconnection (); S = sessionfactory. opensession (conn ); Session. set (s ); } Return S; } Public static void closesession () throws hibernateexception { Session S = (Session) Session. Get (); Session. Set (null ); If (s! = NULL) S. Close (); If (Conn! = NULL) Dbconnectionmanager. returnconnection (conn ); } } |
In this article, dbconnectionmanager. getconnection () is a DAO class that provides the implementation of the connection pool.
We use this con connection to create a session. sission is a session cycle for database connection operations. It provides powerful data management capabilities.
Later, we can use hi. getsession () in the Action execute method to obtain a session support. Typical applications are as follows:
Try { // Start a session and start the transaction rollback capability Session session = Hi. getsession (); Transaction Tx = session. begintransaction ();// Query the database using hql Query q = session. createquery ("from topic as topic order by topic. id desc "); Q. setfirstresult (0 ); Q. setmaxresults (5 ); // Obtain a list type data. List newtopiclist = Q. List (); // Business processing Newtopiclist ntlbean = new newtopiclist (); Ntlbean. setlist (newtopiclist ); Req. setattribute ("newtopiclist", ntlbean ); // Commit a transaction. Remember to close the session! TX. Commit (); Hi. closesession (); } // Because the entire session throws an exception, you need to use try -- catch to wrap it. Catch (hibernateexception e ){ // Log records Log. Error (E. tostring ()); } |
For more information about hql, see the official hibernate documentation.
Iii. Struts
Struts configuration file struts-config.xml placed under the application/WEB-INF/directory, the general configuration is as follows
<? XML version = "1.0" encoding = "ISO-8859-1"?> <! Doctype Struts-config public "-// Apache Software Foundation // DTD struts configuration 1.0 // en" Http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd> <Struts-config><Form-beans> <Form-bean name = "loginform" type = "net. seerlog. VO. loginform"/> <Form-bean name = "replyform" type = "net. seerlog. VO. replyform"/> </Form-beans> <Global-forwards> <Forward name = "Index" Path = "/first. jsp"/> </Global-forwards> <Action-mappings> <Action Path = "/login" type = "net. seerlog. Action. loginaction" Scope = "request" name = "loginform" input = "/login. jsp"> <Forward name = "success" Path = "/success. jsp"/> </Action> <Action Path = "/blog" type = "net. seerlog. Action. blogaction" Scope = "request"> <Forward name = "success" Path = "/sublog. jsp"/> </Action> <Action Path = "/topic" type = "net. seerlog. Action. topicaction" Scope = "request"> <Forward name = "success" Path = "/sutopic. jsp"/> </Action> <Action Path = "/posttopic" type = "net. seerlog. Action. posttopicaction" Scope = "request"> </Action> <Action Path = "/postreply" type = "net. seerlog. Action. postreplyaction" Scope = "request" name = "replyform" input = "/sublog. jsp"> </Action> <Action Path = "/Index" type = "net. seerlog. Action. indexaction" Scope = "request"> </Action> </Action-mappings> <Message-resources parameter = "resouse. Application"> </Message-resources> </Struts-config> |
The configuration here has a visualization tool called Struts-console. The current version is 4.8. You can download it online for free.
You do not need to remember the configuration file. If you need it, copy one and modify it. But here we mainly focus on designing, designing formbean, action, their relationships, and so on. A good design can definitely save a lot of rework possibilities in the future. Struts has a "struts on action", which is definitely a classic book for learning struts. I have translated the first eight chapters. If you need it, contact me.
We will not describe each configuration here. We will only talk about the process of cooperation between struts and hibernate.
An action has an execute method. Of course, the perform method can also be used. However, the perform method is not recommended in struts1.1, but a more powerful execute () method is used. Package net. seerlog. Action;
// Import all used packages Import java. util. List;Import net. seerlog. Po .*; Import net. seerlog. VO .*; Import net. seerlog. util .*; Import net. SF. hibernate .*; Import org. Apache. Struts. Action .*; Import javax. servlet .*; Import javax. servlet. http .*; Import java. Io. ioexception; Import javax. servlet. servletexception; Public class indexaction extends action { // Execute the main method of action. Note that an exception should be thrown. Public actionforward execute (actionmapping mapping, actionform form, httpservletrequest req, Httpservletresponse res) throws ioexception, servletexception { Try { // Enable session Session session = Hi. getsession (); Transaction Tx = session. begintransaction (); // Query Query q = session. createquery ("from topic as topic order by topic. id desc "); Q. setfirstresult (0 ); Q. setmaxresults (5 ); List newtopiclist = Q. List (); Newtopiclist ntlbean = new newtopiclist (); Ntlbean. setlist (newtopiclist ); Req. setattribute ("newtopiclist", ntlbean ); // Commit a transaction and close the session TX. Commit (); Hi. closesession (); // Capture exceptions } Catch (hibernateexception e ){ Log. Error (E. tostring (); // log record } // Returns an actionforward object Return Mapping. findforward ("Index "); } } |
The above is all about struts and hibernate collaborative work. This article only allows you to understand the entire process. The example here cannot be used as an implementation learning example.