使用idea搭建SSH


一、新建項目

  1. 選中Spring

     

     

  2. strust2

     

  3. hibernate

     

二、見項目根路徑下的lib下的jar移動到WEB-INF下

  1. 移動

     

  2. 修改路徑


  3. 在lib目錄下導入【c3p0-0.9.5.2.jar】、【mysql-connector-java-5.1.7-bin.jar】並加載到項目



     

     

三、配置文件

  1. 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>
    web.xml
  2. 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
    jdbc.properties

     

  3. 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
    log4j.properties

     

  4. 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>
    applicationContext-hibernate.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"
        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>
    applicationContext-resource.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: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>
    applicationContext-service.xml

     

  5. 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.xml

    struts-app.xml、struts-biz.xml、struts-sys.xml....

     

四、新建數據表,並反向映射實體類

  1. 建好數據庫表

     

  2. 打開Persistence選項:ViewTool WindowsPersistence

     

  3. 在hibernateGen上右鍵,進行如下操作

     

  4. 生成

     

  5. 結果

     

報錯:java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

  1. 原因:項目未引入【spring-web-5.1.5.RELEASE.jar】
  2. 解決辦法:下載【spring-web-5.1.5.RELEASE.jar

報錯:Cannot resolve method 'getContextPath()

  1. 如圖

     

  2. 原因:缺少了【javax.servlet-api-3.1.0.jar】和【jsp-api-2.0.jar

     

配置AOP報錯:Could not find bean with name 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor

配置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]

  1. 在Strust.xml配置了還在報錯,缺少整合Struts和Spring的Jar

     

  2. 原因:少了【struts2-spring-plugin-2.5.20.jar

 啟動tomcat報錯:java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

  1. 如圖:

     

  2. 看看是不是少了這幾個包【servlet-api-2.5.jar】和【jsp-api-2.1.jar】和【jstl-1.2.jar

頁面404:strust無法用通配符執行action的方法

  1. 原因:使用了新版本的strust2
  2. 解決辦法:在strust2的配置文件中加入【strict-method-invocation="false"

     

項目中用到JSON,配置struts.xml時遇到json-default發紅:Cannot resolve Struts Package 'json-default'

  1. 如圖:

     

  2. 原因:缺少了【struts2-json-plugin-2.5.20.jar

  3. 解決辦法:
    一、項目導入包
    二、到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】


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM