Spring 3 + hibernate 3 + spring MVC integration entry

Source: Internet
Author: User

Project directory structure:

Project Structure
Step 1: Prepare the jar package


The above are all jar packages required by springmvc + hibernate.
Copy all jar packages to the lib directory of the web project.
Step 2: configure the file

Copy and modify files From Hibernate
First, go to the ETC folder from the project folder in Hibernate and copy the two files to the classpath folder,

Figure 2-1

## HypersonicSQLdataSource.password=dataSource.username=rootdataSource.databaseName=testdataSource.driverClassName=com.mysql.jdbc.DriverdataSource.dialect=org.hibernate.dialect.MySQL5DialectdataSource.serverName=localhost:3306dataSource.url=jdbc:mysql://localhost:3306/testdataSource.properties=user=${dataSource.username};databaseName=${dataSource.databaseName};serverName=${dataSource.serverName};password=${dataSource.password}dataSource.hbm2ddl.auto=update#hibernate.connection.url jdbc:hsqldb:hsql://localhost#hibernate.connection.url jdbc:hsqldb:test

Figure 2-2
Modify the hibernate. properties File
As follows:

Modify the log4j. properties File
As follows:

log4j.rootLogger=warn, stdout#log4j.logger.org.hibernate=info#log4j.logger.org.hibernate=debug

If the above two files are not posted, they are not modified.
Compile the spring configuration file
Create an applicationcontext. xml file
The content of the new applicationcontext. xml file under classpath is as follows:

<? XML version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" 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/aop 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-S Can base-package = "com. MVC"/> <! -- Support AOP annotation --> <AOP: aspectj-autoproxy/> <context: Property-placeholder location = "classpath:/hibernate. properties "/> <bean id =" datasource "class =" org. springframework. JDBC. datasource. drivermanagerdatasource "> <property name =" driverclassname "value =" $ {datasource. driverclassname} "/> <property name =" url "value =" $ {datasource. URL} "/> <property name =" username "value =" $ {datasource. username} "/> <Property Name = "password" value = "$ {datasource. password} "/> </bean> <bean id =" sessionfactory "class =" org. springframework. orm. hibernate3.annotation. annotationsessionfactorybean "> <property name =" datasource "ref =" datasource "/> <property name =" hibernateproperties "> <props> <prop key =" hibernate. dialect ">$ {datasource. dialect} </prop> <prop key = "hibernate. hbm2ddl. auto "> $ {datasource. hbm2ddl. auto} </prop> <prop key = "Hibernate. hbm2ddl. auto "> Update </prop> </props> </property> <property name =" packagestoscan "> <list> <value> COM. MVC. model </value> <! -- Scan the object class, that is, the model --> </List> </property> </bean> <bean id = "hibernatetemplate" class = "org. springframework. orm. hibernate3.hibernatetemplate "> <property name =" sessionfactory "ref =" sessionfactory "> </property> </bean> <! -- Configure Transaction Management --> <bean id = "txmanager" class = "org. springframework. orm. hibernate3.hibernatetransactionmanager "> <property name =" sessionfactory "ref =" sessionfactory "> </property> </bean> <TX: annotation-driven transaction-Manager = "txmanager"/> <AOP: config> <AOP: pointcut expression = "execution (Public * COM. MVC. service. impl. *. *(..)) "id =" businessService "/> <AOP: Advisor advice-ref =" txadvice "pointcut-ref =" Bu Sinessservice "/> </AOP: config> <TX: Advice id =" txadvice "transaction-Manager =" txmanager "> <TX: Attributes> <TX: method Name = "find *" Read-Only = "true" propagation = "not_supported"/> <! Methods Starting with -- get do not need to be run in transactions. In some cases, there is no need to use transactions, such as getting data. Starting a transaction has a certain impact on the performance --> <TX: method name = "*"/> <! -- Run other methods in practice --> </TX: Attributes> </TX: Advice> </beans>

Creating a spring-servlet.xml File
Create a spring-servlet.xml file under Web-INF with the following content:

<? XML version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: P = "http://www.springframework.org/schema/p" xmlns: MVC = "http://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 HT TP: // 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd "> <! -- Scan all classes in the Web package to create beans and automatically inject dependencies --> <context: component-scan base-package = "com. MVC. web "/> <MVC: annotation-driven/> <! -- Support spring3.0 new MVC annotation --> <! -- Start the annotation function of spring MVC to map requests and pojo annotations --> <Bean class = "org. springframework. Web. servlet. MVC. annotation. annotationmethodhandleradapter"/> <! -- Resolve the Model View name, that is, add the prefix suffix --> <Bean class = "org. springframework. web. servlet. view. internalresourceviewresolver "P: prefix ="/WEB-INF/JSP/"P: suffix = ". JSP "> <! -- If jstl is used, configure the following attributes --> <property name = "viewclass" value = "org. springframework. web. servlet. view. jstlview "/> </bean> </beans>

Modify the Web. xml file
The file content is as follows:

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5"    xmlns="http://java.sun.com/xml/ns/javaee"    xmlns: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-name>        <servlet-class>  org.springframework.web.servlet.DispatcherServlet        </servlet-class>        <init-param>       <param-name>contextConfigLocation</param-name>      <param-value>classpath:applicationContext*.xml,/WEB-INF/spring-servlet.xml</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>springmvc</servlet-name>        <url-pattern>*.do</url-pattern>    </servlet-mapping>    <welcome-file-list>        <welcome-file>index.*</welcome-file>        <welcome-file>reg.jsp</welcome-file>    </welcome-file-list></web-app>
Step 3: business logic

Model Layer
Create object class user. Java with the following content:

package com.mvc.model;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;@Entitypublic 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
Create userdao. Java with the following content:
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.getName());        if (list.size() > 0) {            return true;        }        return false;    }    public boolean userLogin(User u) {        List<?> list = hibernateTemplate.find(                "from User u where u.name=? and u.password=?", u.getName(),                u.getPassword());        if (list.size() > 0) {            return true;        }        return false;    }}

Service Layer
Create userservice. Java with the following content:

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)
Create usercontroler. Java with the following content:

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; @ requestmapping (Params =" method = reg ") Public String Reg (User user) {system. out. println ("User 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 ("User Logon"); If (userservice. login (User) {return "log_success";} return "log_fail ";}}

View Layer
Create two JSP files in webcontent: Reg. jsp and log. jsp.
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"> <HTML> 

Create four JSP files in the/Web-INF Folder: reg_fail, reg_success, log_fail, and log_success. Only make some simple prompts in the 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"> <HTML> 

The other three will only change the prompt content in the body and will not be mentioned here.
Step 4: Test

Enable Server
Open Tomcat server

Browse in a browser

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.