美文网首页java工具癖JAVA基础(未看)
手把手教你写一个springMVC+spring+hiberna

手把手教你写一个springMVC+spring+hiberna

作者: 帷幕丶归心 | 来源:发表于2017-06-30 11:49 被阅读352次

闲话少说,现在开始。

一、开始环境

开发工具,MyEclipse 2017

数据库 mysql 5.6

服务器 tomcat 8

二、创建工程

一直next,直到下图 finish

三、导入jar包

以上全部导入到WEB-INF/lib下

四、配置springmvc spring hibernate 以及数据库

1.在src下创建package用来存放配置文件,包名为config(后面会用到)

2.其次在src下创建其他package,如下图

3.在config下创建log4j.properties,打印输出日志,内容如下

log4j.rootCategory=INFO, stdout , R

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n

log4j.appender.R=org.apache.log4j.DailyRollingFileAppender

log4j.appender.R.File=${isob.root}/log/isob.log

log4j.appender.logfile.MaxFileSize=4096KB

log4j.appender.R.layout=org.apache.log4j.PatternLayout

# Keep three backup files.

log4j.appender.logfile.MaxBackupIndex=3

# Pattern to output: date priority [category] - message

log4j.appender.logfile.layout=org.apache.log4j.PatternLayout

log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

log4j.logger.com.opensymphony.xwork2=ERROR

# Control logging for other open source packages

log4j.logger.org.springframework=ERROR

log4j.logger.org.quartz=ERROR

log4j.logger.net.sf.ehcache=ERROR

log4j.logger.net.sf.navigator=ERROR

log4j.logger.org.apache.commons=ERROR

log4j.logger.org.apache.struts=ERROR

# Struts OgnlUtil issues unimportant warnings

log4j.logger.com.opensymphony.xwork2.util.OgnlUtil=error

log4j.logger.com.opensymphony.xwork2.ognl.OgnlValueStack=error

log4j.logger.java.sql.ResultSet=INFO

log4j.logger.org.apache=INFO

log4j.logger.java.sql.Connection=DEBUG

log4j.logger.java.sql.Statement=DEBUG

log4j.logger.java.sql.PreparedStatement=DEBUG

#log4j.logger.org.hibernate.ps.PreparedStatementCache=WARN

#log4j.logger.org.hibernate=DEBUG

log4j.logger.org.hibernate=ERROR

#log4j.logger.org.logicalcobwebs=WARN

4.创建数据库

数据库名称自定义

t_users表,我们用来做测试,包含以下字段

encryption为密码加密字段

5.在config下创建jdbc.properties,数据库登录信息

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc\:mysql\://127.0.0.1\:3306/springmvc?useUnicode\=true&characterEncoding\=utf8

jdbc.username=root

jdbc.password=123456

hibernate.dialect=org.hibernate.dialect.MySQLDialect

hibernate.show_sql=true

6.在config下创建spring-common.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:context="http://www.springframework.org/schema/context"

xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd

http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd

http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd

">

<!--加载数据库配置文件-->

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

<!--数据连接池-->

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"

destroy-method="close">

<property name="driverClass">

<value>${jdbc.driver}</value>

</property>

<property name="jdbcUrl">

<value>${jdbc.url}</value>

</property>

<property name="user" value="${jdbc.username}" />

<property name="password" value="${jdbc.password}" />

<!-- c3p0 配置 -->

<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->

<property name="acquireIncrement" value="3" />

<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->

<property name="acquireRetryAttempts" value="30" />

<property name="acquireRetryDelay" value="1000" />

<property name="autoCommitOnClose" value="false" />

<!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。 但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试获取连接失败后该数据源将申明已断开并永久关闭。 Default: false -->

<property name="breakAfterAcquireFailure" value="false" />

<property name="checkoutTimeout" value="5000" />

<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->

<property name="idleConnectionTestPeriod" value="60" />

<!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。 Default: 3 -->

<property name="initialPoolSize" value="10" />

<property name="loginTimeout" value="1800" />

<!--连接池中保留的最小连接数。 -->

<property name="minPoolSize" value="5" />

<!--连接池中保留的最大连接数。 Default: 15 -->

<property name="maxPoolSize" value="15" />

<!--最大空闲时间,60秒内未使用则连接被丢弃。 若为0则永不丢弃。 Default: 0 -->

<property name="maxIdleTime" value="60" />

<property name="maxStatements" value="100" />

<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。 但由于预缓存的statements 属于单个connection而不是整个连接池。

所以设置这个参数需要考虑到多方面的因素。 如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->

<property name="maxStatementsPerConnection" value="100" />

<property name="numHelperThreads" value="3" />

<property name="propertyCycle" value="300" />

<property name="preferredTestQuery" value="true" />

<property name="testConnectionOnCheckin" value="true" />

<!--因性能消耗大请只在需要的时候使用它。 如果设为true那么在每个connection提交的 时候都将校验其有效性。 建议使用idleConnectionTestPeriod或automaticTestTable等方法来提升连接测试的性能。Default: false -->

<property name="testConnectionOnCheckout" value="false" />

<property name="usesTraditionalReflectiveProxies" value="false" />

</bean>

<bean id="sessionFactory"

class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

<property name="dataSource" ref="dataSource" />

<property name="hibernateProperties">

<props>

<prop key="hibernate.dialect">${hibernate.dialect}</prop>

<prop key="hibernate.show_sql">true</prop>

<prop key="hibernate.format_sql">false</prop>

</props>

</property>

<!-- 自动扫描注解方式配置的hibernate类文件 -->

<property name="packagesToScan">

<list>

<value>com.deilsky.springmvc.entity</value>

</list>

</property>

</bean>

<!-- 配置事务管理器 -->

<bean id="transactionManager"

class="org.springframework.orm.hibernate4.HibernateTransactionManager">

<property name="sessionFactory" ref="sessionFactory" />

</bean>

<!-- 配置事务异常封装 -->

<bean id="persistenceExceptionTranslationPostProcessor"

class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

<!-- 配合和完成了事务切面的定义 -->

<!-- 使用强大的切点表达式是语言轻松定义目标方法 -->

<aop:config proxy-target-class="true">

<!-- 通过aop定义事务增强切面 -->

<aop:pointcut expression=" execution(* com.deilsky.springmvc.service.*.*(..))"

id="serviceMethod" />

<!-- 引用事务增强 -->

<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" />

</aop:config>

<!-- 事务增强 -->

<!-- 配置事务通知属性 -->

<tx:advice id="txAdvice" transaction-manager="transactionManager">

<!-- 定义事务传播属性 -->

<tx:attributes>

<tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception" />

<tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception" />

<tx:method name="del*" propagation="REQUIRED" rollback-for="java.lang.Exception" />

<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception" />

<tx:method name="*" read-only="true" />

</tx:attributes>

</tx:advice>

6.在src下创建spring-mvc.xml,用来配置springmvc

<?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:aop="http://www.springframework.org/schema/aop"

xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"

xmlns:context="http://www.springframework.org/schema/context"

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.3.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-4.3.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd

http://www.springframework.org/schema/util

http://www.springframework.org/schema/util/spring-util-4.3.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"

default-autowire="byName">

<!--启用自动扫描 -->

<context:component-scan base-package="com.deilsky.springmvc">

<context:exclude-filter type="regex" expression=".(dao|service.impl)" />

</context:component-scan>

<aop:aspectj-autoproxy />

<!-- 开启注解 -->

<mvc:annotation-driven />

<!-- 静态资源(js/image)的访问 -->

<mvc:resources location="/plugins/" mapping="/plugins/**" />

<!-- 定义视图解析器 -->

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/views/"></property>

<property name="suffix" value=".jsp"></property>

</bean>

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">

<property name="messageConverters">

<list>

<bean class="org.springframework.http.converter.FormHttpMessageConverter" />

<bean class="org.springframework.http.converter.StringHttpMessageConverter">

<property name="supportedMediaTypes">

<list>

<value>text/plain;charset=UTF-8</value>

</list>

</property>

<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">

<property name="objectMapper">

<bean class="com.fasterxml.jackson.databind.ObjectMapper" />

</property>

</bean>

</list>

</property>

</bean>

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<property name="maxInMemorySize" value="40960"></property>

<property name="maxUploadSize" value="10495760000"></property>

<property name="defaultEncoding" value="UTF-8"></property>

</bean>

</beans>

7.修改web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/javaee"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

version="3.0">

<filter>

<filter-name>sitemesh</filter-name>

<filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>sitemesh</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<filter>

<filter-name>encodingFilter</filter-name>

<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

<init-param>

<param-name>encoding</param-name>

<param-value>UTF-8</param-value>

</init-param>

<init-param>

<param-name>forceEncoding</param-name>

<param-value>true</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>encodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<context-param>

<param-name>log4jConfigLocation</param-name>

<param-value>/WEB-INF/classes/config/log4j.properties</param-value>

</context-param>

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath*:config/spring-*.xml</param-value>

</context-param>

<context-param>

<param-name>webAppRootKey</param-name>

<param-value>springmvc.root</param-value>

</context-param>

<listener>

<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>

</listener>

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

<listener>

<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>

</listener>

<servlet>

<servlet-name>springMVC</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath*:config/spring-mvc.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>springMVC</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>

<session-config>

<session-timeout>40</session-timeout>

</session-config>

<filter-mapping>

<filter-name>encodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<filter>

<filter-name>openSession</filter-name>

<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>

<init-param>

<param-name>singleSession</param-name>

<param-value>false</param-value>

</init-param>

<init-param>

<param-name>sessionFactoryBeanName</param-name>

<param-value>sessionFactory</param-value>

</init-param>

<init-param>

<param-name>flushMode</param-name>

<param-value>AUTO</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>openSession</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

</web-app>

8.在WebRoot下,创建资源路径decorators(装饰器页面),views(存放jsp页面),plugins(存放css,js)

9.在WEB-INF下创建sitemesh.xml 用来配置装饰器信息

<sitemesh>

<property name="decorators-file" value="/WEB-INF/decorators.xml" />

<excludes file="${decorators-file}" />

<page-parsers>

<parser content-type="text/html"

<class="com.opensymphony.module.sitemesh.parser.HTMLPageParser" />

</page-parsers>

<decorator-mappers>

<mapper class="com.opensymphony.module.sitemesh.mapper.PageDecoratorMapper">

<param name="property.1" value="meta.decorator" />

<param name="property.2" value="decorator" />

</mapper>

<mapper class="com.opensymphony.module.sitemesh.mapper.FrameSetDecoratorMapper"></mapper>

<mapper class="com.opensymphony.module.sitemesh.mapper.AgentDecoratorMapper">

<param name="match.MSIE" value="ie" />

<param name="match.Mozilla [" value="ns" />

<param name="match.Opera" value="opera" />

<param name="match.Lynx" value="lynx" />

</mapper>

<mapper class="com.opensymphony.module.sitemesh.mapper.PrintableDecoratorMapper">

<param name="decorator" value="printable" />

<param name="parameter.name" value="printable" />

<param name="parameter.value" value="true" />

</mapper>

<mapper class="com.opensymphony.module.sitemesh.mapper.RobotDecoratorMapper">

<param name="decorator" value="robot" />

</mapper>

<mapper class="com.opensymphony.module.sitemesh.mapper.ParameterDecoratorMapper">

<param name="decorator.parameter" value="decorator" />

<param name="parameter.name" value="confirm" />

<param name="parameter.value" value="true" />

</mapper>

<mapper class="com.opensymphony.module.sitemesh.mapper.FileDecoratorMapper">

</mapper>

<mapper class="com.opensymphony.module.sitemesh.mapper.ConfigDecoratorMapper">

<param name="config" value="${decorators-file}" />

</mapper>

</decorator-mappers>

</sitemesh>

10.在WEB-INF下创建decorators.xml 配置哪些页面需要装饰

<?xml version="1.0" encoding="UTF-8"?>

<decorators defaultdir="/decorators">

<decorator name="manager" page="manager_layout.jsp">

<pattern>/default/manager/*/pattern>

</decorator>

<excludes>

<pattern>/default/manager/static/*/pattern>

</excludes>

</decorators>

五、其他的 都是一些手动封装,我会上传到github 大家可以下载来看

如有纰漏,请指出.互相交流

六、传送门

七、此demo 用户名为admin,密码为123456

相关文章

网友评论

    本文标题:手把手教你写一个springMVC+spring+hiberna

    本文链接:https://www.haomeiwen.com/subject/suzmcxtx.html