Spring + springmvc + hibernate integrated instance, springmvchib.pdf

Source: Internet
Author: User

Spring + springmvc + hibernate integrated instance, springmvchib.pdf

In the previous blog, I wrote about the integration of spring and springmvc, and added hibernate to this article.

Like the previous one, this time is still a pilot jar package. This time, you need to add the jar package in hibernate, as shown in:

Create two source folders, config and test, respectively, to store the configuration files and test cases. Now configure spring, springmvc, and hibernate.

New spring-hibernate.xml, applicationContext. xml, springmvc. xml, hibernate. cfg. xml four configuration files, now to configure these four configuration files.

Spring-hibernate.xml:

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE beans PUBLIC "-// SPRING // dtd bean 2.0 // EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [<! ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude. xml ">]> <beans> <bean id =" dataSource "class =" org. springframework. jdbc. datasource. driverManagerDataSource "> <property name =" driverClassName "value =" com. mysql. jdbc. driver "> </property> <property name =" url "value =" jdbc: mysql: // localhost: 3306/contacts "> </property> <property name =" username "value =" root "/> <property name =" pass Word "value =" root "/> </bean> <bean id =" sessionFactory "class =" org. springframework. orm. hibernate3.LocalSessionFactoryBean "> <property name =" dataSource "ref =" dataSource "> </property> <property name =" hibernateProperties "> <props> <prop key =" hibernate. dialect "> org. hibernate. dialect. mySQLDialect </prop> <prop key = "show_ SQL"> true </prop> <prop key = "hibernate. show_ SQL "> true </prop> <prop key =" hiberante. format_ SQL "> t Rue </prop> </props> </property> <property name = "configLocations"> <list> <value> classpath: hibernate. cfg. xml </value> </list> </property> <! -- Annotation scan package --> <! -- <Property name = "annotatedClasses"> <list> <value> </list> </property> --> </bean> <bean id = "transactionManager" class = "org. springframework. orm. hibernate3.HibernateTransactionManager "> <property name =" sessionFactory "ref =" sessionFactory "> </property> </bean> <bean id =" transactionBese "class =" org. springframework. transaction. interceptor. transactionProxyFactoryBean "abstract =" true "lazy-init =" true "> <property name =" transactionManager "ref =" transactionManager "> </property> <property name =" transactionAttributes "> <props> <prop key = "save *"> PROPAGATION_REQUIRED, -Exception </prop> <prop key = "update *"> PROPAGATION_REQUIRED,-Exception </prop> <prop key = "delete *"> PROPAGATION_REQUIRED, -Exception </prop> </props> </property> </bean> <bean id = "hibernateTemplate" class = "org. springframework. orm. hibernate3.HibernateTemplate "> <property name =" sessionFactory "> <ref bean =" sessionFactory "> </ref> </property> </bean> </beans>

ApplicationContext. xml:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">]><beans><import resource="spring-hibernate.xml"></import><bean id="userDao" class="cn.com.dao.impl.UserDaoImpl"><property name="hibernateTemplate" ref="hibernateTemplate"></property></bean><bean id="userService" class="cn.com.service.impl.UserServiceImpl"><property name="userDao" ref="userDao"></property></bean></beans>
Springmvc. xml:

<? 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: mvc = "http://www.springframework.org/schema/mvc" xmlns: context = "http://www.springframework.org/schema/context" xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: tx = "http://www.springframework.org/schema/tx" xsi: schemaLocation = "http://www.springframework.org/schema/beans http :/ /Www.springframework.org/schema/beans/spring-beans-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/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 Mework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "> <! -- Mvc annotation driver --> <mvc: annotation-driven/> <! -- Once the scanner definition mvc: annotation-driven is not required, the scanner has the annotation-driven function --> <context: component-scan base-package = "cn.com. controller "/> <! -- Prefix + viewName + suffix --> <beanclass = "org. springframework. web. servlet. view. InternalResourceViewResolver"> <! -- Webroot path to a specified folder --> <property name = "prefix" value = "/WEB-INF/jsps/"> </property> <! -- View name suffix --> <property name = "suffix" value = ". jsp"> </property> </bean> <! -- Id = "multipartResolver" must be multipartResolver --> <bean id = "multipartResolver" class = "org. springframework. web. multipart. commons. CommonsMultipartResolver"> <! -- MaxUploadSize: the maximum size for file upload is byte. --> <property name = "maxUploadSize" value = "1024000"> </property> </bean> </beans>

The hibernate ing file is:

<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

Now configure in web. xml:

<? 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" xmlns: web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id = "WebApp_ID" version = "2.5"> <context-param> <param-name> contextConfigLocation </param-name> <param-value> classpath: applicationConte Xt. xml </param-value> </context-param> <! -- Configure spring to start listener entry --> <listener-class> org. springframework. web. context. ContextLoaderListener </listener-class> </listener> <! -- Configure springmvc to start the dispatcherServlet entry --> <! -- Central controller --> <servlet-name> springMVC </servlet-name> <servlet-class> org. springframework. web. servlet. dispatcherServlet </servlet-class> <init-param> <param-name> contextConfigLocation </param-name> <param-value> classpath: springmvc. xml </param-value> </init-param> <load-on-startup> 1 </load-on-startup> </servlet> <filter-name> encodingFilter </filter-name> <filter-class> org. springframework. web. filter. C HaracterEncodingFilter </filter-class> <init-param> <param-name> encoding </param-name> <param-value> UTF-8 </param-value> </init- param> <init-param> <param-name> forceEncoding </param-name> <param-value> true </param-value> </init-param> </filter> <! -- Encoding filter for jsp page --> <filter-mapping> <filter-name> encodingFilter </filter-name> <url-pattern>/* </url-pattern> </ filter-mapping> <servlet-name> springMVC </servlet-name> <! -- Struts is used to/* and does not work in springmvc --> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
Start the programming process now:

User class:

package cn.com.domain;import java.io.Serializable;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;import org.hibernate.annotations.GenericGenerator;public class Users implements Serializable {private String id;private String name;private String pwd;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}}
The corresponding User. hbm. xml configuration file is:

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

IUserDao:

package cn.com.dao;import cn.com.domain.Users;public interface IUserDao {public void addUser(Users user);public void updateUser(Users user);}
IUserDaoImpl:

package cn.com.dao.impl;import org.springframework.orm.hibernate3.HibernateTemplate;import cn.com.dao.IUserDao;import cn.com.domain.Users;public class UserDaoImpl implements IUserDao {private HibernateTemplate hibernateTemplate;public HibernateTemplate getHibernateTemplate() {return hibernateTemplate;}public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {this.hibernateTemplate = hibernateTemplate;}public void addUser(Users user) {this.hibernateTemplate.save(user);}public void updateUser(Users user) {this.hibernateTemplate.update(user);}}
IUserService:

package cn.com.service;import cn.com.domain.Users;public interface IUserService {public void addUser(Users users);public void updateUser(Users user);}
IUserServiceImpl:

package cn.com.service.impl;import cn.com.dao.IUserDao;import cn.com.domain.Users;import cn.com.service.IUserService;public class UserServiceImpl implements IUserService {private IUserDao userDao;public void addUser(Users users) {this.userDao.addUser(users);}public IUserDao getUserDao() {return userDao;}public void setUserDao(IUserDao userDao) {this.userDao = userDao;}public void updateUser(Users user) {this.userDao.updateUser(user);}}
A tool class:

ServiceProvinderCore:

Package cn.com. container; import org. springframework. context. applicationContext; import org. springframework. context. support. classPathXmlApplicationContext;/*** the main purpose of this class is to load the spring configuration file * @ author Administrator **/public class ServiceProvinderCore {protected ApplicationContext context; public void load (String filename) {context = new ClassPathXmlApplicationContext (filename );}}

ServiceProvinder:

Package cn.com. container; import org. springframework. util. stringUtils; public class ServiceProvinder {private static ServiceProvinderCore SC; static {SC = new ServiceProvinderCore (); SC. load ("applicationContext. xml ");} public static Object getService (String beanName) {Object bean = null; if (! StringUtils. hasText (beanName) {throw new RuntimeException ("the service name you want to access cannot be blank! ");} // If the spring container contains beanNameif (SC. context. containsBean (beanName) {bean = SC. context. getBean (beanName);} // If the spring container does not contain beanNameif (bean = null) {throw new RuntimeException ("the service name you want to access [" + beanName + "] does not exist") ;}return bean ;}}
Controller UserController:

package cn.com.controller;import java.util.UUID;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import cn.com.container.ServiceProvinder;import cn.com.dao.IUserDao;import cn.com.domain.Users;import cn.com.service.IUserService;@Controller@RequestMapping("/user")public class UserController {@RequestMapping("/toSuccess.do")public String toSuccess(){System.out.println("success");return "success";}@RequestMapping("/toAdd.do")public String add(){return "add";}@RequestMapping("/toLogin.do")public String login(){return "login";}@RequestMapping("/toSave.do")public String save(Users user){System.out.println(user.getName());System.out.println(user.getPwd());String id=UUID.randomUUID().toString().replace("-", "").substring(0,4);user.setId(id);ServiceProvinder provinder=new ServiceProvinder();IUserService userDao=(IUserService) provinder.getService("userService");userDao.addUser(user);return "success";}}
In the compilation of these packages and various classes, the overall structure is:

Now let's test:

Add. jsp

After clicking submit:

The jsp page turns:

Integration completed successfully.

Here, we use xml configuration files for development. It is simpler to use annotations.

Spring + springmvc + hibernate integration.



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.