"Struts2+hibernate4" uses Hibernate to query the database according to MVC, and uses the OGNL expression output in the foreground

Source: Internet
Author: User
Tags object object

This article will introduce the integration of STRUTS2 and Hibernate, the integration of two things do not need to use spring, completely can do their own duties, Struts2 complete the Java file and JSP page interaction, hibernate to complete the database to Java file interaction.


I. BASIC OBJECTIVES

Or the TestTable table that was used in MySQL.


After index.jsp click on the query, you can output all the contents of this table. And the table is the different colors of the plum blossom between bamboo. Of course, this example has been said in many books.


The directory structure is as follows, in strict accordance with MVC idea.



II. Basic Preparation

1, here is no longer said, in the eclipse for Java EE a new Web project, the Struts2 must be the necessary package, specifically refer to the "Struts2" Struts2 Pure manual installation, configuration and HelloWorld to the latest version of Struts 2.3.20 GA Example "(Click to open link) with hibernate necessary package, specifically can refer to" Hibernate "hibernate in Eclipse+mysql configuration, installation, pure Java, Use annotation and hql to complete the database additions and deletions (click the Open link) to the Lib directory under the Web-inf folder. The last Lib folder is as follows:


2, after the Web. Xml only need to be equipped with STRUTS2, Hibernate is a Java plug-in, there is a package can be used. No configuration required, specifically as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "version=" 3.0 "><filter><filter-name>struts2</ filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter</ filter-class></filter><filter-mapping><filter-name>struts2</filter-name>< Url-pattern>/*</url-pattern></filter-mapping></web-app>


Third, the production process

1, first write good long-lasting layer m bar. Hibernate.cfg.xml and "Hibernate" hibernate in the SRC root directory, the Hibernate4.3 of the initialization of the new code (Click to open link) The only difference is that the last line indicates that the map of the test table is Java Test.model.TestTable.java. Instead of Testtable.java in the root directory:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http://www.hibernate.org/ DTD/HIBERNATE-CONFIGURATION-3.0.DTD ">

As for Testtable.java is not changed, testtable or that Testtable.java, just because this is in the Web project Test.model package, so the beginning of a package name.

Package Test.model;import javax.persistence.*, @Entity @table (name = "TestTable") public class TestTable {private int id; The private string Username;private string number;//represents the primary key with the auto-generated item @id@generatedvaluepublic int getId () {return Id;} public void setId (int id) {this.id = ID;} @Column (name = "username") public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} @Column (name = "number") public String GetNumber () {return number;} public void Setnumber (String number) {this.number = number;} @Overridepublic String toString () {return id + "," + Username + "," + Number;}}
2, also has not changed the database service class Dbdao.java, the database service completely through the HQL statement operation, after the direct use of the method in this class can be. No longer need to take care of hibernate in the bizarre execution of the session initialization problem, no longer a bunch of statements, just to initialize the session.

Package Test.model;import Org.hibernate.*;import Org.hibernate.cfg.*;import org.hibernate.service.*;import Org.hibernate.boot.registry.*;p Ublic class Dbdao {Private Session session;//constructor, initialize session, equivalent to connect database public Dbdao () {/ /Here is the use of the Hibernate4.3.8, hibernate here and the initialization method has been modified, very painful configuration cfg = new configuration (). Configure (); Serviceregistry serviceregistry = new Standardserviceregistrybuilder (). Applysettings (Cfg.getproperties ()). build (); Sessionfactory sessionfactory = cfg.buildsessionfactory (serviceregistry); this.session = SessionFactory.openSession ( );} Execute Query Public query query (String hql) {return session.createquery (HQL);}  Execute INSERT, modify public void Save (Object object) {Transaction transaction=session.begintransaction (); Session.save (object); Transaction.commit (); }//Execute Delete public void Delete (Object object) {Transaction transaction=session.begintransaction (); Session.delete (object) ; Transaction.commit (); }//destructor, interrupt session, equivalent to interrupt database connection protected void Finalize () throws Exception {if (session.isconnected () | | Session! = NULL) {Session.close ();}}}
3, then to write C-layer. The Struts.xml is created and configured in SRC first, indicating that the action of query is executed by Test.action.query.java

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts public        "-//apache software foundation//dtd struts Configuration 2.0//en"        

4. Query.java is the only action class of the C layer in this Web project, and of course the core action class. No need to come up with any data. Directly like the "Hibernate" Hibernate level division, the Hibernate4.3 of the initialization of the new wording (Click Open link) Hql.java,java and database interaction, the introduction of the entire package Test.model, which contains testtable class and database business logic Dbdao.java, directly with the HQL statement to the TestTable class query out the entire testtable table. and press it into a list dynamic array testtablelist, which holds the TestTable class, and pushes it to the foreground using getter methods. Of course, the setter method can be completely no, just use eclipse incidentally generated.

Package Test.action;import Test.model.*;import java.util.*;//This is the Struts2 necessary support import com.opensymphony.xwork2.actionsupport;//prevent the serial number warning @suppresswarnings ("serial")//Struts2 must inherit this class public classes query Extends Actionsupport {private list<testtable> testtablelist;//prevent JDK1.5 of generic warning @suppresswarnings ("unchecked") Public String Run () {Dbdao db = new Dbdao (), testtablelist = Db.query ("from TestTable"). List (); return "Success";} Eclipse automatically generates public list<testtable> Gettesttablelist () {return testtablelist;} public void Settesttablelist (list<testtable> testtablelist) {this.testtablelist = Testtablelist;}}

5, the last is the V layer, on a index.jsp, applied to the OGNL expression, notice in the beginning to introduce the S-tag, this thing and jstl expression is the C tag "Servlet" Using Servlet3.0 Standard and JSTL expression to implement file upload system, support image upload display (Click to open link) no difference, but note in the equivalent of <c:if> <s:if> incompatible El expression "filter" using filter filter to solve the coding problem of post transmission and the use of El expression to simplify the transfer of parameters (Click to open the link), the inside can only be <s:if> own things, the other S tags can be. The first is to determine if Testtablelist has a value, because when the user does not have a point to query the hyperlink, it should not output testtablelist this table at all. Then use the equivalent of <c:foreach> <s:iterator> output the whole sheet. The output is judged by whether it is a single row, and if so, the background color of this column is gray.

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><%@ taglib prefix=" s "uri="/struts-tags "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >


Iv. Summary and Prospect

Struts2+hibernate4 The MVC idea used throughout the development process is exactly the same as the "Servlet" Design user login, user registration, and change of password system according to the MVC idea (click the Open link). Just as jquery is the framework of JavaScript. Struts2+hibernate4 can do things jsp/jstl+servlet+jdbc can do.

"Struts2+hibernate4" uses Hibernate to query the database according to MVC, and uses the OGNL expression output in the foreground

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.