spring4+springmvc+hibernate3 demo,欢迎拍砖

来源:互联网 发布:windows apache 启动 编辑:程序博客网 时间:2024/06/04 18:13

自己是个菜鸟,希望能够更快的成长,让砖头来的更猛烈些吧!目前来说该项目只是个玩具,可以借鉴一些东西,但是不建议在实际生产环境中使用。

感谢孔浩老师的视频!

感谢网上的各位大神!

话不多说,进入正题。

--------------------------------------------------------------------------------------------------------


1.项目整个截图如下:


2.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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>shTest1</display-name>  <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list>    <!-- 创建spring监听器 -->  <listener>  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <!-- spring的监听器可以通过这个上下文参数来获取applicationContext.xml的位置 -->  <context-param>  <param-name>contextConfigLocation</param-name>  <param-value>classpath:applicationContext.xml</param-value>  </context-param>    <servlet>  <servlet-name>spring-mvc</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>  <servlet-mapping>  <servlet-name>spring-mvc</servlet-name><url-pattern>/</url-pattern>  </servlet-mapping>    <filter>  <filter-name>CharacterFilter</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>CharacterFilter</filter-name>  <url-pattern>/*</url-pattern>  </filter-mapping>  </web-app>


3.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:p="http://www.springframework.org/schema/p"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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd" ><!-- Spring为我们提供了一种极为方便注册这些BeanPostProcessor的方式,即使用<context:annotation- config/>隐式地向 Spring容器注册AutowiredAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor以及PersistenceAnnotationBeanPostProcessor这4个BeanPostProcessor -->    <context:annotation-config />        <!-- <mvc:annotation-driven /> 是一种简写形式,    会自动注册DefaultAnnotationHandlerMapping与    AnnotationMethodHandlerAdapter 两个bean,    是spring MVC为@Controllers分发请求所必须的 --><mvc:annotation-driven /><!--使Spring支持自动检测组件,如注解的Controller --><context:component-scan base-package="com.aodong.shTest1.controller" /><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/jsp/" /><property name="suffix" value=".jsp" /></bean></beans>


4.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd" default-autowire="byName" default-lazy-init="false"><!-- 打开spring的annotation的支持 --><context:annotation-config /><!-- 设定spring去那些包中找annotation --><context:component-scan base-package="com.aodong.shTest1" /><!-- 导入src目录下的jdbc.properties文件 --><context:property-placeholder location="classpath:jdbc.properties"/><!-- 配置c3p0连接池--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${datasource.driverClassName}"></property>      <property name="jdbcUrl" value="${datasource.url}"></property>      <property name="user" value="${datasource.username}"></property>      <property name="password" value="${datasource.password}"></property>      <property name="acquireIncrement" value="${c3p0.acquireIncrement}"></property>      <property name="initialPoolSize" value="${c3p0.initialPoolSize}"></property>      <property name="maxIdleTime" value="${c3p0.maxIdleTime}"></property>      <property name="maxPoolSize" value="${c3p0.maxPoolSize}"></property>      <property name="minPoolSize" value="${c3p0.minPoolSize}"></property>      <property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}"></property>      <property name="maxStatements" value="${c3p0.maxStatements}"></property>      <property name="numHelperThreads" value="${c3p0.numHelperThreads}"></property>      <property name="testConnectionOnCheckout" value="${c3p0.testConnectionOnCheckout}"></property>      <property name="preferredTestQuery" value="${c3p0.preferredTestQuery}"></property>      <property name="acquireRetryDelay" value="1000"></property>      <property name="acquireRetryAttempts" value="60"></property>      <property name="breakAfterAcquireFailure" value="false"></property> </bean><!-- 创建spring的sessionfactory工厂 --><bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"><!-- 注入数据源 --><property name="dataSource" ref="dataSource"/><!-- 设置spring去哪个包中查找相应的实体类 --><property name="packagesToScan"><list><value>com.aodong.shTest1.model</value></list></property><property name="hibernateProperties"><props><prop key="hibernate.dialect">${hibernate.dialect}</prop><prop key="hibernate.format_sql">false</prop> <prop key="hibernate.show_sql">true</prop><!-- 如果开启, Hibernate将在SQL中生成有助于调试的注释信息, 默认值为false. 取值 true | false --><prop key="hibernate.use_sql_comments">false</prop><!-- Fetch Size 是设定JDBC的Statement读取数据的时候每次从数据库中取出的记录条数。 --><prop key="hibernate.jdbc.fetch_size">50</prop><!-- Batch Size是设定对数据库进行批量删除,批量更新和批量插入的时候的批次大小 --><prop key="hibernate.jdbc.batch_size">25</prop><!-- 允许使用外连接抓取.取值. true | false --><prop key="hibernate.use_outer_join">true</prop><!-- 外连接抓取树的最大深度,建议在0到3之间 --><prop key="hibernate.max_fetch_depth">1</prop><!-- 强制Hibernate按照被更新数据的主键,为SQL更新排序。这么做将减少在高并发系统中事务的死锁。 取值 true | false  --><prop key="hibernate.order_updates">true</prop><!-- 如果开启, Hibernate将收集有助于性能调节的统计数据.取值true|false --><prop key="hibernate.generate_statistics">true</prop><prop key="hibernate.hbm2ddl.auto">update</prop></props></property></bean>        <!-- 开启HibernateTemplate,并且为其注入SessionFactory          使用HibernateTemplate不太方便的就是要获取session得通过getSessionFactory()方法获取 -->        <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">            <property name="sessionFactory" ref="sessionFactory"/>        </bean>        <!-- 开启配置事务拦截器 --><bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean><!-- 基本事务定义,使用transactionManager做事务管理,默认get*,find*方法的事务为read-only --><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="find*" read-only="true"/><tx:method name="get*" read-only="true"/><tx:method name="add*" propagation="REQUIRED"/><tx:method name="update*" propagation="REQUIRED"/><tx:method name="delete*" propagation="REQUIRED"/><tx:method name="save*" propagation="REQUIRED"/><tx:method name="*" propagation="REQUIRED" /></tx:attributes></tx:advice><!-- 配置aop, spring是通过aop来进行事务管理的 --><aop:config><!-- 设置pointCut表示那些方法要加入事务处理 --><!-- 以下的事务是声明在dao中的,但是通常都会在service来处理多个业务对象逻辑的关系,注入删除,更新等,此时如果在执行了一个步骤之后抛出异常   就会导致数据不完整,所以事务不应该在dao层处理,而应在service,这也是spring所提供的一个非常方便的工具,声明式事务--><aop:pointcut id="interceptorPointCuts"expression="execution(* com.aodong.shTest1.service.*.*(..))"/> <!-- 通过advisor来确定具体要加入事务控制的方法 --><aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts"/></aop:config></beans>

5.jdbc.properties代码如下:

datasource.type=mysqldatasource.driverClassName=com.mysql.jdbc.Driverdatasource.url=jdbc\:mysql\://127.0.0.1\:3306/shtest?useUnicode\=true&characterEncoding\=UTF-8datasource.username=rootdatasource.password=roothibernate.dialect=org.hibernate.dialect.MySQLDialect#datasource.type=oracle#datasource.driverClassName=oracle.jdbc.driver.OracleDriver#datasource.url=jdbc\:oracle\:thin\:@192.168.1.88\:1521\:juice?useUnicode\=true&characterEncoding\=utf-8 #datasource.username=root#datasource.password=root#hibernate.dialect=org.hibernate.dialect.Oracle10gDialectdatasource.maxActive=100datasource.initialSize=5datasource.maxIdle=20datasource.maxWait=120000datasource.whenExhaustedAction=1#datasource.validationQuery=select 1 from dualdatasource.testOnBorrow=truedatasource.testOnReturn=falsec3p0.acquireIncrement=3c3p0.initialPoolSize=3c3p0.idleConnectionTestPeriod=60c3p0.minPoolSize=2c3p0.maxPoolSize=50c3p0.maxStatements=100c3p0.numHelperThreads=10c3p0.maxIdleTime=600c3p0.testConnectionOnCheckout=falsec3p0.preferredTestQuery=select 1 from dual  

6.log4j.properties代码如下:

log4j.rootCategory=INFO, stdout , Rlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=[springTest] %p [%t] %C.%M(%L) | %m%nlog4j.appender.R=org.apache.log4j.DailyRollingFileAppenderlog4j.appender.R.File=c\:logsshTest.loglog4j.appender.R.layout=org.apache.log4j.PatternLayoutlog4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n

7.model中Student.java代码如下:

package com.aodong.shTest1.model;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entitypublic class Student  {  @Id@GeneratedValue(strategy=GenerationType.AUTO)@Column(name="id")    private long id;  @Column(name="name",length=32)    private String name;  @Column(name="niceName")      private String niceName;  @Column(name="age")    private int age;public long getId() {return id;}public void setId(long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getNiceName() {return niceName;}public void setNiceName(String niceName) {this.niceName = niceName;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}              }

8.BaseDao代码如下:

package com.aodong.shTest1.dao;import javax.annotation.Resource;import org.hibernate.SessionFactory;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;public class BaseDao extends HibernateDaoSupport {@Resourcepublic void setMySessionFactory(SessionFactory sessionFactory){this.setSessionFactory(sessionFactory);}}

9.IStudentDao代码如下:

package com.aodong.shTest1.dao;import java.util.List;import com.aodong.shTest1.model.Student;public interface IStudentDao  {  public void add(Student stu);public void update(Student stu);public void delete(long id);public Student load(long id);public List<Student> list();public Student loadByUsername(long id);}

10.StudentDaoHibernateImpl代码如下:

package com.aodong.shTest1.dao.impl;import java.util.List;import org.springframework.stereotype.Repository;import com.aodong.shTest1.dao.BaseDao;import com.aodong.shTest1.dao.IStudentDao;import com.aodong.shTest1.model.Student;@Repositorypublic class StudentDaoHibernateImpl extends BaseDao implements IStudentDao {@Overridepublic void add(Student stu) {getHibernateTemplate().save(stu);}@Overridepublic void update(Student stu) {getHibernateTemplate().update(stu);}@Overridepublic void delete(long id) {getHibernateTemplate().delete(this.load(id));}@Overridepublic Student load(long id) {return getHibernateTemplate().get(Student.class, id);//return getHibernateTemplate().load(Student.class, id);}@Overridepublic List<Student> list() {return (List<Student>)this.getHibernateTemplate().find("from Student");}@Overridepublic Student loadByUsername(long id) {return getHibernateTemplate().load(Student.class, id);}}

11.IStudentService代码如下:

package com.aodong.shTest1.service;import java.util.List;import com.aodong.shTest1.model.Student;public interface IStudentService  {  public void add(Student stu);public void update(Student stu);public void delete(long id);public Student load(long id);public List<Student> list();} 

12.StudentServiceImpl代码如下:

package com.aodong.shTest1.service;import java.util.List;import javax.annotation.Resource;import org.springframework.stereotype.Service;import com.aodong.shTest1.dao.IStudentDao;import com.aodong.shTest1.model.Student;import com.aodong.shTest1.service.IStudentService;@Service("studentService")public class StudentServiceImpl implements IStudentService  {      private IStudentDao stuDao;      @Resource      public void setStuDao(IStudentDao stuDao)      {          this.stuDao = stuDao;      }    @Overridepublic void add(Student stu) {stuDao.add(stu);}@Overridepublic void update(Student stu) {stuDao.update(stu);}@Overridepublic void delete(long id) {stuDao.delete(id);}@Overridepublic Student load(long id) {return stuDao.load(id);}@Overridepublic List<Student> list() {return stuDao.list();}      }  

13.StudentController代码如下:

package com.aodong.shTest1.controller;import java.util.List;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.ModelAndView;import com.aodong.shTest1.model.Student;import com.aodong.shTest1.service.IStudentService;@Controller  @RequestMapping("/student")  public class StudentController  {  @Resource    private IStudentService stuService;        @RequestMapping(value="/list.do",method=RequestMethod.GET)    public ModelAndView getUserlist(Model model){                ModelAndView mv = new ModelAndView();        List<Student> userList = stuService.list();        System.out.println("log======table 'user' all records:"+userList.size());        mv.addObject("userList", userList);        mv.setViewName("list");        return mv;    }        @RequestMapping(value="/add.do",method=RequestMethod.GET)    public ModelAndView getAdd(){        ModelAndView mv = new ModelAndView();        mv.setViewName("add");        return mv;    }        @RequestMapping(value="/add.do",method=RequestMethod.POST)    public String add(@ModelAttribute("user") Student stu){        stuService.add(stu);        return "redirect:/student/list.do";    }        @RequestMapping(value="/{userid}/show.do",method=RequestMethod.GET)    public String show(@PathVariable Long userid,Model model){        Student user = stuService.load(userid);    model.addAttribute("user", user);        return "detail";    }        @RequestMapping(value="/{userid}/del.do",method=RequestMethod.GET)    public String del(@PathVariable Long userid){        stuService.delete(userid);        List<Student> stus=stuService.list();        System.out.println(stus.size());        return "redirect:/student/list.do";    }        @RequestMapping(value="/{userid}/edit.do",method=RequestMethod.GET)    public ModelAndView getEdit(@PathVariable Long userid,Model model){    Student user = stuService.load(userid);        model.addAttribute("userAttribute", user);        ModelAndView mv = new ModelAndView();        mv.setViewName("edit");        return mv;    }        @RequestMapping(value="/{userid}/save.do",method=RequestMethod.POST)    public String saveEdit(@ModelAttribute("userAttribute") Student user,@PathVariable Long userid){        stuService.update(user);        return "redirect:/student/list.do";    }         @RequestMapping(value="/show.do", method=RequestMethod.GET, produces="application/json", params="json")    @ResponseBody    public Student show(){    return stuService.load(1);    }          @RequestMapping(value="/login.do", method=RequestMethod.GET)    public String login(){    return "login";    }        @RequestMapping(value="/login.do", method=RequestMethod.POST)    public String submit(String userName, String passwd, HttpServletRequest request,HttpServletResponse response, ModelMap model){    return "redirect:/student/list.do";    } }  

14.list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!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>User List</title></head><body>    <a href="add.do">Add</a>    <table>        <tr>            <td>ID</td>            <td>Name</td>            <td>NiceName</td>            <td>Age</td>        </tr>        <c:forEach var="user" items="${userList }" >            <tr>                <td>${user.id }</td>                <td>${user.name }</td>                <td>${user.niceName }</td>                <td>${user.age }</td>                <td><a href="${user.id }/show.do">详细</a></td>                <td><a href="${user.id}/edit.do">编辑</a></td>                <td><a href="${user.id}/del.do">删除</a></td>            </tr>        </c:forEach>    </table></body></html>

15.add.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!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>Add User</title></head><body>    <form action="add.do" method="post">                Name:<input id="name" name="name" type="text" />        <br>        Nice Name:<input id="niceName" name="niceName" type="text" />        <br>        Age:<input id="age" name="age" type="text" />        <br>        <input type="submit" value="提交">    </form></body></html>

16.detail.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!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>Show user</title></head><body>    <c:out value="${user.id }"></c:out>    <br>    <c:out value="${user.name }"></c:out>    <br>    <c:out value="${user.niceName }"></c:out>    <br>    <c:out value="${user.age }"></c:out></body></html>

17.edit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%><!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>Edit user</title></head><body>    <c:url var="saveUrl" value="/student/${userAttribute.id}/save.do" />    <form:form modelAttribute="userAttribute" action="${saveUrl }">        <table>            <tr>                <td>ID:</td>                <td><form:input path="id" /></td>            </tr>            <tr>                <td>Name:</td>                <td><form:input path="name"/></td>            </tr>            <tr>                <td>Nice name:</td>                <td><form:input path="niceName"/></td>            </tr>            <tr>                <td>Age:</td>                <td><form:input path="age"/></td>            </tr>        </table>        <input type="submit" value="Save">    </form:form></body></html>

完工!


1 3
原创粉丝点击