一、新建项目
- 选中Spring
- strust2
- hibernate
二、见项目根路径下的lib下的jar移动到WEB-INF下
- 移动
- 修改路径
- 在lib目录下导入【c3p0-0.9.5.2.jar】、【mysql-connector-java-5.1.7-bin.jar】并加载到项目
三、配置文件
- web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app 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_4_0.xsd" version="4.0"> <!--配置spring整合web侦听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring ApplicationContext配置文件的路径,可使用通配符,多个路径用,号分隔 此参数用于后面的Spring ContextLoader --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext-*.xml</param-value> </context-param> <!--配置延时加载--> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--配置struts核心过滤器--> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
- jdbc.properties
hibernate.dialect=org.hibernate.dialect.MySQLDialect jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.validationQuery=SELECT 1 jdbc.url=jdbc:mysql://localhost:3306/stu_return_late?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=123456 hibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.format_sql=true
- log4j.properties
# This is the configuring for logging displayed in the Application Server log4j.rootLogger=INFO, stdout,file log4j.addivity.org.apache=true log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern= %p [%d] %c{1}.%M(%L) | %m%n log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.File=D:\\logs\\test.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%c]-[%p] %m%n log4j.logger.org.acegisecurity.context=DEBUG log4j.logger.org.apache.commons=ERROR log4j.logger.org.springframework=INFO log4j.logger.org.hibernate.ps.PreparedStatementCache=WARN log4j.logger.org.hibernate=WARN log4j.logger.org.hibernate.SQL=ERROR log4j.logger.org.hibernate.type=ERROR ############################################## handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler ############################################################ # Handler specific properties. # Describes specific configuration info for Handlers. ############################################################ #org.apache.juli.FileHandler.level = FINE #org.apache.juli.FileHandler.directory = ../logs/ #org.apache.juli.FileHandler.prefix = error-debug. # #java.util.logging.ConsoleHandler.level = FINE #java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
- spring
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--数据库连接池--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClassName}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- 每300秒检查所有连接池中的空闲连接 --> <property name="idleConnectionTestPeriod" value="300"></property> <!-- 最大空闲时间,900秒内未使用则连接被丢弃。若为0则永不丢弃 --> <property name="maxIdleTime" value="900"></property> <!-- 最大连接数 --> <property name="maxPoolSize" value="40"></property> <property name="minPoolSize" value="1"></property> <property name="initialPoolSize" value="1"></property> </bean> <!--sessionFactory--> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!-- 注入连接池,包含了数据库用户名,密码等等信息 --> <property name="dataSource" ref="dataSource"/> <!--扫描组件进spring容器--> <property name="packagesToScan" value="com.stureturnlate.moudels.sys.vo" /> <!-- 配置Hibernate的其他的属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/stu_return_late</prop> <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop> </props> </property> </bean> <!-- 使用hibernateTemplate --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 配置事务 --> <!-- 事务管理器 --> <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 开启通过注解@Transactional管理事务 --> <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" /> <!-- 事务 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="query*" read-only="true" propagation="REQUIRED" /> <tx:method name="find*" read-only="true" propagation="REQUIRED" /> <tx:method name="select*" read-only="true" propagation="REQUIRED" /> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!-- 配置AOP --> <aop:config proxy-target-class="true"> <aop:pointcut expression="execution(* *..service..*Service*.*(..))" id="serviceMethod" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" /> </aop:config> </beans>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- 引入外部属性文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> </beans>
<?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:context="http://www.springframework.org/schema/context" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd "> <task:annotation-driven/> <!--自动扫描(DAO) --> <context:component-scan base-package="com.stureturnlate.moudels.sys.dao"/> <!-- 自动扫描(Service) --> <context:component-scan base-package=" com.stureturnlate.moudels.sys.service"/> <!-- 自动扫描(Quartz) --> <!--<context:component-scan base-package="com.stureturnlate.moudels.sys.quartz"/>--> </beans>
- strust
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <!--suppress ALL --> <struts> <!-- 将Action交给spring容器管理 --> <constant name="struts.objectFactory" value="spring" /> <constant name="struts.enable.DynamicMethodInvocation" value="true"/> <!-- 设置为简单样式 --> <constant name="struts.ui.theme" value="simple"></constant> <!-- 零配置 --> <!--<constant name="struts.convention.package.locators" value="shi" />--> <constant name="struts.convention.package.locators.basePackage" value="com" /> <!-- 字符集编码 --> <constant name="struts.i18n.encoding" value="utf-8" /> <package name="defaultPackage" namespace="/" extends="struts-default"> </package> <include file="strust/struts-sys.xml"/> <include file="strust/struts-biz.xml"/> <include file="strust/struts-app.xml"/> </struts>
struts-app.xml、struts-biz.xml、struts-sys.xml....
四、新建数据表,并反向映射实体类
- 建好数据库表
- 打开Persistence选项:View→Tool Windows→Persistence
- 在hibernateGen上右键,进行如下操作
- 生成
- 结果
报错:java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
- 原因:项目未引入【spring-web-5.1.5.RELEASE.jar】
- 解决办法:下载【spring-web-5.1.5.RELEASE.jar】
报错:Cannot resolve method 'getContextPath()
- 如图
- 原因:缺少了【javax.servlet-api-3.1.0.jar】和【jsp-api-2.0.jar】
配置AOP报错:Could not find bean with name 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor
- 原因,缺少了包【aopalliance-1.0.jar】和【aspectjweaver-1.9.2.jar】
配置C3P0报错:Error creating bean with name 'dataSource'--Caused by: java.lang.NoClassDefFoundError: com/mchange/v2/ser/Indirector
- 原因:使用c3p0时要导入两个包【c3p0-0.9.5.2.jar】和【mchange-commons-java-0.2.11.jar】
实体类外键映射报错:Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.stureturnlate.moudels.sys.vo.HostelEntity column: dorm_id (should be mapped with insert="false" update="false")
报错:Caused by: Cannot locate the chosen ObjectFactory implementation: spring - [unknown location]
- 在Strust.xml配置了还在报错,缺少整合Struts和Spring的Jar
- 原因:少了【struts2-spring-plugin-2.5.20.jar】
启动tomcat报错:java.lang.ClassNotFoundException: org.apache.jsp.index_jsp
- 如图:
- 看看是不是少了这几个包【servlet-api-2.5.jar】和【jsp-api-2.1.jar】和【jstl-1.2.jar】
页面404:strust无法用通配符执行action的方法
- 原因:使用了新版本的strust2
- 解决办法:在strust2的配置文件中加入【strict-method-invocation="false"】
项目中用到JSON,配置struts.xml时遇到json-default发红:Cannot resolve Struts Package 'json-default'
- 如图:
- 原因:缺少了【struts2-json-plugin-2.5.20.jar】
- 解决办法:
一、项目导入包
二、到Project Structure条件strust配置文件
三、如下图:
SSH框架下Ajax与Action交互数据时报错:org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException
- 根本原因是:是Hibernate的懒加载引起的。就是在传递的数据中有引用类型的数据采用了懒加载机制。
主键(int)查询报错:java.lang.IllegalArgumentException: org.hibernate.TypeMismatchException: Provided id of the wrong type for class com.stureturnlate.moudels.sys.vo.StudentEntity. Expected: class java.lang.String, got class java.lang.Integer
第一种可能:
- 原因:实体类的hibernate映射文件没有指定字段属性的sql-type,导致查询的时候默认String
- 解决办法:在生成实体类的时候这样子勾选:
第二种可能:
- 使用了hibernate的get方法查询
Session currentSession = sessionFactory.openSession(); return currentSession.get(StudentEntity.class, 主键id); //return currentSession.load(StudentEntity.class, 主键id);--懒加载查询
- 使用这种方法查询,查询条件必须为主键,且类型要与主键匹配
第三种可能:
- 外键查询
- 解决办法:(qbc查询)
if (studentEntity.getUserId() != null) { Criteria cr=currentSession.createCriteria(StudentEntity.class);//userId为student外键,为sysUser主键 // cr.add(Restrictions.eq("sysUser.userId", studentEntity.getUserId()));//是外键的直接用,没问题 cr.add(Restrictions.eq("userId", studentEntity.getUserId()));//是外键的直接用,没问题 //cr.add(Restrictions.eq("sysUser.userName", "aaa"));//报错 // cr.createAlias("sysUser", "sysUser").add(Restrictions.eq("sysUser.userName", "黄结"));//不是外键的定义别名,不会报错 list = cr.list(); // return (StudentEntity) cr.list().get(0); } else { CriteriaBuilder criteriaBuilder = currentSession.getCriteriaBuilder(); CriteriaQuery<StudentEntity> query = criteriaBuilder.createQuery(StudentEntity.class); Root<StudentEntity> root = query.from(StudentEntity.class); Predicate studentId = criteriaBuilder.equal(root.get("studentId"), studentEntity.getStudentId()); query.where(studentId); list = currentSession.createQuery(query).list(); } return list.size()>0&&list!=null?list.get(0):null;
jsp页面向后台action绑定模型驱动Date类型的属性:No result defined for action com.stureturnlate.moudels.biz.action.student.StudentAction and result input
- 原因:该实体类的Date属性使用了【java.sql.Date】
- 解决办法:改为【java.util.Date】