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加入:
    Win10下用IDEA搭建Struts2+Spring4+Hibernate5(SSH)框架,实现用户登录注册_第1张图片
    在Spring4中将spring-web.jar包加入:
    Win10下用IDEA搭建Struts2+Spring4+Hibernate5(SSH)框架,实现用户登录注册_第2张图片
    点击中间的绿色“+”号,添加Library,选择Java选择c3p0及其依赖包和mysql jdbc包,加入工程,将此Library命名为MySQL:
    Win10下用IDEA搭建Struts2+Spring4+Hibernate5(SSH)框架,实现用户登录注册_第3张图片
    同样的,加入Tomcat Library:
    Win10下用IDEA搭建Struts2+Spring4+Hibernate5(SSH)框架,实现用户登录注册_第4张图片
    全部添加完毕,点击左边的Artifacts->如下图操作:
    Win10下用IDEA搭建Struts2+Spring4+Hibernate5(SSH)框架,实现用户登录注册_第5张图片
    完成后,上图下部的警告即消除,然后点击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”,那个一定要点,下同):



<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driverproperty>
        <property name="connection.url">jdbc:mysql://localhost:3306/j2eetestproperty>
        <property name="dialect">org.hibernate.dialect.MySQL57Dialectproperty>

        <property name="show_sql">trueproperty>
        <property name="format_sql">trueproperty>
        <property name="hbm2ddl.auto">validateproperty>
        <mapping class="cn.hust.entity.User"/>
        <mapping resource="cn/hust/entity/User.hbm.xml"/>
    session-factory>
hibernate-configuration>

选择IDEA界面左下侧边的“Persistence”:
Win10下用IDEA搭建Struts2+Spring4+Hibernate5(SSH)框架,实现用户登录注册_第6张图片
右键项目名,如下图选择:
Win10下用IDEA搭建Struts2+Spring4+Hibernate5(SSH)框架,实现用户登录注册_第7张图片
点击之后出现界面:
Win10下用IDEA搭建Struts2+Spring4+Hibernate5(SSH)框架,实现用户登录注册_第8张图片
在“Choose Data Source”上配置数据库:
Win10下用IDEA搭建Struts2+Spring4+Hibernate5(SSH)框架,实现用户登录注册_第9张图片
可以点击“Test Connection”测试一下是否可以连接上该数据库。
之后,选择刚才创建的数据库连接,在Package选择保存的包,将“entity suffix”删除,勾选上需要持久化的表,点击OK即可。
Win10下用IDEA搭建Struts2+Spring4+Hibernate5(SSH)框架,实现用户登录注册_第10张图片
此时entity包下多出了两个文件:
Win10下用IDEA搭建Struts2+Spring4+Hibernate5(SSH)框架,实现用户登录注册_第11张图片
原来的hibernate.cfg.xml也加入了相关映射:
Win10下用IDEA搭建Struts2+Spring4+Hibernate5(SSH)框架,实现用户登录注册_第12张图片
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:
Win10下用IDEA搭建Struts2+Spring4+Hibernate5(SSH)框架,实现用户登录注册_第13张图片
Win10下用IDEA搭建Struts2+Spring4+Hibernate5(SSH)框架,实现用户登录注册_第14张图片
上图中上方的提示一定要点,再次强调。
applicationContext.xml内容如下:


<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">

    
    <context:component-scan base-package="cn.hust"/>

    
    <context:property-placeholder location="classpath:/conf/db.properties" />

    
    <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>

    
    <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>

    
    <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如下:





<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.jspresult>
            <result name="error">/index.jspresult>
        action>

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

web.xml如下:


<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>MyDemodisplay-name>
    <welcome-file-list>
        <welcome-file>index.htmlwelcome-file>
        <welcome-file>index.htmwelcome-file>
        <welcome-file>index.jspwelcome-file>
        <welcome-file>default.htmlwelcome-file>
        <welcome-file>default.htmwelcome-file>
        <welcome-file>default.jspwelcome-file>
    welcome-file-list>

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

    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:/conf/applicationContext.xmlparam-value>
    context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-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>Registertitle>
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>Successtitle>
head>
<body>
<p>Success!p>
body>
html>

最后配置一下tomcat,运行即可实现用户登录注册功能啦!

你可能感兴趣的:(j2ee项目,java-web,spring,hibernate5,struts2)