欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring4Mvc整合Hibernate4框架示例

程序员文章站 2022-04-07 14:47:57
...
今天用NetBeans8.1搭建了一套Spring4MVC+Hibernate4+PostgreSQL的基础框架,这套框架需要JDK1.7和Tomcat8.0.30。

第一步:在PostgreSQL9.5里建两张数据表,笔者这里在实际框架中只用到了一个,因为对PostgreSQL还不是很熟悉,所以没做分页存储过程,笔者这里的PostgreSQL表中的主键id用的是sequence序列自动增长的。
Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 

第二步:开始搭建Spring4+Hibernate4框架。
先看一下工程结构图:
Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 
Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 
Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 
Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 
Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 
Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 

下面是工程中所有的配置文件代码:

web.xml文件代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    
    <display-name>shihuan</display-name>
	
    <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>*.do</url-pattern>
    </filter-mapping>
    
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>webvip.shihuan.root</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.WebAppRootListener</listener-class>
    </listener>

    <context-param>
            <param-name>logbackConfigLocation</param-name>
            <param-value>classpath:logback.xml</param-value>
    </context-param>
    <listener>
            <listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class>
    </listener>
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <listener>
            <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    
    <listener>
        <listener-class>com.shihuan.webss.SystemLoadListener</listener-class>
    </listener>
    
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>   
            <param-name>contextConfigLocation</param-name>   
            <param-value>classpath:dispatcher-servlet.xml</param-value>   
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            60
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>  
        <!--
        <welcome-file>index.jsp</welcome-file>
        -->
    </welcome-file-list>
</web-app>


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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"  default-autowire="byName">

    
    <context:property-placeholder location="classpath:*.properties" />
    <context:annotation-config />

    <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="${jdbc_driverClassName}"
        p:url="${jdbc_url}"
        p:username="${jdbc_username}"
        p:password="${jdbc_password}" />
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>  
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>  
                <prop key="hibernate.show_sql">true</prop>  
                <prop key="hibernate.format_sql">true</prop>  
                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>  
            </props>
        </property>
        <!-- 自动扫描实体对象com.shihuan.po的包结构中存放实体类 -->
        <property name="packagesToScan" value="com.shihuan.po" />
    </bean>
    
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
    
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="maxUploadSize" value="10485760" />
    </bean>

    <context:component-scan base-package="com.shihuan">
            <context:exclude-filter type="regex" expression="com.shihuan.*.controller" />
    </context:component-scan>
</beans>


dispatcher-servlet.xml文件代码:
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc" 
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <context:component-scan base-package="com.shihuan.web.controller"/>
    
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
    
    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

    <mvc:annotation-driven enable-matrix-variables="true"/>
    <mvc:default-servlet-handler />
    
    <mvc:interceptors>
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/admin/**"/>
            <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor" />
        </mvc:interceptor>
        <!--  
        <mvc:interceptor>
            <mvc:mapping path="/secure/*"/>
            <bean class="com.shihuan.web.interceptor.SecurityInterceptor" />
        </mvc:interceptor>
        -->
    </mvc:interceptors>
    
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="mediaTypes">
            <map>
                <entry key="atom" value="application/atom+xml"/>
                <entry key="html" value="text/html"/>
                <entry key="json" value="application/json"/>
            </map>
        </property>
        <property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/"/>
                    <property name="suffix" value=".jsp"/>
                </bean>
            </list>
        </property>
        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
            </list>
        </property>
    </bean>
    
    <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="siteLanguage"/>
    </bean>
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"/>

    <bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
    </bean>

    <mvc:resources mapping="/resources/**" location="/resources/"/>
	
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.Throwable">500</prop>
            </props>
        </property>
        <property name="warnLogCategory" value="WARN"></property>
        <property name="defaultErrorView" value="500"></property>
        <property name="defaultStatusCode" value="500"></property>
        <property name="statusCodes">
            <props>
                <prop key="404">404</prop>
                <prop key="500">500</prop>
            </props>
        </property>
    </bean>

</beans>


jdbc.properties文件代码:
jdbc_driverClassName=org.postgresql.Driver
jdbc_url=jdbc:postgresql://127.0.0.1:5432/postgres
jdbc_username=postgres
jdbc_password=postgres


logback.xml文件代码:
<configuration debug="true" scan="true" scanPeriod="30 seconds">
	<property name="Project_Name" value="webvip" />
	<property name="logDir" value="D:/logs/" /><!-- 日志根目录 -->
	<property name="archivesDirectory" value="${logDir}/archives/" />

	<property name="outFormat" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] [%thread] [%X{sessionId}] [%X{UserId}] %msg %caller{1}"></property>

	<jmxConfigurator />

	<appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<file>${logDir}${Project_Name}/Out${Project_Name}.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- rollover daily -->
			<fileNamePattern>${archivesDirectory}${Project_Name}/Out/${Project_Name}-%d{yyyy-MM-dd}.%i.zip</fileNamePattern>
			<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
				<maxFileSize>10MB</maxFileSize>
			</timeBasedFileNamingAndTriggeringPolicy>
		</rollingPolicy>
		<encoder>
			<pattern>${outFormat}</pattern>
		</encoder>
	</appender>
        <!--
	<appender name="SocketAppender" class="ch.qos.logback.classic.net.SocketAppender">
		<RemoteHost>192.168.100.11</RemoteHost>
		<Port>4560</Port>
		<ReconnectionDelay>170</ReconnectionDelay>
		<IncludeCallerData>true</IncludeCallerData>
	</appender>
        -->
	<appender name="ERRORLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<file>${logDir}${Project_Name}/Error${Project_Name}.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- rollover daily -->
			<fileNamePattern>${archivesDirectory}${Project_Name}/Error/${Project_Name}-%d{yyyy-MM-dd}.%i.zip</fileNamePattern>
			<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
				<maxFileSize>10MB</maxFileSize>
			</timeBasedFileNamingAndTriggeringPolicy>
		</rollingPolicy>
		<encoder>
			<pattern>${outFormat}</pattern>
		</encoder>
		<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
			<evaluator name="myEval">
				<!-- 输出error及以上 -->
				<expression>level>=40000</expression>
			</evaluator>
			<OnMatch>ACCEPT</OnMatch>
			<OnMismatch>DENY</OnMismatch>
		</filter>
	</appender>

	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
			<pattern>${outFormat}</pattern>
		</encoder>
	</appender>
	<appender name="sendMail" class="ch.qos.logback.classic.net.SMTPAppender">
		<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
			<evaluator name="myEval">
				<!-- 输出error及以上,并且"email:"开头的消息 -->
				<expression>message.startsWith("fatal:")</expression>
			</evaluator>
			<OnMatch>ACCEPT</OnMatch>
			<OnMismatch>DENY</OnMismatch>
		</filter>
		<SMTPHost>192.168.100.111</SMTPHost>
		<!-- <Username>${MAIL_USER}</Username>用户名 -->
		<!-- <Password>${MAIL_PWD}</Password>密码 -->
		<To>javatest@yeah.net</To>
		<From>${Project_Name}</From>
		<Subject>${Project_Name}Error: %logger{20} - %m</Subject>
		<layout class="ch.qos.logback.classic.html.HTMLLayout">
			<Pattern>${outFormat}</Pattern>
		</layout>
	</appender>
	<logger name="com.shihuan" level="debug" />
	<root level="info">
		<appender-ref ref="ROLLING" />
		<!-- <appender-ref ref="SocketAppender" />
                    <appender-ref ref="sendMail" />
                -->
		
		<appender-ref ref="STDOUT" />
		<appender-ref ref="ERRORLog" />
	</root>
</configuration>


下面介绍主要java代码,部分细节代码就不做详细介绍了,读者需要自己做参考。

SystemLoadListener.java代码如下:
package com.shihuan.webss;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 *
 * @author shihuan
 */
public class SystemLoadListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {
    protected static Logger logger = LoggerFactory.getLogger(SystemLoadListener.class);
	//参数
    private HttpServletRequest request;
    private ServletContext sc;

    // Public constructor is required by servlet spec
    public SystemLoadListener() {
    	
    }
	
    // -------------------------------------------------------
    // HttpSessionAttributeListener implementation
    // -------------------------------------------------------
	@Override
	public void attributeAdded(HttpSessionBindingEvent sbe) {
		/* This method is called when an attribute 
	        is added to a session.
	     */
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent sbe) {
		/* This method is called when an attribute
	        is removed from a session.
	     */
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent sbe) {
		/* This method is invoked when an attibute
	        is replaced in a session.
	     */
	}

	// -------------------------------------------------------
    // HttpSessionListener implementation
    // -------------------------------------------------------
	@Override
	public void sessionCreated(HttpSessionEvent se) {
//		System.out.println("shihuan11: session创建了!!!!!!" + se.getSession().getId());
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		/* Session is destroyed. */
		//TODO 调用authService
//		System.out.println("shihuan22: session过期了!!!!!!" + se.getSession().getId());
	}
	
	public void requestDestroyed(ServletRequestEvent srd) {

    }

    public void requestInitialized(ServletRequestEvent sri) {
        request = (HttpServletRequest)sri.getServletRequest();
    }

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		/* This method is invoked when the Servlet Context 
	        (the Web application) is undeployed or 
	        Application Server shuts down.
	     */
	}

	// -------------------------------------------------------
    // ServletContextListener implementation
    // -------------------------------------------------------
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		
		ServletContext context = sce.getServletContext();
        //取得appliction上下文
        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
        context.setAttribute("ac", ctx);
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(context);
        context.setAttribute("wac", wac);
        context.setAttribute("currequest", request);
    }
}


OpMessage.java文件代码:
package com.shihuan.web.page;

/**
 *
 * @author shihuan
 */
public class OpMessage {
    /**
    * @param success
    *  true 表示成功, false 表示失败
    * @param message
    */
   public OpMessage(boolean success, String message) {
           this.success = success;
           this.message = message;
           this.logResult = message;
   }

   public OpMessage(boolean success, String message, Object infoObj) {
           this.success = success;
           this.message = message;
           this.logResult = message;
           this.infoObj=infoObj;
   }

   public OpMessage(boolean success, String message, java.io.Serializable poID) {
           this.success = success;
           this.message = message;
           this.logResult = message;
           this.poID = poID;
   }
   public OpMessage(boolean success, String message, java.io.Serializable poID, Object infoObj) {
           this.success = success;
           this.message = message;
           this.logResult = message;
           this.poID = poID;
           this.infoObj=infoObj;
   }

   public OpMessage(boolean success, Exception ex) {
           this.success = success;
           this.message = ex.getMessage();
           this.logResult = ex.getMessage();
   }

   /**
    * 表示是否成功
    */
   private boolean success;
   /**
    * 表示返回信息
    */
   private String message;

   /**
    * 错误信息
    */
   private String logResult;

   /**
    * PK
    */
   java.io.Serializable poID;

   //作为返回信息
   private Object infoObj;

   public Object getInfoObj() {
           return infoObj;
   }

   public void setInfoObj(Object infoObj) {
           this.infoObj = infoObj;
   }

   public boolean getSuccess() {
           return success;
   }

   public void setSuccess(boolean success) {
           this.success = success;
   }

   public String getMessage() {
           return message;
   }

   public void setMessage(String message) {
           this.message = message;
   }

   public java.io.Serializable getPoID() {
           return poID;
   }

   public void setPoID(java.io.Serializable poID) {
           this.poID = poID;
   }

   public String getLogResult() {
           return logResult;
   }

   public void setLogResult(String logResult) {
           this.logResult = logResult;
   }
   public OpMessage(){

   }

   public static OpMessage getInstance(){
           return new OpMessage();
   }
   public OpMessage setOPSuccess(boolean isSuccess){
           this.setSuccess(isSuccess);
           return this;
   }
   public OpMessage setOPMessage(String msg){
           this.setMessage(msg);
           return this;
   }
   public OpMessage setOPPoID(java.io.Serializable msg){
           this.setPoID(msg);
           return this;
   }
   public OpMessage setOPInfoObj(Object infoObj){
           this.setInfoObj(infoObj);
           return this;
   }
   public OpMessage setOPLogResult(String logResult){
           this.setLogResult(logResult);
           return this;
   }
}


TestPgDao.java代码如下:
package com.shihuan.web.dao;

import java.util.Map;

/**
 *
 * @author shihuan
 */
public interface TestPgDao {
    public void insertData(Map params);
    public void updateData(Map params);
    public void queryData(Map params);
    public void deleteData(Map params);
}


TestPgDaoImpl.java代码如下:
package com.shihuan.web.dao.impl;

import com.shihuan.web.dao.TestPgDao;
import com.shihuan.web.util.UserHibernateDao;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

/**
 *
 * @author shihuan
 */
@Repository
public class TestPgDaoImpl extends UserHibernateDao implements TestPgDao {

    protected Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    
    @Override
    public void insertData(Map params) {
        String sql = "insert into company(name,age,address,salary) values (?,?,?,?)";
        Object[] objparams = new Object[4];
        objparams[0] = params.get("name");
        objparams[1] = Integer.parseInt(params.get("age").toString());
        objparams[2] = params.get("address");
        objparams[3] = Double.parseDouble(params.get("salary").toString());
        
        batchExecuteByArrs(sql, objparams);
    }

    @Override
    public void updateData(Map params) {
        String sql = "update company set name=? where id=?";
        batchExecuteByMulti(sql, "大家好", 1);
    }

    @Override
    public void queryData(Map params) {
        String sql = "select id,name,age,address,salary from company";
        
    }

    @Override
    public void deleteData(Map params) {
        String sql = "delete from company where id=2";
        
    }
    
}


TestPgService.java代码如下:
package com.shihuan.web.service;

import java.util.Map;

/**
 *
 * @author shihuan
 */
public interface TestPgService {
    public void insertData(Map params);
    public void updateData(Map params);
    public void queryData(Map params);
    public void deleteData(Map params);
}


TestPgServiceImpl.java代码如下:
package com.shihuan.web.service.impl;

import com.shihuan.web.dao.TestPgDao;
import com.shihuan.web.service.TestPgService;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author shihuan
 */
@Service
public class TestPgServiceImpl implements TestPgService {

    @Autowired
    TestPgDao testPgDao;
    
    @Override
    @Transactional(readOnly = false, rollbackFor = Throwable.class)
    public void insertData(Map params) {
        testPgDao.insertData(params);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Throwable.class)
    public void updateData(Map params) {
        testPgDao.updateData(params);
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Throwable.class)
    public void queryData(Map params) {
        testPgDao.queryData(params);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Throwable.class)
    public void deleteData(Map params) {
        testPgDao.deleteData(params);
    }
    
}


BaseControl.java代码如下:
package com.shihuan.web.controller;

import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

/**
 *
 * @author shihuan
 */
public abstract class BaseControl {
    
    protected Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    
    protected boolean useRedirect = false;
    public static final String ENTRY_URL = "ENTRY_URL";
    
    @InitBinder
    public void InitBinder(WebDataBinder dataBinder) {
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
        dataBinder.registerCustomEditor(Integer.class, new PropertyEditorSupport() {
            public void setAsText(String value) {
                try {
                    if (value == null || "".equals(value)) {
                        setValue(0);
                    } else {
                        setValue(Integer.parseInt(value));
                    }
                } catch (Exception e) {
                    setValue(0);
                }
            }

            public String getAsText() {
                Object obj = getValue();
                if (obj != null) {
                    return obj.toString();
                }
                return "";
            }

        });
    }

    @SuppressWarnings("rawtypes")
	public Map getParmMap(HttpServletRequest p_request) {
        HashMap map = new HashMap();
        Map orimap = p_request.getParameterMap();
        Set keys = orimap.keySet();
        for (Object key1 : keys) {
            String key = (String) key1;
            String[] value = (String[]) orimap.get(key);
            if(StringUtils.endsWith(key, "[]")){
        		key = key.substring(0, key.length()-2);
        	}
            if (value.length > 1) {
            	StringBuffer sb = new StringBuffer();
            	sb.append(" * Para : " + key + " = '[");
            	boolean firstFlag = true;
            	for(String logvalue : value){
            		if(firstFlag){
            			firstFlag = false;
            		}else{
            			sb.append(",");
            		}
            		sb.append(logvalue);
            	}
            	logger.debug(sb.toString() + "]'  * ");
                map.put(key, value);
            } else {
                logger.debug(" * Para : " + key + " = '" + value[0] + "'  * ");
                map.put(key, value[0]);
            }
        }
        return map;
    }

    /**
     * 功能: 获取当前登录用户的userid
     * */
    public int getUserid(HttpServletRequest p_request){
    	int resultid = p_request.getSession().getAttribute("curuserid")==null ? 0 : Integer.parseInt(p_request.getSession().getAttribute("curuserid").toString());
    	return resultid;
    } 
    /**
     * 功能: 获取当前登录用户的userName
     * */
    public String getUserName(HttpServletRequest p_request){
    	String resultName = p_request.getSession().getAttribute("username")==null ? "" : p_request.getSession().getAttribute("username").toString();
    	return resultName;
    }
    
    /**
     * 功能: 获取当前登录用户的公司id
     * */
    public int getOrganizationId(HttpServletRequest p_request){
    	int resultid = p_request.getSession().getAttribute("organizationid")==null ? 0 : Integer.parseInt(p_request.getSession().getAttribute("organizationid").toString());
    	return resultid;
    }
    
    //Initialize global variables
    public final void init() {
    	
    }

    //Clean up resources
    public final void destroy() {
    	
    }
}


IndexController.java代码如下:
package com.shihuan.web.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 * @author shihuan
 */
@Controller
@RequestMapping(value = "/")
public class IndexController {
    protected Logger logger = LoggerFactory.getLogger(getClass().getName());
    
    @RequestMapping(value = "index.do")
    public String testPgListPage(HttpServletRequest request) {
        return "appbusiness/testpg/TestPgAdd";
    }
}


TestPgController.java代码如下:
package com.shihuan.web.controller;

import com.shihuan.web.page.OpMessage;
import com.shihuan.web.service.TestPgService;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author shihuan
 */
@Controller
@RequestMapping(value = "appbusiness/testpg/")
public class TestPgController extends BaseControl {
    protected Logger logger = LoggerFactory.getLogger(getClass().getName());
    
    @Autowired
    private TestPgService testPgService;
    
    @RequestMapping(value = "addCompanyMsg.do")
    @ResponseBody
    public OpMessage addCompany(HttpServletRequest request, HttpServletResponse response) throws Exception {
        OpMessage om = null;
        try {
                Map params = getParmMap(request);
//                params.put("curuserid", getUserid(request));
                testPgService.insertData(params);
                om = new OpMessage(true, "添加公司信息成功");
        } catch (Exception e) {
                om = new OpMessage(false, "后台数据查询错误,请通知系统管理员处理。");
                logger.error(e.getMessage(), e);
                e.printStackTrace();
        }
        return om;
    }

}


SimpleHibernateDao.java文件代码太多,都是执行SQL语句的方法,这里只做结构介绍:
package com.shihuan.web.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.SessionFactoryUtils;

import com.shihuan.config.ConfigCommon;
import com.shihuan.util.AssertUtil;
import com.shihuan.exception.SysException;


/**
 *
 * @author shihuan
 */
public abstract class SimpleHibernateDao {
    
    protected Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    
    public static int queryTimeout = 0;

    /**
     * 取得sessionFactory.
     */
    abstract public SessionFactory getSessionFactory();
    
    /**
     * 取得当前Session.
     */
    public Session getSession() {
        return getSessionFactory().getCurrentSession();
    }

    /**
     * 功能: insert、update或者delete一条数据
     * @param sql
     * @param params sql语句参数数组
     * @return 返回执行条数
     * */
    public int batchExecuteByArrs(String sql, Object[] params) {
    	AssertUtil.notEmptyAndNull(sql, "sql语句不允许为空");
    	SQLQuery sqlquery = getSession().createSQLQuery(sql);
    	StringBuilder sb = new StringBuilder();
		sb.append(ConfigCommon.SQLFLAG).append(sql).append(ConfigCommon.LINEFEEDFLAG).append(ConfigCommon.PARAMSFLAG);
		boolean isFirst = true;
		if(params.length > 0){
			for(int i=0; i<params.length; i++){
	    		sqlquery.setParameter(i, params[i]);
	    		if(isFirst){
	    			sb.append(params[i]);
	    			isFirst = false;
	    		} else {
	    			sb.append(ConfigCommon.SEPARATEFLAG).append(params[i]);
	    		}
	    	}
		}
		logger.info(sb.toString());
    	return sqlquery.executeUpdate();
    }

/**
     * 功能: insert、update或者delete一条数据
     * @param sql
     * @param params sql语句对应的参数
     * @return 返回执行条数
     * */
    public int batchExecuteByMulti(String sql, Object... params) {
    	AssertUtil.notEmptyAndNull(sql, "sql语句不允许为空");
    	SQLQuery sqlquery = getSession().createSQLQuery(sql);
    	sqlquery.setTimeout(queryTimeout);
    	StringBuilder sb = new StringBuilder();
		sb.append(ConfigCommon.SQLFLAG).append(sql).append(ConfigCommon.LINEFEEDFLAG).append(ConfigCommon.PARAMSFLAG);
		boolean isFirst = true;
		if(params.length > 0){
			for(int i=0; i<params.length; i++){
	    		sqlquery.setParameter(i, params[i]);
	    		if(isFirst){
	    			sb.append(params[i]);
	    			isFirst = false;
	    		} else {
	    			sb.append(ConfigCommon.SEPARATEFLAG).append(params[i]);
	    		}
	    	}
		}
    	logger.info(sb.toString());
    	return sqlquery.executeUpdate();
    }

    
    ......
    //这里注意Spring4中获取JDBC连接的写法变了,放弃Hibernate3中的getSession().connection()方法,改为conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();


UserHibernateDao.java代码如下:
package com.shihuan.web.util;

import javax.annotation.Resource;
import org.hibernate.SessionFactory;

/**
 *
 * @author shihuan
 */
public class UserHibernateDao extends SimpleHibernateDao {
    @Resource(name="sessionFactory")
    protected SessionFactory sessionFactory;

    @Override
    public SessionFactory getSessionFactory() {
            return sessionFactory;
    }
}


TestPgAdd.js文件代码如下:
function addCompany() {
    if($("#name").val().trim() == ""){
            alert("姓名不允许为空!");
            $("#name").focus();
            return;
    }else{
            var url="appbusiness/testpg/addCompanyMsg.do";
            var params={"name":$("#name").val(),"age":$("#age").val(),"address":$("#address").val(),"salary":$("#salary").val()};
            $.post(url, params, function(json){
                if (json.success) {
                        alert(json.message);
                        return;
                }
            },"json");
    }
}


TestPgAdd.jsp文件代码如下:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ page isELIgnored="false" %>
<fmt:requestEncoding value="UTF-8"/>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<c:set var="requestURI" value="${pageContext.request.servletPath}"/>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>TestPgAdd Company</title>
        <script type="text/javascript" src="${ctx}/resources/js/jquery-1.12.0.min.js"></script>
        <script type="text/javascript" src="${ctx}/appbusiness/testpg/js/TestPgAdd.js"></script>
    </head>
    <body>
        <form id="testpgform" name="testpgform" action="appbusiness/testpg/addCompanyMsg.do" method="post">
            <table>
                <tr>
                    <td>姓名</td>
                    <td>年龄</td>
                    <td>地址</td>
                    <td>薪资</td>
                </tr>
                <tr>
                    <td><input id="name" name="name" /></td>
                    <td><input id="age" name="age" /></td>
                    <td><input id="address" name="address" /></td>
                    <td><input id="salary" name="salary" /></td>
                </tr>
            </table>
            <br />
            <input type="button" id="btn" name="btn" value="提交" onclick="addCompany();" />
        </form>
    </body>
</html>


redirect.jsp代码如下:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% response.sendRedirect("index.do"); %>


在浏览器中输入http://127.0.0.1:8080/webvip/访问工程,截图如下:
Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 
数据库结果截图如下:
Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 


附件webvip.rar文件是工程源代码,项目所需jar包在abcdef830619的网易邮箱网盘的我的原创目录里。
  • Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 
  • 大小: 16.7 KB
  • Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 
  • 大小: 7.7 KB
  • Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 
  • 大小: 33.5 KB
  • Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 
  • 大小: 27.5 KB
  • Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 
  • 大小: 24.4 KB
  • Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 
  • 大小: 25.4 KB
  • Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 
  • 大小: 45.3 KB
  • Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 
  • 大小: 40.6 KB
  • Spring4Mvc整合Hibernate4框架示例
            
    
    博客分类: J2EESpring4hibernate4postgresql spring4hibernate4postgresql 
  • 大小: 38 KB

上一篇: 二维数组

下一篇: 数字显示