Spring 3 + Hibernate 3 + spring MVC Integration Primer __java

Source: Internet
Author: User
Tags aop tomcat server log4j

Project directory structure diagram:


Project Structure Chart
Step one: Prepare Jar packs
These are the required jar packs for all springmvc+hibernate.
Copy all jar packages to the Lib directory of the Web project.
Step Two: The configuration file copies and modifies files from the hibernate
Start by hitting the ETC folder from the project folder in Hibernate, copying the two files shown in the figure to classpath, as in figure:


Figure 2-1

# # Hypersonicsql
datasource.password=
datasource.username=root
datasource.databasename=test
Datasource.driverclassname=com.mysql.jdbc.driver
Datasource.dialect=org.hibernate.dialect.mysql5dialect
datasource.servername=localhost:3306
datasource.url=jdbc:mysql://localhost:3306/test
Datasource.properties=user=${datasource.username};d atabasename=${datasource.databasename};servername=${ Datasource.servername};p Assword=${datasource.password}
datasource.hbm2ddl.auto=update
# Hibernate.connection.url jdbc:hsqldb:hsql://localhost
#hibernate. Connection.url jdbc:hsqldb:test


Figure 2-2
modifying hibernate.properties files
As follows:


modifying log4j.properties files
As follows:
Log4j.rootlogger=warn, stdout

#log4j. Logger.org.hibernate=info
#log4j. Logger.org.hibernate=debug


The above two documents did not post the expression does not change.
Writing the spring configuration file
New Applicationcontext.xml File
The contents of the new Applicationcontext.xml file under Classpath are as follows:
<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns:
    aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:p= "http://www.springframework.org/schema/p" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://www.springframework.org/schema/beans  Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context/spring-context-3.0.xsd Http://www.springframework.org/schema/ao P http://www.springframework.org/schema/aop/spring-aop-3.0.xsd Http://www.springframework.org/schema/tx http:/
    /www.springframework.org/schema/tx/spring-tx-3.0.xsd "> <context:component-scan base-package=" Com.mvc "/> <!--support AOP annotations--> &LT;AOP:ASPECTJ-autoproxy/> <context:property-placeholder location= "classpath:/hibernate.properties"/> <bean id= "D Atasource "class=" Org.springframework.jdbc.datasource.DriverManagerDataSource "> <property name=" driv
        Erclassname "value=" ${datasource.driverclassname} "/> <property name=" url "value=" ${datasource.url} "/> <property name= "username" value= "${datasource.username}"/> <property name= "password" value= Asource.password} "/> </bean> <bean id=" sessionfactory "class=" Org.springframework.orm.hibern Ate3.annotation.AnnotationSessionFactoryBean "> <property name=" dataSource "ref=" DataSource "/> &L T;property name= "Hibernateproperties" > <props> <prop key= "Hibernate.dialect" >${ datasource.dialect}</prop> <prop key= "Hibernate.hbm2ddl.auto" >${datasource.hbm2ddl.auto}</p
                Rop><prop key= "Hibernate.hbm2ddl.auto" >update</prop> </props> </property> <property name= "Packagestoscan" > <list> &LT;VALUE&GT;COM.MVC.MODEL&LT;/VALUE&GT;&L t;! --Scan entity class, which is usually said model--> </list> </property> </bean> <bean id= "Hibe Rnatetemplate "class=" org.springframework.orm.hibernate3.HibernateTemplate "> <property name=" sessionfactory
        "Ref=" Sessionfactory ></property> </bean> <!--configuration Transaction management--> <bean id= "Txmanager" class= "Org.springframework.orm.hibernate3.HibernateTransactionManager" > <property name= "sessionfactory" R ef= "Sessionfactory" ></property> </bean> <tx:annotation-driven transaction-manager= "Txmanager"/&
    Gt
            <aop:config> <aop:pointcut expression= "Execution (public * com.mvc.service.impl.*.* (..))" Id= "BusinessservicE "/> <aop:advisor advice-ref= txadvice" pointcut-ref= "Businessservice"/> </aop:config> &l T;tx:advice id= "Txadvice" transaction-manager= "Txmanager" > <tx:attributes> <tx:method Name = "find*" read-only= "true" propagation= "not_supported"/> <!--get Start method does not need to run in a transaction. In some cases there is no need to use transactions, such as obtaining data. Opening the transaction itself has a certain impact on performance--> <tx:method name= "*"/> <!--other methods run in practice--> </tx:attributes&
    Gt </tx:advice> </beans>


New Spring-servlet.xml File
Under Web-inf, create a new Spring-servlet.xml file with the following contents:
<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xmlns:mvc= "H" Ttp://www.springframework.org/schema/mvc "xmlns:context=" Http://www.springframework.org/schema/context "xmlns: Util= "Http://www.springframework.org/schema/util" xsi:schemalocation= "http://www.springframework.org/schema/ Beans Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/ Context Http://www.springframework.org/schema/context/spring-context-3.0.xsd Http://www.springframework.or G/SCHEMA/MVC http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/s Chema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd "> <!--scan all classes in the Web package. To complete the function of bean creation and automatic dependency injection--> &LT;CONTEXT:COMPONENT-SCAn base-package= "Com.mvc.web"/> <mvc:annotation-driven/> <!--support spring3.0 new MVC annotations--> <!--boot sp Ring MVC annotation Function, complete the mapping of request and annotation Pojo--> <bean class= " Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter "/> <!--parsing the model view name, That is, add the prefix--> <bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" to the Model view name P:pref ix= "/web-inf/jsp/" p:suffix= ". jsp" > <!--if you are using JSTL, configure the following properties--> <property name= "Viewclass" va Lue= "Org.springframework.web.servlet.view.JstlView"/> </bean> </beans>


modifying Web.xml files
The contents of the document are as follows:
<?xml version= "1.0" encoding= "UTF-8"?> <web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee" x Mlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http ://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "> <servlet> <servlet-name>springmvc</servlet-n
        ame> <servlet-class> Org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpa Th:applicationcontext*.xml,/web-inf/spring-servlet.xml</param-value> </init-param> <load-on -startup>1</load-on-startup> </servlet> <servlet-mapping> &LT;SERVLET-NAME&GT;SPRINGM vc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-f Ile-list> <weLcome-file>index.*</welcome-file> <welcome-file>reg.jsp</welcome-file> </welcome-file- List> </web-app>


Step three: business logicModel Layer
New entity class User.java, as follows:
Package Com.mvc.model;

Import javax.persistence.Entity;
Import Javax.persistence.GeneratedValue;
Import Javax.persistence.Id;

@Entity public
class User {
    private int id;
    private String name;
    private String password;

    @Id
    @GeneratedValue Public
    int getId () {return
        Id;
    }

    public void setId (int id) {
        this.id = ID;
    }

    Public String GetName () {return
        name;
    }

    public void SetName (String name) {
        this.name = name;
    }

    Public String GetPassword () {return
        password;
    }

    public void SetPassword (String password) {
        this.password = password;
    }
}


DAO layer
New Userdao.java, which reads as follows:
Package Com.mvc.dao;

Import java.util.List;

Import Javax.annotation.Resource;

Import org.springframework.orm.hibernate3.HibernateTemplate;
Import org.springframework.stereotype.Repository;

Import Com.mvc.model.User;

@Repository ("Userdao") public
class Userdao {
    @Resource
    private hibernatetemplate hibernatetemplate;

    public void Add (User u) {
        hibernatetemplate.save (U);
    }

    public boolean Finduser (User u) {
        list<?> List = Hibernatetemplate.find ("from User u where u.name=?",
                U.G Etname ());
        if (list.size () > 0) {return
            true;
        }
        return false;
    }

    public boolean userlogin (User u) {
        list<?> List = Hibernatetemplate.find (
                "from User u where u.name=?" U.password=? ", U.getname (),
                U.getpassword ());
        if (list.size () > 0) {return
            true;
        }
        return false;
    }
}


Service Layer
New Userservice.java, which reads as follows:
Package com.mvc.service;

Import Javax.annotation.Resource;

Import Org.springframework.stereotype.Service;

Import Com.mvc.dao.UserDao;
Import Com.mvc.model.User;

@Service ("UserService") public
class UserService {
    @Resource
    private Userdao Userdao;

    public void Add (user user) {
        userdao.add (user);
    }

    Public boolean exist (user user) {return
        userdao.finduser (user);
    }

    public boolean login (user user) {return
        userdao.userlogin (user);
    }
}


Controller layer (Action layer)
New Usercontroler.java, which reads as follows:
Package com.mvc.web;

Import Javax.annotation.Resource;

Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;

Import Com.mvc.model.User;
Import Com.mvc.service.UserService;

@Controller ("Usercontroller")
@RequestMapping ("/user.do") public
class Usercontroller {

    @Resource
    private UserService UserService;

    @RequestMapping (params = "Method=reg") Public
    String reg (user user) {
        System.out.println ("Subscriber Registration");
        if (userservice.exist (user)) {return
            "Reg_fail";
        }
        Userservice.add (user);
        return "reg_success";
    }

    @RequestMapping (params = "method=log") public
    String log (user user) {
        System.out.println ("Log On");
        if (userservice.login (user)) {return
            "log_success";
        }
        return "Log_fail";
    }


View Layer
Create a new two JSP files in WebContent, reg.jsp and log.jsp respectively.
The contents of reg.jsp are as follows:
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <!
DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >  


Create four JSP files in the/web-inf folder by creating a new JSP folder: Reg_fail, Reg_success, Log_fail, log_success. Only a few simple hints are made in four files.
LOG_FAIL.JSP:
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "
    pageencoding=" UTF-8 "%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >


The other three changes only in the body of the hint content, no longer described here.
Step Fourth: TestTurn on the server
Open the Tomcat server as shown in figure:

Browsing in the browser

As shown in figure:



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.