码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC+hibernate整合小例子,用户的增删查改

时间:2016-04-29 18:50:36      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:

SpringMVC+hibernate整合小例子,用户的增删查改

对于使用框架写项目,我的第一反应的把所有需要的jar文件引入。

因为我用的是JDK1.8,当使用spring3.2 注解的时候会出现问题,所以最终使用的spring4.0.  hibernate使用的版本为4.0 。至于一些依赖包的版本就是看别人的资料拿的。

技术分享技术分享

然后看下整体的项目结构

技术分享

第一步写的是web.xml配置文件,当然有写东西是后面加上去的,不是一步到位的,比如说控制post方式的乱码、以及无法时候JS文件等一些静态文件,后面的代码都是在做的过程遇到问题再一点一点百度,然后加上去的。

<?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" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

<!-- 控制乱码  -->
<filter>  
     <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>  
    <url-pattern>/*</url-pattern>  
</filter-mapping>  
  
 <!-- 创建spring监听器 --> 
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
 <!-- spring的监听器可以通过这个上下文参数来获取beans.xml的位置--> 
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:beans.xml</param-value>
  </context-param>
  
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <!--<url-pattern>/</url-pattern>	使用/会拦截所有的url所以无法直接访问项目中的静态文件 
	      解决方法使用 资源管理
	  <mvc:resources location="/js/" mapping="/js/**"/>
  -->
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>/</url-pattern> 
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

第二 写实体类以及映射文件 Users类、Users.hbm.xml

这里的实体类的生成、以及Users.hbm.xml文件使用的hibernate的反向工程生成的。至于方向工程如何操作可以看我之前关于方向工程的文件。使用反向工程的好处就是在于节省时间,减少错误的发生。

http://blog.csdn.net/qq303437511/article/details/47263849   具体讲解了如何安装插件、以及使用方向工程。

package com.spring.mvc.model;

// Generated 2016-4-22 10:22:24 by Hibernate Tools 3.4.0.CR1

/**
 * Users generated by hbm2java
 */
public class Users implements java.io.Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Integer userid;
	private String nickname;
	private String username;
	private String password;
	private String answer;
	private Boolean question;
	private Boolean role;
	private Boolean isdel;
	private Boolean userState;

	public Users() {
	}

	public Users(String nickname, String username, String password,
			String answer, Boolean question, Boolean role, Boolean isdel,
			Boolean userState) {
		this.nickname = nickname;
		this.username = username;
		this.password = password;
		this.answer = answer;
		this.question = question;
		this.role = role;
		this.isdel = isdel;
		this.userState = userState;
	}

	public Integer getUserid() {
		return this.userid;
	}

	public void setUserid(Integer userid) {
		this.userid = userid;
	}

	public String getNickname() {
		return this.nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getUsername() {
		return this.username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return this.password;
	}

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

	public String getAnswer() {
		return this.answer;
	}

	public void setAnswer(String answer) {
		this.answer = answer;
	}

	public Boolean getQuestion() {
		return this.question;
	}

	public void setQuestion(Boolean question) {
		this.question = question;
	}

	public Boolean getRole() {
		return this.role;
	}

	public void setRole(Boolean role) {
		this.role = role;
	}

	public Boolean getIsdel() {
		return this.isdel;
	}

	public void setIsdel(Boolean isdel) {
		this.isdel = isdel;
	}

	public Boolean getUserState() {
		return this.userState;
	}

	public void setUserState(Boolean userState) {
		this.userState = userState;
	}

}
Users.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-4-22 10:22:24 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.spring.mvc.model.Users" table="users" catalog="database1">
        <id name="userid" type="java.lang.Integer">
            <column name="userid" />
            <generator class="identity" />
        </id>
        <property name="nickname" type="string">
            <column name="nickname" length="20" />
        </property>
        <property name="username" type="string">
            <column name="username" length="40" />
        </property>
        <property name="password" type="string">
            <column name="password" length="40" />
        </property>
        <property name="answer" type="string">
            <column name="answer" length="50" />
        </property>
        <property name="question" type="java.lang.Boolean">
            <column name="question" />
        </property>
        <property name="role" type="java.lang.Boolean">
            <column name="role" />
        </property>
        <property name="isdel" type="java.lang.Boolean">
            <column name="isdel" />
        </property>
        <property name="userState" type="java.lang.Boolean">
            <column name="userState" />
        </property>
    </class>
</hibernate-mapping>

第三写控制器

package com.spring.mvc.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spring.mvc.model.Users;
import com.spring.mvc.service.UsersService;
//声明这是一个控制器
@Controller
public class UsersController {
	
	@Resource
	private UsersService userservice;
        
	@RequestMapping("adduser")
	public String addUser(String username,String password,Users user){
		System.out.println(username);
		System.out.println(password);
		System.out.println("1"+user);
	        userservice.addUsers(user);
		return "success";
		
	}
        //这个方法用于用户注册时判断用户名是否已经存在。需要使用ajax来实现异步刷新
	@RequestMapping("valUsername")
	public  @ResponseBody Map<String,Object> findUsersByName(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		String username = (String) request.getParameter("username");
		//System.out.println(username+"111");
		String msg = userservice.findUsersByName(username);
	        map.put("msg", msg);
		return map;
	}
	@RequestMapping("/listUsers")
	public String listAll(Map<String,Object> model){
		//Map<String,Object> model 这种形式的返回model中的属性可以任意。
		List<Users> userList =userservice.list();
		model.put("userList", userList);
		
		return "UsersList";
	}
	@RequestMapping("/userUpdate")
	public String update(Integer id, Model model){
		//System.out.println(id);
		Users Users = userservice.findUsersById(id);
		model.addAttribute(Users); //model里面的属性需要和类名一样 但是需要小写
		
		return "UserUpdate";
	} 
	@RequestMapping("/updateInfo")
	public String updateInfo(HttpServletRequest request,Users user){
		System.out.println(user.getUsername());
		userservice.UpdateInfo(user);
		return "UserUpdate";
	}
	@RequestMapping("/deleteById")
	public String delUser(Integer id){
		userservice.delUserById(id);
		return "redirect:/listUsers";
	}
      
}

在 Spring mvc3中,响应、接受 JSON都十分方便。 
使用注解@ResponseBody可以将结果(一个包含字符串和JavaBean的Map),转换成JSON。 
使用 @RequestBody 注解前台只需要向 Controller 提交一段符合格式的 JSON,Spring 会自动将其拼装成 bean。 

Spring这个转换是靠org.codehaus.jackson这个组件来实现的,所有需要引入jackson-core-asl和org.codehaus.jackson两个jar包 

上面一段是从别人那复制过来了,但是我只使用了jackson-core-asl-1.9.13.jar、jackson-mapper-asl-1.9.13.jar也是可以实现效果的。

第四 写service类

package com.spring.mvc.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.spring.mvc.dao.UsersDao;
import com.spring.mvc.model.Users;
@Service("userservice")
public class UsersService {
	@Resource
    private UsersDao userdao;
 
    public boolean addUsers(Users user){
    	this.userdao.addUser(user);	
    	return true;
    }
   
    public String findUsersByName(String username){
    	return this.userdao.findUserByName(username);
    }

	public List<Users> list() {
		return this.userdao.list();
	}

	public Users findUsersById(Integer id) {
		return this.userdao.findUserById(id);
	}

	public void UpdateInfo(Users user) {
		this.userdao.UpdateInfo(user);
		
	}

	public void delUserById(Integer id) {
		this.userdao.delUserById(id);
	}
}

第五写 DAO类、DAOImpl实现类。

package com.spring.mvc.dao;

import java.util.List;

import com.spring.mvc.model.Users;


public interface UsersDao {
	public void addUser(Users user);
	public String findUserByName(String username);
	public List<Users> list();
	public Users findUserById(Integer id);
	public void UpdateInfo(Users user);
	public void delUserById(Integer id);
}
package com.spring.mvc.daoimpl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.spring.mvc.dao.UsersDao;
import com.spring.mvc.model.Users;

@Repository("userdao")
public class UserDaoImpl implements UsersDao {  
	@Resource
	private SessionFactory sessionFactory;
	
	public void addUser(Users user) {
		sessionFactory.getCurrentSession().saveOrUpdate(user);
	}

	@SuppressWarnings("unchecked")
	@Override
	public String findUserByName(String username) {
		String sql = "from Users u where u.username = "+"'"+username+"'";
		System.out.println(username);
		List<Users> usersList =  (List<Users>) sessionFactory.getCurrentSession().createQuery(sql).list();
		System.out.println(usersList.size());
		if(usersList.size()>0){
			return "true";
		}else{
			return "false";
		}
	}

	@Override
	public List<Users> list() {
		//Query q = sessionFactory.getCurrentSession().createQuery("from Users");
		@SuppressWarnings("unchecked")
		List<Users> usersList =  (List<Users>) sessionFactory.getCurrentSession().createQuery("from Users").list();
		return usersList;
	}

	@Override
	public Users findUserById(Integer id) {
		return (Users) sessionFactory.getCurrentSession().get(Users.class,id);
	}

	@Override
	public void UpdateInfo(Users user) {
		String sql = "update Users  set username=? where userid=?";
		Query q = sessionFactory.getCurrentSession().createQuery(sql);
		q.setString(0, user.getUsername());
		q.setInteger(1, user.getUserid());
		q.executeUpdate();
		
	}

	@Override
	public void delUserById(Integer id) {
			Users u = (Users) sessionFactory.getCurrentSession().get(Users.class,id);
			sessionFactory.getCurrentSession().delete(u);
	}

}

写完这个之后写Spring的配置文件

<?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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
			http://www.springframework.org/schema/mvc 
			http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
			http://www.springframework.org/schema/context 
			http://www.springframework.org/schema/context/spring-context-3.2.xsd ">
    
	       <!-- 自动扫描 -->
		<context:component-scan base-package="com.spring.mvc.action"/>
		
		<!-- 注解驱动 -->
		<mvc:annotation-driven/>
		<!-- 资源管理 -->
		<mvc:resources location="/js/" mapping="/js/**"/>
		<mvc:resources location="/imgs/" mapping="/imgs/**"/>
		
		
		<!--视图解析器  -->	
		<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 前缀 -->
		<property name="prefix" value="/jsp/"/>
		<!-- 后缀 -->
		<property name="suffix" value=".jsp"/>
	</bean>
</beans>
一些bean的实例、数据源、还有事务管理、AOP配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:tx="http://www.springframework.org/schema/tx"
	   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"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
			http://www.springframework.org/schema/mvc 
			http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
			http://www.springframework.org/schema/context 
			http://www.springframework.org/schema/context/spring-context-3.2.xsd 
			http://www.springframework.org/schema/aop 
			http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
			http://www.springframework.org/schema/tx 
			http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
			
	<!-- 自动扫描 -->
	<context:component-scan base-package="com.spring.mvc.daoimpl,com.spring.mvc.service,com.spring.mvc.dao"/>	
		
	<!-- 数据源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">  
        <property name="driverClass" value="com.mysql.jdbc.Driver" />  
        <property name="jdbcUrl" value="jdbc:mysql://localhost/database1" />    
        <property name="user" value="root" />   
        <property name="password" value="1234" />   
        <property name="maxPoolSize" value="80" />  
        <property name="minPoolSize" value="1"/> 
        <property name="initialPoolSize" value="1" />   
      <!--   <property name="maxIdleTime" value="2500" />  --> 
     </bean>  
     <!--配置sessionFactory-->	
	<bean id="sessionFactory"  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
        <property name="dataSource" ref="dataSource"/>
        <!-- 映射文件的目录 -->  
        <property name="mappingDirectoryLocations">
			<list>
				<value>classpath:com/spring/mvc/model</value>
			</list>
		</property>
        <!-- 其他的hibernate常用配置 -->  
        <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
                <prop key="show_sql">true</prop>  
                <prop key="hibernate.hbm2ddl.auto">update</prop>  
            </props>  
        </property>  
    </bean>  
    
	<!-- hibernate事务管理器,在service层上实现事务管理,实现平台无关 -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<!-- 事务通知 -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT" />
			<tx:method name="updae*" propagation="REQUIRED" isolation="DEFAULT" />
			<tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" />
			<tx:method name="batch*" propagation="REQUIRED" isolation="DEFAULT" />
			<tx:method name="load*" propagation="REQUIRED" isolation="DEFAULT" read-only="true" />
			<tx:method name="get*" propagation="REQUIRED" isolation="DEFAULT" read-only="true" />
			<tx:method name="find*" propagation="REQUIRED" isolation="DEFAULT" read-only="true" />
			<tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" />
		</tx:attributes>
	</tx:advice>
                    
	<aop:config>
		<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.spring.mvc.service.*.*(..))" />
	</aop:config>
	   
</beans>
下面是JSP文件

这个是用户注册页面、里面有一段ajax代码实现用户名是否可以用的异步验证功能

技术分享

当用户输入的用户名已存在 会出现提示

技术分享

<%@ 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>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="/GDUTCourse/js/jquery-1.9.1.min.js"> </script>
</head>
<body>
  <form action="${pageContext.request.contextPath}/adduser" method="post">
  <h1>用户注册</h1>
  用户名:<input type="text" name="username" id="username"/> <label id="tishi" style="display:none;">用户名已经存在</label>
   密码:  <input type="password" name="password"/>
      <input type="submit" value="注册">
  </form>
</body>
 <script type="text/javascript">
    $("#username").blur(function(){ 
        	 var username = $("#username").val();
        		 $.ajax({  
        		        data:{username:username},  
        		        type:"GET",  
        		        dataType: 'json',  
        		        url:"/GDUTCourse/valUsername",  
        		        error:function(data){  
        		            alert("出错了!!:"+data.msg);  
        		        },  
        		        success:function(data){  
        		        	if(data.msg == "true" ){
        		             // alert("success:"+data.msg);  
        		             $("#tishi").show();
        		             }else{
        		            	 $("#tishi").hide(); 
        		             }
        		        }  
        		  
        	    });
     });          
    </script>
</html>

用户列表页面

技术分享

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户列表</title>
</head>
<body>
<h2>用户列表</h2>
	
	
<table border="1">
<tr>
	<td>id</td>
	<td>name</td>
	<td>password</td>
	<td>操作</td>
</tr>

<c:forEach items="${userList}" var="users">
<tr>
	<td>${users.userid}</td>
	<td>${users.username}</td>
	<td>${users.password}</td>
	<td>
		<a href="${pageContext.request.contextPath}/userUpdate?id=${users.userid}">修改</a>
		<a href="${pageContext.request.contextPath}/deleteById?id=${users.userid}">删除</a>
	</td>
</tr>
</c:forEach>

</table>
  </body>
</html>

用户修改页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<body>  

<sf:form id="p" action="updateInfo" method="post" modelAttribute="users">
<h2>修改用户</h2>
<table border="1">
<tr>
	<td>id:</td>
	<td><sf:input path="userid"/></td>
</tr>
<tr>
	<td>name:</td>
	<td><sf:input path="username"/></td>
</tr>
<tr>
	<td>age:</td>
	<td><sf:input path="password"/></td>
</tr>

<tr>
	<td><input type="submit"/></td>
</tr>

</table>

</sf:form>
</body>  
</body>
</html>

刚刚学这个,文笔也不好,希望大家不要太介意。源码下载地址:http://download.csdn.net/detail/qq303437511/9501271






SpringMVC+hibernate整合小例子,用户的增删查改

标签:

原文地址:http://blog.csdn.net/qq303437511/article/details/51235340

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!