在IDEA中配置SSH環境


在IDEA中配置SSH環境

新建項目

在新建項目中選擇Spring中的SpringWebHibernate,設置為稍后設置庫

  1. 如果web中有struts選項直接選擇,沒有的話可以稍后設置。

  2. 如果左側沒有spring,可以按住Ctrl+Alt+Shift+/,選擇彈出界面的第一個選項,找到javaee.legacy.project.wizard選中即可。

image-20211115184246853

導入jar包

在項目中新建lib文件夾導入如圖46個jar包,並添加為庫。

image-20211116085232151image-20211116085318605

配置數據庫環境

創建一個數據庫,添加一個person表如圖的數據庫環境。

配置Struts環境

配置 Struts 核心過濾器

web.xml中配置struts核心過濾器

<?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">
    <!-- 配置Struts2核心過濾器 -->
    <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>

添加 struts.xml 配置文件

src中添加struts.xml文件,然后為struts添加文件集。

image-20211115201122174

添加 log4j.properties 文件

在 Hibernate 解壓包中的 project\etc 路徑下找到 log4j.properties 的文件,並復制到 src 源文件夾中。打開並編輯后,如下所示。

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file myLog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=E:/myLog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=info, stdout

配置Spring環境

添加 applicationContext.xml 文件

src中添加applicationContext.xml文件,然后為spring添加應用程序上下文。

image-20211115201900667

配置 Spring 的監聽器和過濾器

web.xml中配置Spring的監聽器和過濾器

<?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">
    <!-- 配置Struts2核心過濾器 -->
    <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>
    <!-- 監聽器 -->
    <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>
    <!-- 添加過濾器,延遲session關閉 -->
    <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>
</web-app>

配置 Hibernate 環境

src中添加hibernate.cfg.xml文件。

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.url">
            jdbc:mysql://localhost:3306/filmsystem?serverTimezone=UTC
        </property>
        <property name="connection.driver_class">
            com.mysql.cj.jdbc.Driver
        </property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
    </session-factory>
</hibernate-configuration>

Spring 和 Hibernate 整合

創建實體類

package POJO;
import java.io.Serializable;

public class Person implements Serializable {
    private static final long serialVersionUID = -3541561917509006050L;
    private String id;
    private String name;
    public Person() {
    }
    public Person(String id,String name) {
        super();
        this.id = id;
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

創建映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="POJO.Person" table="person">
        <id name="id" type="java.lang.String">
            <column name="id" length="32" />
            <generator class="assigned" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" length="50" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

編寫 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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 1.1確定文件位置 -->
        <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
        <!-- 1.2配置hbm.xml映射文件,mappingDirectoryLocationd表示本地映射文件的目錄 -->
        <property name="mappingDirectoryLocations" value="classpath:POJO"/>
    </bean>
</beans>

編寫測試類

package test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import POJO.Person;
public class TestMerge {
    ClassPathXmlApplicationContext ctx;
    @Before
    public void loadCtx() {
        // 加載配置文件
        ctx = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
    }
    @Test
    public void testHibernate() {
        SessionFactory sf = (SessionFactory) ctx.getBean("sessionFactory");
        Session session = sf.openSession();
        Transaction transaction = session.beginTransaction();
        session.save(new Person("1","用戶1"));
        transaction.commit();
        session.close();
        sf.close();
    }
}

運行測試類

如圖,測試成功!

image-20211116080349755

Spring 與 Struts2 整合

實現 Service 的配置

創建接口

package service;

public interface PersonService {
    public void say();
}

創建接口實現類

package service;

public class PersonServiceImpl implements PersonService{
    @Override
    public void say() {
        System.out.println("Service say hello");
    }
}

配置 Spring

applicationContext.xml中配置

<bean id="PersonService" class="service.PersonServiceImpl"></bean>

驗證配置

為了驗證 Spring 的加載是否正確,可以在測試類 TestMerge.java 中創建一個名稱為 testSpring 的方法進行測試。該方法代碼如下所示

@Test
    public void testSpring(){
        PersonService ts = (PersonService)ctx.getBean("personService");
        ts.say();
    }

如圖配置成功!

image-20211116082342536

實現 Action 的配置

創建 Action

package action;

import com.opensymphony.xwork2.ActionSupport;
import service.PersonService;

public class PersonAction extends ActionSupport {
    private static final long serialVersionUID = 1L;
    private PersonService personService;
    public PersonService getPersonService() {
        return personService;
    }
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }
    public String execute() {
        personService.say();
        return SUCCESS;
    }
}

配置 Struts2

<struts>
    <package name="test-package" namespace="/" extends="struts-default">
        <action name="person_*" class="action.PersonAction" method="{1}">
            <result name="success">/index.jsp</result>
        </action>
    </package>
</struts>

配置 Action 的 Bean 信息

<bean id="personAction" class="action.PersonAction"></bean>

查看測試結果

啟動項目后,運行jsp頁面,如下圖:
QQ截圖20211116084304

此時控制台輸出

image-20211116084749958 說明配置成功!

項目結構


免責聲明!

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



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