1. 程式人生 > >Win10下用IDEA搭建Struts2+Spring4+Hibernate5(SSH)框架,實現使用者登入註冊

Win10下用IDEA搭建Struts2+Spring4+Hibernate5(SSH)框架,實現使用者登入註冊

搭建環境:
-Win10專業版
-JetBrains IDEA 2017.1.5
-JDK1.8
-MySQL5.7
-Tomcat9

  1. 建立SSH工程
    開啟IDEA主介面->Create New Project,選擇左邊的Spring,勾選右邊的Spring、Struts2和Hibernate,點選Next,設定好專案目錄和專案名,點選Finish,等待IDEA將所需依賴包下載完成,SSH工程即建立完畢。
  2. 新增依賴包
    File->Project Structure->選擇Libraries->在Struts2中將struts2-spring-plugin.jar加入:
    這裡寫圖片描述

    在Spring4中將spring-web.jar包加入:
    這裡寫圖片描述
    點選中間的綠色“+”號,新增Library,選擇Java選擇c3p0及其依賴包和mysql jdbc包,加入工程,將此Library命名為MySQL:
    這裡寫圖片描述
    同樣的,加入Tomcat Library:
    這裡寫圖片描述
    全部新增完畢,點選左邊的Artifacts->如下圖操作:
    這裡寫圖片描述
    完成後,上圖下部的警告即消除,然後點選OK即完成依賴包的配置。
  3. MySQL資料庫建表
    建立資料庫名為j2eetest,建表user,username和password兩個varchar欄位。
  4. 完善工程目錄結構
    在src目錄下建立cn.hust.action、cn.hust.dao、cn.hust.entity和cn.hust.service四個包和一個conf資料夾,conf資料夾用來放置配置檔案。
  5. Hibernate資料持久化
    在conf目錄下建立hibernate配置檔案hibernate.cfg.xml,內容如下(注意,首次寫配置檔案時,IDEA編輯器會在上方有提示“Add to xxx”,那個一定要點,下同):
<?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.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/j2eetest</property> <property name="dialect">org.hibernate.dialect.MySQL57Dialect</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">validate</property> <mapping class="cn.hust.entity.User"/> <mapping resource="cn/hust/entity/User.hbm.xml"/> </session-factory> </hibernate-configuration>

選擇IDEA介面左下側邊的“Persistence”:
這裡寫圖片描述
右鍵專案名,如下圖選擇:
這裡寫圖片描述
點選之後出現介面:
這裡寫圖片描述
在“Choose Data Source”上配置資料庫:
這裡寫圖片描述
可以點選“Test Connection”測試一下是否可以連線上該資料庫。
之後,選擇剛才建立的資料庫連線,在Package選擇儲存的包,將“entity suffix”刪除,勾選上需要持久化的表,點選OK即可。
這裡寫圖片描述
此時entity包下多出了兩個檔案:
這裡寫圖片描述
原來的hibernate.cfg.xml也加入了相關對映:
這裡寫圖片描述
6. spring相關配置檔案
在conf目錄下建立配置檔案db.properties:

db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/j2eetest
db.username=root
db.password=yourpassword

在conf目錄下建立Spring配置檔案applicationContext.xml:
這裡寫圖片描述
這裡寫圖片描述
上圖中上方的提示一定要點,再次強調。
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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       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">

    <!-- spring註解自動注入 -->
    <context:component-scan base-package="cn.hust"/>

    <!-- 載入資料庫屬性配置檔案 -->
    <context:property-placeholder location="classpath:/conf/db.properties" />

    <!-- data connection setting -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="${db.driverClassName}"/>
        <property name="jdbcUrl" value="${db.url}"/>
        <property name="user" value="${db.username}"/>
        <property name="password" value="${db.password}"/>
        <property name="initialPoolSize" value="2"/>
        <property name="minPoolSize" value="1"/>
        <property name="maxPoolSize" value="10"/>
    </bean>

    <!-- session工廠 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="configLocation" value="classpath:/conf/hibernate.cfg.xml" />
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="ht" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <!-- 配置Spring事務管理器 -->
    <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <tx:annotation-driven transaction-manager="txManager"/>

</beans>

以下采取程式註解的方式進行spring注入,而非採取配置檔案中配置的方式。
簡要說明一下用的註解:

  • @Repository:用於標註資料訪問元件,即用於將資料訪問層 (DAO 層 ) 的類標識為 Spring Bean。同時,為了讓 Spring 能夠掃描類路徑中的類並識別出 @Repository 註解,需要在 XML 配置檔案中啟用Bean 的自動掃描功能,可以通過標籤“context:component-scan”實現
  • @Transactional:基於註解式的事務配置方法
  • @Scope:Spring Bean的模式,例如prototype原型模式,表示每次獲取Bean的時候會有一個新的例項
  • @Service:用於標註業務層元件
  • @Controller:用於標註控制層元件,如Struts中的action
  • @Component:泛指元件,當元件不好歸類時,可用此進行標註
  • @AutoWired:把依賴的物件自動的注入到bean裡

dao層程式碼如下:
BaseDAO介面類:

package cn.hust.dao;/*Created by LCJ on 2017.7.15.*/

import java.util.List;

public interface BaseDAO {

    boolean add(Object o);

    boolean delete(Object o);

    boolean update(Object o);

    List find(Object o);
}

BaseDAOImpl.java實現類:

package cn.hust.dao.Impl;/*Created by LCJ on 2017.7.15.*/

import cn.hust.dao.BaseDAO;
import org.hibernate.FlushMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
@Transactional
@Scope("prototype")
public class BaseDAOImpl implements BaseDAO {

    private HibernateTemplate ht;

    @Autowired
    public void setHt(HibernateTemplate ht) {
        this.ht = ht;
    }

    private HibernateTemplate getHt() {
        ht.setCacheQueries(true);
        ht.getSessionFactory().getCurrentSession().setHibernateFlushMode(FlushMode.AUTO);
        return ht;
    }

    @Override
    public boolean add(Object o) {
        try {
            this.getHt().save(o);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean delete(Object o) {
        try {
            this.getHt().delete(o);
            return true;
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean update(Object o) {
        try {
            this.getHt().update(o);
            return true;
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List find(Object o) {
        return this.getHt().findByExample(o);
    }
}

service層程式碼:
UserService介面類:

package cn.hust.service;/*Created by LCJ on 2017.7.15.*/

import cn.hust.entity.User;

public interface UserService {

    User checkLogin(String name, String pass);

    boolean register(String name, String pass);
}

UserServiceImpl.java實現類:

package cn.hust.service.Impl;/*Created by LCJ on 2017.7.15.*/

import cn.hust.dao.BaseDAO;
import cn.hust.entity.User;
import cn.hust.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Scope("prototype")
public class UserServiceImpl implements UserService {

    @Autowired
    private BaseDAO baseDAO;

    @Override
    public User checkLogin(String name, String pass) {

        User u = new User();
        u.setUsername(name);
        u.setPassword(pass);
        List users = baseDAO.find(u);
        if (users.size() != 0) return (User)users.get(0);
        return null;
    }

    @Override
    public boolean register(String name, String pass) {

        User u = new User();
        u.setUsername(name);
        u.setPassword(pass);
        List users = baseDAO.find(u);
        return users.size() == 0 && baseDAO.add(u);
    }
}

action層程式碼:
UserAction.java

package cn.hust.action;/*Created by LCJ on 2017.7.15.*/

import cn.hust.entity.User;
import cn.hust.service.UserService;
import com.opensymphony.xwork2.ActionSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

@Controller
@Scope("prototype")
public class UserAction extends ActionSupport {

    @Autowired
    private UserService userService;

    private String username;
    private String password;

    public String login() {
        User user = userService.checkLogin(username, password);
        if (user != null) return SUCCESS;
        return ERROR;
    }

    public String register() {
        if (userService.register(username, password)) return SUCCESS;
        return ERROR;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

配置struts.xml如下:

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

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <constant name="struts.devMode" value="false"/>
    <constant name="struts.objectFactory" value="spring"/>

    <package name="user" namespace="/" extends="struts-default">
        <action name="login" class="cn.hust.action.UserAction" method="login">
            <result name="success">/success.jsp</result>
            <result name="error">/index.jsp</result>
        </action>

        <action name="register" class="cn.hust.action.UserAction" method="register">
            <result name="success">/index.jsp</result>
            <result name="error">/register.jsp</result>
        </action>
    </package>
</struts>

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_3_1.xsd"
         version="3.1">

    <display-name>MyDemo</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 新增對spring的支援 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/conf/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

index.jsp:

<%--
  Created by IntelliJ IDEA.
  User: LCJ
  Date: 2017.7.14
  Time: 01:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>登入</title>
</head>
<body>
<form action="login.action" method="post">
  <input type="text" name="username" placeholder="輸入使用者名稱" />
  <br/>
  <input type="password" name="password" placeholder="輸入密碼" />
  <br />
  <input type="submit" value="登入">
  <input type="reset" value="重置">
  <div>
    <a href="register.jsp">還沒有賬號?點此註冊</a>
  </div>
</form>
</body>
</html>

register.jsp:

<%--
  Created by IntelliJ IDEA.
  User: LCJ
  Date: 2017.7.14
  Time: 11:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Register</title>
</head>
<body>
<form action="register.action" method="post">
    <input type="text" name="username" placeholder="輸入使用者名稱" />
    <br/>
    <input type="password" name="password" placeholder="輸入密碼" />
    <br />
    <input type="submit" value="註冊">
    <input type="reset" value="重置">
</form>
</body>
</html>

success.jsp:

<%--
  Created by IntelliJ IDEA.
  User: LCJ
  Date: 2017.7.13
  Time: 11:21
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Success</title>
</head>
<body>
<p>Success!</p>
</body>
</html>

最後配置一下tomcat,執行即可實現使用者登入註冊功能啦!