Spring-springmvc-hibernate Integration

Source: Internet
Author: User

Just look at the package structure because you don't use maven! Maybe it will come with maven!

The package is a bit more, but don't care about these details, more than the less good. See Configuration file Spring-common.xml (equivalent to applicationcontext.xml) below
<?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 "><!--Configuring the 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><!--Configuring 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>

The other is the SPRINGMVC 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) Interview--><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 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 the following 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 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>

The 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 completed the integration between Spring-springmvc-hibernate and carried out the main crud operations. Of course, there are many shortcomings also look at the light spray!










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.