spring+springmvc+hibernate 礼品管理系统

spring+springmvc+hibernate template礼品管理系统

1.简单介绍

    如标题所示,这篇文章简单写了一个基于spring+springmvc+hibernate template的礼品管理系统,适合初学者,这是我的第三篇文章,希望可以通过这篇文章让同学了解这个系统基本流程,虽然逐渐退出主流,但是还有很多地方思路值得我们学习。如有兴趣,可以随时联系我:1763907618.

2.环境搭建

    我的项目测试成功,前台jsp,没有美化,主要是后台功能都能实现。

    jdk:1.6;

    数据库:mysql5.6;

    基于hibernate的jar包,cglib.jar可能还会有冲突,每次发布项目需要删除。

    基于springmvc的jar包,

3.成果基本样式

4.详细内容

    HibernateTemplate的常用方法。
    delete(Object entity): 删除指定持久化实例。
    find(String queryString): 根据 HQL 查询字符串来返回实例集合。
    save(Object entity): 保存新的实例。
    update(Object entity): 更新实例的状态,要求entity 是持久状态。

主要就是一个增删改查的过程。上面这四个是我们常用方法。

因为我的项目用到了hibernate的逆向工程,所以数据库是自动生成。

下面就写一个登录实例,因为登录是一个查询的过程,所以我们将用find方法。

a.创建项目,导入jar包,这些我就不介绍了。

b.创建

com.controller,

com.dao,

com.model,

com.service

包,在里面分别建立java

usercontroller,

userdao,

user,

userservice

注意开头大写。

c.编写hibernate.cfg.xml

 

<?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">
<hibernate-configuration>
    <session-factory>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/bgift?useUnicode=true&characterEncoding=UTF-8</property>
        <property name="connection.username">root</property>
        <property name="connection.password">1478</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="myeclipse.connection.profile">Bgift</property>
        <property name="show_sql">true</property>
	    <property name="format_sql">true</property>
	    <property name="hbm2ddl.auto">update</property>
	    <property name="hibernate.connection.autocommit">true</property> 
	    <mapping class="com.model.User" />
/////其中 mapping class="com.model.User"是要注意的。路径问题。
</session-factory> </hibernate-configuration> 

d.编写web.xml
<?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">  
	<!-- log4j -->
	<context-param>  
        <param-name>log4jConfigLocation</param-name>  
        <param-value>/WEB-INF/classes/log4j.properties</param-value>  
    </context-param>  
      
    <context-param>  
        <param-name>log4jRefreshInterval</param-name>  
        <param-value>60000</param-value>  
    </context-param>  
    <listener>  
        <listener-class>  
            org.springframework.web.util.Log4jConfigListener  
        </listener-class>  
    </listener> 	
    <!-- 字mvc -->
	<servlet>
		<servlet-name>mvc</servlet-name>
	    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/applicationContext.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>mvc</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>	
	<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  <!-- 字符编码过滤器,结觉乱码问题 -->
	<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>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

  e.编写applicationContext.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	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.0.xsd 
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-3.0.xsd 
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  ">
    
	<context:annotation-config></context:annotation-config>
	<context:component-scan base-package="com.*"></context:component-scan>
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="" p:suffix=".jsp">
	</bean>
	
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="configLocation" value="classpath:hibernate.cfg.xml"> </property>
	</bean>
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>	
	<tx:annotation-driven transaction-manager="transactionManager"/>
	<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>

  f.编写com.model.user.java

package com.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="user")
public class User {

	int id;
    String username;
    String password;
    @Id
    @Column
    @GeneratedValue(strategy=GenerationType.AUTO)
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	@Column
    public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	 @Column
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}	 	
    
}

  g.编写com.model.userdao.java

package com.dao;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
 
import com.model.User;

@Repository
public class UserDao extends HibernateDaoSupport{
	@Resource
    public void setSessionFactoryOverride(SessionFactory sessionFactory){
	    super.setSessionFactory(sessionFactory);
	}

/////////////*登录*//////////////////////////////*登录*////////////////////////*登录*/
	@SuppressWarnings("unchecked")
	public List<User> userlogin(User user){
		String hql= "from User where username=? and password=?";
		List<User>  t=this.getHibernateTemplate().find(hql,new Object[]{user.getUsername(),user.getPassword()});
		return t;
	}

}

 h.编写com.model.userservice.java 

package com.service;

import java.util.List;

import javax.annotation.Resource;
import org.springframework.stereotype.Component;
 
import com.dao.UserDao;
import com.model.User;

@Component
public class UserService {
	@Resource
	UserDao userdao;

	public UserDao getUserdao() {
		return userdao;
	}

	public void setUserdao(UserDao userdao) {
		this.userdao = userdao;
	}
/////////////*登录*//////////////////////////////*登录*//////////*登录*/
	public List<User> userlogin(User user){
		 return userdao.userlogin(user);
		 
	 }

}

  i.编写com.model.usercontroller.java

package com.Controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
import com.model.User;
import com.service.UserService;

@Controller
public class UserController {
	@Resource
	UserService userService;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

/////////////*登录*//////////////////////////////*登录*/
	@RequestMapping("userlogin.do")
	public String findAll(HttpSession session,User user,HttpServletResponse response){	
    List<User> listuser = userService.userlogin(user);
    if(listuser.size()>0){
    	session.setAttribute("listuser", listuser);
        return "loginsuccess";	
    }else{
		response.setContentType("text/html; charset=UTF-8"); //转码
	    PrintWriter out;
		try {
			out = response.getWriter();
			out.flush();
		    out.println("<script>");
		    out.println("alert('账号或密码错误!');");
		    out.println("history.back();");
		    out.println("</script>");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	   	    
    	return "index";
    }   
}

}

  j.编写前台index.jsp

 <form name="formuser" id="formuser" method="post" action="userlogin.do">
	 <input type="text"   id="username" name="username" placeholder="请输入账号" /><br /><br />		
	 <input type="password" class="index_mi"  id="password"  name="password" placeholder="请输入密码"  /><br /><br />	
         <input class="index_z_fi" type="submit"  value="登录" /> 	
 </form>

 

k.编写前台loginsuccess.jsp
添加${sessionScope.listuser[0].username}
接受后台传来的
session.setAttribute("listuser", listuser);值。

 

5.总结

   一个登录写完,其实我只是把文件中的一部分赋值过来,便于了解。

在写这个系统之前,有过很多问题:

  a.路径问题,return 后面接jsp路径的话,要把路径写对,在提交时候XXX.do要写对。否则404。

  b.jar包冲突问题,当初困扰我很久,后来把冲突包删除,再发布后还会出现,索性把jar包都放到lib文件夹下。

  c.乱码,在web.xml下配置,相互传值要注意。比较好改。

最后:文档只是一部分,如有需要请联系1763907618。记得关注和点赞,谢谢各位。

另附源码:

 

链接:https://pan.baidu.com/s/1Cimu_lybQLdOZu0qSOSDRQ
提取码:1p59

如果有帮助,记得点赞支持!

 

原文地址:https://www.cnblogs.com/wangyongping/p/10006295.html