Spring-springmvc-hibernate Integration

Source: Internet
Author: User

Because you are not using MAVEN, look directly at the package structure! The follow-up may come with maven!

</pre><p></p><p> pack a bit more, but don't care about these details, more than less good. </p><p> See configuration file </p><p>spring-common.xml (equivalent to Applicationcontext.xml) </p><p> </p><pre name= "code" class= "HTML" ><?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:context=" http ://www.springframework.org/schema/context "xmlns:mvc=" Http://www.springframework.org/schema/mvc "xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd "><!--Configure Data source--><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/test "> </property><property name= "username" value= "root" ></property><property name= "password"Value= "root" ></property></bean><!--configuration sessionfactory--><bean id= "sessionfactory" class= " Org.springframework.orm.hibernate4.LocalSessionFactoryBean "><property name=" DataSource "ref=" DataSource " ></property><!--metabase dialect--><property name= "hibernateproperties" ><props><prop key= " Hibernate.dialect ">org.hibernate.dialect.mysqldialect</prop><prop key=" Hibernate.hbm2ddl.auto "> Update</prop><prop key= "Hibernate.show_sql" >true</prop><prop key= "Hibernate.format_sql" > True</prop></props></property><property name= "Packagestoscan" ><list><value> com.iss.model</value></list></property></bean><!--Configure a transaction manager--><bean id= " TransactionManager "class=" Org.springframework.orm.hibernate4.HibernateTransactionManager "><property name= "Sessionfactory" ref= "sessionfactory"/></bean><!--configuration transactions, using proxies--><bean id= "Transactionproxy" Class= "Org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract= "true" ><property Name= "TransactionManager" ref= "TransactionManager" ></property><property name= "TransactionAttributes" ><props><prop key= "add*" >propagation_required,-exception</prop><prop key= "modify*" > Propagation_required,-myexception</prop><prop key= "del*" >propagation_required</prop><prop key= "*" >PROPAGATION_REQUIRED</prop></props></property></bean></beans>

And one is SPRINGMVC's configuration file.

Spring-mvc.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:context= "Http://www.springframework.org/schema/context" Xmlns:mvc= "Http://www.springframework.org/schema/mvc" xsi:schemalocation= "Http://www.springframework.org/schema /beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/ contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/ Schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd "><!--Note Scan Package--><context: Component-scan base-package= "Com.iss"/><!--opening annotations--><mvc:annotation-driven/><!--static resources (Js/image) Access--><mvc:resources location= "/js/" mapping= "/js/**"/><!--define View resolver--><bean id= "ViewResolver" class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" ><property name= "prefix" value= "/ "></pRoperty><property name= "suffix" value= ". JSP" ></property></bean></beans> 

Finally, 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 "><display-name>json_test</display-name><welcome-file-list>< welcome-file>login.jsp</welcome-file></welcome-file-list><!--Load all the configuration files-->< context-param><param-name>contextconfiglocation</param-name><param-value>classpath*: spring-*.xml</param-value></context-param><!--Configuring Spring monitoring--><listener>< Listener-class>org.springframework.web.context.contextloaderlistener</listener-class></listener ><!--Configuration Springmvc--><servlet><servlet-name>springmvc</servlet-name><servlet-class >org.springframework.web.servlet.dispatcherservlet</servlet-class><init-param><param-name>contextconfiglocation</param-name>< Param-value>web-inf/classes/spring-mvc.xml</param-value></init-param><load-on-startup>1 </load-on-startup></servlet><servlet-mapping><servlet-name>springmvc</servlet-name ><url-pattern>/</url-pattern></servlet-mapping><!--Configuring Character Set--><filter>< Filter-name>encodingfilter</filter-name><filter-class> Org.springframework.web.filter.characterencodingfilter</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><filter-mapping><filter-name>encodingfilter</filter-name>< url-pattern>/*</url-pattern></filter-mapping><!--Configuration Session--><filter><filter-name>opensession</filter-name><filter-class> org.springframework.orm.hibernate4.support.opensessioninviewfilter</filter-class></filter>< Filter-mapping><filter-name>opensession</filter-name><url-pattern>/*</url-pattern> </filter-mapping></web-app>


OK all the configuration files can be completed below to see the logic code.


Com.iss.model.User.class

Package Com.iss.model;import Javax.persistence.entity;import Javax.persistence.generatedvalue;import Javax.persistence.generationtype;import javax.persistence.id;import javax.persistence.table;/** * @author Dell *  */@Entity @table (name = "User") public class User {private int id;private String name; @Id @generatedvalue (strategy = Ge Nerationtype.auto) 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;}}

Com.iss.dao.UserDao.class

Package Com.iss.dao;import Java.util.list;import Com.iss.model.user;public interface Userdao {public user addUser (user User);p ublic list<user> getAllUsers ();p ublic user getUser (int userId);p ublic void deleteuser (user user);

Com.iss.dao.impl.UserDaoImpl.class

Package Com.iss.dao.impl;import Java.util.list;import Org.hibernate.query;import org.hibernate.session;import Org.hibernate.sessionfactory;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.repository;import Com.iss.dao.userdao;import Com.iss.model.User; @Repositorypublic Class Userdaoimpl implements Userdao {private sessionfactory sessionfactory; @Autowiredpublic void Setsessionfactory ( Sessionfactory sessionfactory) {this.sessionfactory = sessionfactory;} Public user addUser (user user) {Session session = Sessionfactory.getcurrentsession (); session.saveorupdate (user); Session.flush (); return user;} Public list<user> GetAllUsers () {Session session = Sessionfactory.getcurrentsession (); Query query = Session.createquery ("from User"); list<user> users = Query.list (); Session.flush (); return users;} Public User getUser (int userId) {Session session = Sessionfactory.getcurrentsession (); User user = (user) Session.get (user.class, userId); return uSer;} public void DeleteUser (user user) {Session session = Sessionfactory.getcurrentsession (); session.delete (user); Session.flush ();}}

Com.iss.service.UserService.class

Package Com.iss.service;import Java.util.list;import Com.iss.model.user;public interface UserService {public User AddUser (user user);p ublic list<user> getAllUsers ();p ublic User getUser (int userId);p ublic void DeleteUser (user user);}

Com.iss.service.UserServiceImpl.class

Package Com.iss.service.impl;import Java.util.list;import org.springframework.beans.factory.annotation.Autowired; Import Org.springframework.stereotype.service;import Com.iss.dao.userdao;import Com.iss.model.user;import Com.iss.service.UserService, @Service ("UserService") public class Userserviceimpl implements UserService {private Userdao Userdao; @Autowiredpublic void Setuserdao (Userdao userdao) {This.userdao = Userdao;} Public user addUser (user user) {//TODO auto-generated method Stubreturn userdao.adduser (user);} Public list<user> getAllUsers () {//TODO auto-generated method Stubreturn userdao.getallusers ();} Public User getUser (int userId) {//TODO auto-generated method Stubreturn Userdao.getuser (userId);} public void DeleteUser (user user) {userdao.deleteuser (user);}}
Com.iss.controller.UserController
Package Com.iss.controller;import Java.io.ioexception;import Java.util.list;import Javax.servlet.http.httpservletresponse;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Org.springframework.ui.modelmap;import Org.springframework.web.bind.annotation.requestmapping;import Com.iss.model.user;import Com.iss.service.UserService; @Controller @requestmapping ("/user") public class Usercontroller {private UserService UserService; @Autowiredpublic void Setuserservice (UserService userservice) {this.userservice = UserService;} @RequestMapping ("/toadduser") public String Toadduser () {return "AddUser";} @RequestMapping ("/toupdateuser") public String toupdateuser (int id, Modelmap modelmap) {User user = Userservice.getuser ( ID); Modelmap.addattribute ("User", user); return "Edituser";} @RequestMapping ("/adduser") public String addUser (user user) {userservice.adduser (user); return "redirect:/user/ Getalluser ";} @RequestMapping ("/getalluser") public StRing GetAllUsers (Modelmap modelmap) {list<user> userlist = Userservice.getallusers (); Modelmap.addattribute (" UserList ", userlist); return" index ";} @RequestMapping ("/deluser") public String deluser (int ID, httpservletresponse response) throws IOException {User user = Userservice.getuser (ID); System.err.println (User.getname ()); Userservice.deleteuser (user); Response.getwriter (). Print ("Success"); return null;}}
Here are the code for several JSP pages

login.jsp

<body>

index.jsp

<body>

Where does the deletion use jquery need to be referenced? jquery Package

<script type= "Text/javascript" src= ". /js/jquery.js "></script><script type=" Text/javascript ">function del (ID) {/* $.get (" delUser?id= "+ ID, function (data) {alert (data), if ("success" = = data) {alert ("Delete succeeded"), $ ("#tr" + ID). Remove ();} else {alert ("delete failed");}); */var url = "deluser?id=" + id;$.ajax ({type: "Post", Url:url,datatype: "Text", success:function (data) {if ("success" = = data) {alert ("Delete succeeded"), $ ("#tr" + ID). Remove ();} else {alert ("delete failed");}});} </script>

edituser.jsp

adduser.jsp

<body>

Where JS code

<script type= "Text/javascript" >function AddUser () {var form = Document.forms[0];form.action = "AddUser"; Form.method = "POST"; Form.submit ();} </script>

The above basically completes the integration between Spring-springmvc-hibernate and carries on the basic crud operation. Of course, there are many shortcomings also look at the light spray!










Spring-springmvc-hibernate Consolidation

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.