`
shihuan830619
  • 浏览: 582749 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Spring4Mvc整合Hibernate4框架示例

阅读更多
今天用NetBeans8.1搭建了一套Spring4MVC+Hibernate4+PostgreSQL的基础框架,这套框架需要JDK1.7和Tomcat8.0.30。

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


第二步:开始搭建Spring4+Hibernate4框架。
先看一下工程结构图:







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

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/访问工程,截图如下:

数据库结果截图如下:



附件webvip.rar文件是工程源代码,项目所需jar包在abcdef830619的网易邮箱网盘的我的原创目录里。
  • 大小: 16.7 KB
  • 大小: 7.7 KB
  • 大小: 33.5 KB
  • 大小: 27.5 KB
  • 大小: 24.4 KB
  • 大小: 25.4 KB
  • 大小: 45.3 KB
  • 大小: 40.6 KB
  • 大小: 38 KB
分享到:
评论

相关推荐

    Spring4MVC整合Hibernate5 示例源码

    本示例源码"Spring4MVC整合Hibernate5"展示了如何将这两个强大的框架协同工作,以构建高效、灵活的Java Web应用。 Spring MVC是Spring框架的一个模块,专门用于处理Web应用程序的请求-响应模型。它提供了丰富的控制...

    Spring3mvc和hibernate整合示例代码.zip

    这个压缩包中的“Spring3mvc和hibernate整合示例代码”应该包含了上述所有步骤的实现。通过学习和理解这个示例,你可以了解到如何在实际项目中整合 Spring3 MVC 和 Hibernate,实现一个完整的 Java Web 应用。对于...

    spring4mvc_hibernate4入门示例

    导入并运行"spring4mvc_hibernate4"示例,开发者可以直观地理解这两个框架的协同工作方式,从而快速上手并应用于实际项目。学习并掌握Spring4MVC和Hibernate4的集成,不仅可以提高开发效率,还能增强系统的稳定性...

    spring mvc + spring + hibernate 全注解整合开发视频教程 11

    在本教程中,我们将深入探讨如何使用Spring MVC、Spring和Hibernate三大框架进行全注解的整合开发。这个视频教程系列的第11部分,重点可能是建立在前几部分的基础之上,进一步深化对这三个核心技术的理解和实践。 ...

    搭建Spring+Spring MVC+Hibernate开发框架

    在IT行业中,构建高效、可扩展的Web应用是至关重要的,而Spring、Spring MVC和Hibernate是Java领域中广泛使用的三大框架,它们各自负责不同的职责,共同构建了一个强大的开发环境。本篇文章将深入探讨如何利用这三大...

    spring4mvc_hibernate4示例

    《Spring4MVC与Hibernate4整合实战详解》 在当今的Java Web开发领域,Spring MVC和Hibernate是两个不可或缺的重要框架。Spring4MVC作为Spring框架的一部分,提供了强大的模型-视图-控制器(MVC)架构支持,而...

    Spring3mvc和hibernate整合示例代码

    在IT行业中,Spring3 MVC和Hibernate是两个非常重要的框架,它们分别用于构建Web应用程序的模型-视图-控制器(MVC)结构和持久层管理。本示例代码将这两个框架进行了整合,使得开发者能够更高效地开发基于Java的Web...

    spring mvc 与JPA/Hibernate的整合示例

    在Java Web开发中,Spring MVC和JPA(Java Persistence API)以及Hibernate作为ORM(对象关系映射)框架的实现,是构建高效、可维护性的应用的常见选择。本示例将探讨如何将这三个组件整合在一起,以实现一个完整的...

    spring boot jsp mvc jpa hibernate mysql 示例 sample

    在本示例中,我们将探讨如何整合 JSP、MVC、JPA 和 Hibernate 来构建一个与 MySQL 数据库交互的 Web 应用。 1. **Spring Boot MVC**:Spring Boot 提供了对 Spring MVC 的集成,使得构建 Web 应用变得简单。MVC...

    spring famework4整合hibernate4示例代码

    Spring Framework 4 与 Hibernate 4 的整合是Java开发中常见的技术组合,它们共同构建了高效、灵活的企业级应用。Spring 提供了丰富的容器管理、依赖注入以及AOP(面向切面编程)等功能,而Hibernate则是一个强大的...

    spring4+springmvc4+hibernate4 整合

    Spring、SpringMVC和Hibernate是Java开发中三大核心框架,它们的整合是企业级应用开发的常见模式,常被简称为SSH(Spring、SpringMVC、Hibernate)。在本项目"spring4+springmvc4+hibernate4 整合"中,我们将探讨这...

    Maven构建Spring3mvc和Hibernate

    ** Maven构建Spring3 MVC与Hibernate整合详解 ** 在软件开发中,Maven是一个强大的项目管理和构建工具,它简化了Java项目的构建过程,通过统一的构建生命周期和依赖管理,使得开发者可以更加专注于代码本身。本篇将...

    简单的spring+springMVC+hibernate框架整合

    总的来说,这个"简单的spring+springMVC+hibernate框架整合"项目是一个基础的学习资源,可以帮助开发者了解如何将这三个流行的Java框架集成在一起,构建一个完整的、具备数据访问和Web功能的应用程序。通过对项目的...

    Spring mvc+hibernate+mysql Demo

    【Spring MVC + Hibernate + MySQL 整合详解】 在IT领域,Spring MVC、Hibernate和MySQL是构建Web应用程序的常用技术栈。Spring MVC作为Spring框架的一部分,提供了强大的MVC(Model-View-Controller)架构,用于...

    Extjs + Spring MVC + hibernate + mysql

    标题 "Extjs + Spring MVC + hibernate + mysql" 涉及的是一个综合性的Web应用程序开发框架,结合了前端UI库、后端MVC框架、ORM工具和关系型数据库。让我们详细了解一下这些技术及其在实际项目中的应用。 1. ExtJS...

    spring mvc + hibernate4整合文档

    ### Spring MVC + Hibernate4 整合知识点解析 #### 一、Spring MVC 与 Hibernate 整合概述 在软件开发领域,尤其是Java Web应用开发中,框架间的整合是提高开发效率和系统性能的重要手段之一。本篇文章主要介绍了...

    spring mvc spring4.x hibernate4.注解方式注入

    在IT行业中,Spring MVC、Spring 4.x和Hibernate 4是三个非常重要的框架,它们各自在Web应用开发中承担着核心角色。Spring MVC是用于构建Web应用程序的模型-视图-控制器(MVC)框架,Spring 4.x是Spring框架的一个...

    spring mvc+hibernate+extjs代码示例

    这是一个基于Spring MVC、Hibernate和ExtJS的Web应用示例,主要展示了如何整合这三个技术来构建一个功能完善的后台管理系统。下面将分别对这三个技术及其整合方式进行详细介绍。 **Spring MVC** Spring MVC是Spring...

    spring-mvc+hibernate+druil+maven框架

    在IT领域,构建高效、可扩展的Web应用是常见的需求,而`Spring MVC`、`Hibernate`、`Druid`和`Maven`这四个框架和技术的组合正是解决这一问题的有效途径。这篇概述将深入探讨这些技术以及如何利用它们协同工作。 ...

Global site tag (gtag.js) - Google Analytics