- 浏览: 582150 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (174)
- JBPM (3)
- WWF (0)
- JavaScript (11)
- J2EE (40)
- OperationSystem (11)
- 数据库 (12)
- CSS (1)
- Ajax (2)
- J2SE (30)
- Tools (10)
- 服务器中间件 (3)
- 异常 (0)
- Flex (5)
- jQuery (11)
- html (9)
- Ejb (1)
- HTML5 Shiv–让该死的IE系列支持HTML5吧 (1)
- Spring (9)
- Quartz (3)
- log4j (1)
- maven (1)
- cpdetector (1)
- JSON (1)
- log4jdbc (1)
- asm (8)
- FusionCharts (1)
- jqplot (1)
- highcharts (1)
- excanvas (1)
- html5 (1)
- jpcap介绍 (1)
- weblogic (3)
- URLURLClassLoader (0)
- URLClassLoader (1)
- ant (2)
- ivy (2)
- nexus (1)
- IT (0)
- LoadRunner (1)
- SCSS (1)
- ruby (1)
- webstorm (1)
- typescript (1)
- Jboss7 (1)
- wildfly (1)
- oracle (5)
- esb (0)
- dubbo (2)
- zookeeper (3)
- eclipse (1)
- Android (2)
- Studio (1)
- Google (1)
- 微信 (1)
- 企业号 (1)
- Linux (13)
- Oracle12c (1)
- Hadoop (1)
- InletexEMC (1)
- Windows (1)
- Netty (3)
- Marshalling (2)
- Protobuf (1)
- gcc (1)
- Git (1)
- GitLab (1)
- shell (2)
- java (3)
- Spring4 (1)
- hibernate4 (1)
- postgresql (1)
- ApacheServer (2)
- Tomcat (2)
- ApacheHttpServer (2)
- realvnc (1)
- redhat (7)
- vncviewer (1)
- LVS (4)
- LVS-DR (1)
- RedHat6.5 (5)
- LVS-NAT (1)
- LVS-IPTUNNEL (2)
- LVS-TUN (1)
- keepalived (2)
- yum (1)
- iso (1)
- VMware (1)
- redhat5 (1)
- ha (1)
- nginx (2)
- proguard (1)
- Mat (1)
- DTFJ (1)
- axis2 (1)
- web service (1)
- centos (1)
- random (1)
- urandom (1)
- apache (1)
- IBM (1)
- cve (1)
- 漏洞 (1)
- JDBC (1)
- DataSource (1)
- jdk (1)
- tuxedo (2)
- wtc (1)
最新评论
-
skying007:
好资料,谢谢分享给啊
FusionCharts在服务器端导出图片(J2EE版) -
cgnnzg:
大神好 可以发一份源码给我学习么 多谢了 978241085 ...
springmvc+dubbo+zookeeper -
jifengjianhao:
求源码:854606899@qq.com
springmvc+dubbo+zookeeper -
wdloyeu:
shihuan8@163.com邮箱网盘在哪,没找到。能给份源 ...
Java Socket长连接示例代码 -
huangshangyuanji:
求代码:45613032@qq.com
springmvc+dubbo+zookeeper
今天用NetBeans8.1搭建了一套Spring4MVC+Hibernate4+PostgreSQL的基础框架,这套框架需要JDK1.7和Tomcat8.0.30。
第一步:在PostgreSQL9.5里建两张数据表,笔者这里在实际框架中只用到了一个,因为对PostgreSQL还不是很熟悉,所以没做分页存储过程,笔者这里的PostgreSQL表中的主键id用的是sequence序列自动增长的。
第二步:开始搭建Spring4+Hibernate4框架。
先看一下工程结构图:
下面是工程中所有的配置文件代码:
web.xml文件代码如下:
applicationContext.xml文件代码:
dispatcher-servlet.xml文件代码:
jdbc.properties文件代码:
logback.xml文件代码:
下面介绍主要java代码,部分细节代码就不做详细介绍了,读者需要自己做参考。
SystemLoadListener.java代码如下:
OpMessage.java文件代码:
TestPgDao.java代码如下:
TestPgDaoImpl.java代码如下:
TestPgService.java代码如下:
TestPgServiceImpl.java代码如下:
BaseControl.java代码如下:
IndexController.java代码如下:
TestPgController.java代码如下:
SimpleHibernateDao.java文件代码太多,都是执行SQL语句的方法,这里只做结构介绍:
UserHibernateDao.java代码如下:
TestPgAdd.js文件代码如下:
TestPgAdd.jsp文件代码如下:
redirect.jsp代码如下:
在浏览器中输入http://127.0.0.1:8080/webvip/访问工程,截图如下:
数据库结果截图如下:
附件webvip.rar文件是工程源代码,项目所需jar包在abcdef830619的网易邮箱网盘的我的原创目录里。
第一步:在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的网易邮箱网盘的我的原创目录里。
- webvip.rar (251.4 KB)
- 下载次数: 2
发表评论
-
Spring4配置properties文件的一点儿细节
2016-02-04 15:40 2801http://repo.spring.io/release/o ... -
JavaWeb发送信息到微信公众平台的企业号
2015-11-01 22:42 3804首先到微信公众平台申请微信企业号: https://qy.we ... -
springmvc+dubbo+zookeeper
2015-09-22 11:34 12025笔者这里使用的是apache- ... -
OracleAS10g安装配置与部署
2015-07-01 20:59 709先到Oracle官方下载OracleAS10的安装包,截图如下 ... -
java和spring使用weblogic数据源配置
2014-10-13 11:29 3015需要weblogic.jar和jrmpclient.jar ... -
一套基本的SpringMvc工程所需要的最基本jar包(pom.xml)
2014-08-19 16:38 1913附件里是pom.xml文件。 -
html的form表单提交得不到参数问题
2014-07-25 16:13 1861今天同事问我他的form表单按submit方式提交,在Java ... -
Spring3Mvc导出PDF的3种形式+导出excel的两种形式(exportAnimal.do)
2014-07-19 22:55 1145附件里SpringMvc导出PDF和Excel的示例代码。 ... -
Java利用中国网建SMS短信通平台发送手机短信
2014-04-26 21:55 2243JAVA发送手机短信,流传有几种方法: (1)使用webser ... -
在Java中发送电子邮件
2014-04-26 18:42 9610要先申请一个网易的126邮箱和一个新浪的com邮箱。 以下程 ... -
cpdetector_1.0.10_binary下载
2014-03-26 20:53 1040附件里是cpdetector_1.0.10_binary.ra ... -
在Java代码中用Axis2调用DotNet语言的WebService程序
2014-02-19 15:19 2575package com.shihuan.ymail.com ... -
SpringMvc多语言配置
2014-01-14 16:01 14432applicationContext.xml文件中加入如下代码 ... -
log4j多级别多输出文件的配置
2013-07-22 21:28 1573以下代码需要log4j-1.2.17.jar的支持。 B ... -
mysql和Oracle在对clob和blob字段的处理
2012-08-25 18:50 30906一、MySQL与Oracle数据库如何处理Clob,Bl ... -
Spring3Mvc+Hibernate整合Axis2发布WebService并配置Quartz调度
2012-08-05 12:54 2217附件里是笔者的源代码,相关的jar包在笔者的abcdef的16 ... -
Lucene案例
2012-06-10 15:15 2610IndexerMmseg4j.java代码如下: import ... -
Mina入门程序
2012-06-02 15:05 1150附件里是Mina的入门程序。 http://mina.apa ... -
让Hibernate的执行语句看见完整参数
2012-04-29 10:09 1046http://www.ibm.com/developerwor ... -
ant打包Web工程
2012-03-18 13:13 3499build.properties文件内容如下: project ...
相关推荐
本示例源码"Spring4MVC整合Hibernate5"展示了如何将这两个强大的框架协同工作,以构建高效、灵活的Java Web应用。 Spring MVC是Spring框架的一个模块,专门用于处理Web应用程序的请求-响应模型。它提供了丰富的控制...
这个压缩包中的“Spring3mvc和hibernate整合示例代码”应该包含了上述所有步骤的实现。通过学习和理解这个示例,你可以了解到如何在实际项目中整合 Spring3 MVC 和 Hibernate,实现一个完整的 Java Web 应用。对于...
导入并运行"spring4mvc_hibernate4"示例,开发者可以直观地理解这两个框架的协同工作方式,从而快速上手并应用于实际项目。学习并掌握Spring4MVC和Hibernate4的集成,不仅可以提高开发效率,还能增强系统的稳定性...
在本教程中,我们将深入探讨如何使用Spring MVC、Spring和Hibernate三大框架进行全注解的整合开发。这个视频教程系列的第11部分,重点可能是建立在前几部分的基础之上,进一步深化对这三个核心技术的理解和实践。 ...
在IT行业中,构建高效、可扩展的Web应用是至关重要的,而Spring、Spring MVC和Hibernate是Java领域中广泛使用的三大框架,它们各自负责不同的职责,共同构建了一个强大的开发环境。本篇文章将深入探讨如何利用这三大...
《Spring4MVC与Hibernate4整合实战详解》 在当今的Java Web开发领域,Spring MVC和Hibernate是两个不可或缺的重要框架。Spring4MVC作为Spring框架的一部分,提供了强大的模型-视图-控制器(MVC)架构支持,而...
在IT行业中,Spring3 MVC和Hibernate是两个非常重要的框架,它们分别用于构建Web应用程序的模型-视图-控制器(MVC)结构和持久层管理。本示例代码将这两个框架进行了整合,使得开发者能够更高效地开发基于Java的Web...
在Java Web开发中,Spring MVC和JPA(Java Persistence API)以及Hibernate作为ORM(对象关系映射)框架的实现,是构建高效、可维护性的应用的常见选择。本示例将探讨如何将这三个组件整合在一起,以实现一个完整的...
在本示例中,我们将探讨如何整合 JSP、MVC、JPA 和 Hibernate 来构建一个与 MySQL 数据库交互的 Web 应用。 1. **Spring Boot MVC**:Spring Boot 提供了对 Spring MVC 的集成,使得构建 Web 应用变得简单。MVC...
Spring Framework 4 与 Hibernate 4 的整合是Java开发中常见的技术组合,它们共同构建了高效、灵活的企业级应用。Spring 提供了丰富的容器管理、依赖注入以及AOP(面向切面编程)等功能,而Hibernate则是一个强大的...
Spring、SpringMVC和Hibernate是Java开发中三大核心框架,它们的整合是企业级应用开发的常见模式,常被简称为SSH(Spring、SpringMVC、Hibernate)。在本项目"spring4+springmvc4+hibernate4 整合"中,我们将探讨这...
** Maven构建Spring3 MVC与Hibernate整合详解 ** 在软件开发中,Maven是一个强大的项目管理和构建工具,它简化了Java项目的构建过程,通过统一的构建生命周期和依赖管理,使得开发者可以更加专注于代码本身。本篇将...
总的来说,这个"简单的spring+springMVC+hibernate框架整合"项目是一个基础的学习资源,可以帮助开发者了解如何将这三个流行的Java框架集成在一起,构建一个完整的、具备数据访问和Web功能的应用程序。通过对项目的...
【Spring MVC + Hibernate + MySQL 整合详解】 在IT领域,Spring MVC、Hibernate和MySQL是构建Web应用程序的常用技术栈。Spring MVC作为Spring框架的一部分,提供了强大的MVC(Model-View-Controller)架构,用于...
标题 "Extjs + Spring MVC + hibernate + mysql" 涉及的是一个综合性的Web应用程序开发框架,结合了前端UI库、后端MVC框架、ORM工具和关系型数据库。让我们详细了解一下这些技术及其在实际项目中的应用。 1. ExtJS...
### Spring MVC + Hibernate4 整合知识点解析 #### 一、Spring MVC 与 Hibernate 整合概述 在软件开发领域,尤其是Java Web应用开发中,框架间的整合是提高开发效率和系统性能的重要手段之一。本篇文章主要介绍了...
在IT行业中,Spring MVC、Spring 4.x和Hibernate 4是三个非常重要的框架,它们各自在Web应用开发中承担着核心角色。Spring MVC是用于构建Web应用程序的模型-视图-控制器(MVC)框架,Spring 4.x是Spring框架的一个...
这是一个基于Spring MVC、Hibernate和ExtJS的Web应用示例,主要展示了如何整合这三个技术来构建一个功能完善的后台管理系统。下面将分别对这三个技术及其整合方式进行详细介绍。 **Spring MVC** Spring MVC是Spring...
在IT领域,构建高效、可扩展的Web应用是常见的需求,而`Spring MVC`、`Hibernate`、`Druid`和`Maven`这四个框架和技术的组合正是解决这一问题的有效途径。这篇概述将深入探讨这些技术以及如何利用它们协同工作。 ...