struts2+hibernate留言板 练习java ee

项目结构

项目结构

**action:**
准备数据,跳转到主界面
    GoMessageUi.java
package com.frank.action;

import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.frank.domain.Message;
import com.frank.domain.User;
import com.frank.service.imp.MessageServiceImp;
import com.frank.service.inter.MessageServiceInter;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class GoMessageUi extends ActionSupport {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("#########GoMessageUi###########");
        User user=(User) ActionContext.getContext().getSession().get("userinfo");
        System.out.println(user.getName());
        MessageServiceInter messageService=new MessageServiceImp();
        List<Message> message=messageService.showMessage(user);
        System.out.println(message.size());
        ServletActionContext.getRequest().setAttribute("messageList",message);
        return SUCCESS;
    }
}

GoSendMessageUi.java
跳转到发送信息界面



package com.frank.action;

import com.opensymphony.xwork2.ActionSupport;

public class GoSendMessageUi extends ActionSupport {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("##########GoSendMessageUi#########");
        return SUCCESS;
    }

}

处理用户登录登出
LoginAction.java

package com.frank.action;


import com.frank.domain.User;
import com.frank.service.imp.UserServiceImp;
import com.frank.service.inter.UserServiceInter;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String userId;
    private String password;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getPassword() {
        return password;
    }

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

    public String Login() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("#######login#########");
        User user=new User();
        UserServiceInter userservice=new UserServiceImp();
        user.setUserId(Integer.parseInt( this.getUserId() ) ); 
        user.setPassword(this.getPassword());

        user=userservice.checkUser(user);
        if(user!=null){
            //将user信息放入session
            ActionContext.getContext().getSession().put("userinfo", user);
            System.out.println(user.getName());
            return SUCCESS;
        }
        else{
            System.out.println("the password of user is worng");
            return LOGIN;
        }
    }
    public String Logout() throws Exception{
        System.out.println("#########logout#########");
        ActionContext context=ActionContext.getContext();
        context.getSession().clear();   //清空session
        return LOGIN;


    }

}

SendMessageAction.java
发布信息

package com.frank.action;

import java.util.Date;

import com.frank.domain.Message;
import com.frank.domain.User;
import com.frank.service.imp.MessageServiceImp;
import com.frank.service.imp.UserServiceImp;
import com.frank.service.inter.MessageServiceInter;
import com.frank.service.inter.UserServiceInter;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class SendMessageAction extends ActionSupport {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String getterId;
    private String content;
    public String getGetterId() {
        return getterId;
    }
    public void setGetterId(String getterId) {
        this.getterId = getterId;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("########SendMessageAction#########");
        //获得sender和getter
        User sender=(User) ActionContext.getContext().getSession().get("userinfo");
        UserServiceInter userService=new UserServiceImp();
        System.out.println(this.getterId);
        System.out.println(this.getContent());
        User getter=(User) userService.findById(User.class, this.getterId);
        Message message=new Message();
        message.setContent(this.getContent());
        message.setGetter(getter);
        message.setSender(sender);
        message.setMesTime(new Date());
        //保存message到数据库
        MessageServiceInter messageService=new MessageServiceImp();
        messageService.save(message);
        return SUCCESS;
    }


}

domain
Message.java
many的一端,要在这里把延迟加载取消。否则在取的时候hibernate不会取其中的User属性。如果不想取消延迟加载,可以使用opensessionInView,扩大session的作用范围。

package com.frank.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;



@Entity
@Table(name="Message_inf")
public class Message {
    @Id @Column(name="mesId")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer mesId;
    private java.util.Date mesTime;
    private String content;
    //对象
    //关闭延迟加载
    @ManyToOne(targetEntity=User.class,fetch=FetchType.EAGER)
    private User sender;
    @ManyToOne(targetEntity=User.class,fetch=FetchType.EAGER)
    private User getter;

    public Integer getMesId() {
        return mesId;
    }
    public void setMesId(Integer mesId) {
        this.mesId = mesId;
    }
    public java.util.Date getMesTime() {
        return mesTime;
    }
    public void setMesTime(java.util.Date mesTime) {
        this.mesTime = mesTime;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public User getSender() {
        return sender;
    }
    public void setSender(User sender) {
        this.sender = sender;
    }
    public User getGetter() {
        return getter;
    }
    public void setGetter(User getter) {
        this.getter = getter;
    }

}

User.java
one的一端,用set集合储存Message对象

package com.frank.domain;

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="User_inf")
public class User {
    @Id @Column(name="user_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer userId;
    private String password;
    private String name;
    //一个用户可以发送多条消息,也可以接收多条消息
    //mappedBy指定该实体不控制关联关系
    @OneToMany(targetEntity=Message.class,mappedBy="sender" )
    private Set<Message>  sentMessages; 
    @OneToMany(targetEntity=Message.class,mappedBy="getter")
    private Set<Message> getMessages;

    public Integer getUserId() {
        return userId;
    }
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Set<Message> getSentMessages() {
        return sentMessages;
    }
    public void setSentMessages(Set<Message> sentMessages) {
        this.sentMessages = sentMessages;
    }
    public Set<Message> getGetMessages() {
        return getMessages;
    }
    public void setGetMessages(Set<Message> getMessages) {
        this.getMessages = getMessages;
    }


}

service->implements
该包下为interface下接口的实现类

BaseImp.java
基础接口的实现类

package com.frank.service.imp;

import java.io.Serializable;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.frank.service.inter.BaseInter;
import com.frank.util.HibernateSessionFactory;

public class BaseImp implements BaseInter {

    public Object findById(Class clazz, Serializable id) {
        // TODO Auto-generated method stub
        Object obj = null;
        Session session = HibernateSessionFactory.getSession();
        Transaction tx = session.beginTransaction();
        //temp  no!
        obj = session.load(clazz,Integer.parseInt( id.toString()));
        tx.commit();
        return obj;
    }

    @Override
    public void save(Object obj) {
        // TODO Auto-generated method stub
        Session session = HibernateSessionFactory.getSession();
        Transaction tx = session.beginTransaction();
        obj = session.save(obj);
        tx.commit();
    }

}

MessageServiceImp.java
MessageServiceinter的实现类,同时继承了基础接口的实现类

package com.frank.service.imp;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.frank.domain.Message;
import com.frank.domain.User;
import com.frank.service.inter.MessageServiceInter;
import com.frank.util.HibernateSessionFactory;

public class MessageServiceImp extends BaseImp implements MessageServiceInter{

    @Override
    public List<Message> showMessage(User user) {
        // TODO Auto-generated method stub
        String hql="from Message where sender.userId=:sId or getter.userId=:gId ";
        Session session=HibernateSessionFactory.getSession();
        Transaction tx=session.beginTransaction();
        @SuppressWarnings("unchecked")
        List<Message>message=session.createQuery(hql)
        .setParameter("sId", user.getUserId())
        .setParameter("gId", user.getUserId())
        .list();
        tx.commit();
        session.close();

        return message;
    }

}

UserServiceImp.java
UserServiceinter的实现类,并继承了基础接口的实现类

package com.frank.service.imp;



import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.frank.domain.User;
import com.frank.service.inter.UserServiceInter;
import com.frank.util.HibernateSessionFactory;
import com.frank.util.Mytools_md5;

public class UserServiceImp extends BaseImp implements UserServiceInter {

    /**
     *验证用户是否合法 
     * @param user 需要验证的信息
     * @retur 不合法返回null,合法返回用户信息 
     */
    public User checkUser(User user){
        String hql="from User where userId=:uId and password=:uPd";
        System.out.println(user.getPassword());
        System.out.println("###########################");
        Session session=HibernateSessionFactory.getSession();
        //开始事务
        Transaction tx=session.beginTransaction();
        @SuppressWarnings("unchecked")
        List<User> ul=session.createQuery(hql)
                .setString("uId",user.getUserId().toString())
                .setString("uPd",Mytools_md5.MD5( user.getPassword())).list()
                ;
        System.out.println("*************************");
        tx.commit();
        HibernateSessionFactory.closeSession();
        if(ul.size()==0)
            return null;
        else{
            return ul.get(0);
        }
    }


}

service->interface
该包下为接口

BaseInter.java
基础接口,定义了findById和save方法

package com.frank.service.inter;

public interface BaseInter {
    public Object findById(Class clazz, java.io.Serializable id);
    public void save(Object obj);

}

MessageServiceInter.java
MessageService接口,继承接口

package com.frank.service.inter;

import java.util.List;

import com.frank.domain.Message;
import com.frank.domain.User;

public interface MessageServiceInter extends BaseInter {
    public List<Message> showMessage(User user);

}

UserServiceInter.java
UserService接口,继承继承接口

package com.frank.service.inter;

import com.frank.domain.User;

public interface UserServiceInter  extends BaseInter{
    public User checkUser(User user);

}

test
该包下为编码过程中写的测试类,方便调试使用。

util
该包下存放工具类

HibernateSessionFactory.java
sessionFactory工具类,为工具自动生成

package com.frank.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static org.hibernate.SessionFactory sessionFactory;

    private static Configuration configuration = new Configuration();
    private static ServiceRegistry serviceRegistry; 

    static {
        try {
            configuration.configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Exception e) {
            System.err.println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }
    private HibernateSessionFactory() {
    }

    /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = threadLocal.get();

        if (session == null || !session.isOpen()) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            session = (sessionFactory != null) ? sessionFactory.openSession()
                    : null;
            threadLocal.set(session);
        }

        return session;
    }

    /**
     *  Rebuild hibernate session factory
     *
     */
    public static void rebuildSessionFactory() {
        try {
            configuration.configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Exception e) {
            System.err.println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }

    /**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

    /**
     *  return session factory
     *
     */
    public static org.hibernate.SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    /**
     *  return hibernate configuration
     *
     */
    public static Configuration getConfiguration() {
        return configuration;
    }

}

Mytools_md5.java
工具类,提供md5加密

package com.frank.util;

import java.security.MessageDigest;

public class Mytools_md5 {
    public final static String MD5(String s) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6',
                '7', '8', '9', 'a', 'b', 'c',
                'd', 'e', 'f' };
        try {
            byte[] strTemp = s.getBytes();
            MessageDigest mdTemp = MessageDigest
                    .getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }
}

hibernate.cfg.xml
hibernate配置文件

<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>

    <session-factory>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.url">jdbc:mysql://127.0.0.1:3306/spdb1</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="myeclipse.connection.profile">mysql</property>
        <!-- 显示Hibernate持久化操作所生成的SQL -->
        <property name="show_sql">true</property>
        <!-- 将SQL脚本进行格式化后再输出 -->
        <property name="hibernate.format_sql">true</property>


        <!-- 根据需要自动创建数据库 -->
        <property name="hbm2ddl.auto">update</property>
        <!-- 罗列所有持久化类的类名 -->
        <mapping class="com.frank.domain.User" />
        <mapping class="com.frank.domain.Message" />

    </session-factory>

</hibernate-configuration>

struts.xml
struts2配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>

    <package name="lee" namespace="/" extends="struts-default">
    <!-- 处理登录/登出 -->
        <action name="*Action" class="com.frank.action.LoginAction" method="{1}">
            <result name="login">index.jsp</result>
            <result  name="success" type="redirectAction" >GoMessageUi</result>
        </action>
        <!-- 准备数据,跳转到MessageUi -->
        <action name="GoMessageUi" class="com.frank.action.GoMessageUi">
            <result name="success">WEB-INF/MessageUi.jsp</result>
        </action>
        <!-- 跳转到发布信息界面 -->
        <action name="GoSendMessageUi" class="com.frank.action.GoSendMessageUi">
            <result name="success">WEB-INF/SendMessageUi.jsp</result>
        </action>
        <!-- 发布信息 -->
        <action name="SendMessageAction" class="com.frank.action.SendMessageAction">
            <result name="success">WEB-INF/tem.jsp</result>
        </action>
    </package></struts>    

index.jsp
首界面,在WebRoot目录下

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

<body>
    <form action="LoginAction" method="post">
    用户ID:<input type="text" name="userId"><br>
    密&nbsp;&nbsp;&nbsp;&nbsp;码:<input type="password" name="password"><br>
    <input type="submit" value="登录">
    </form>
  </body>
</html>

MessageUi.jsp
主界面,显示信息。在WEB-INF目录下

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'MessageUi.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
    <font size=7><a href="GoSendMessageUi">发送信息</a></font>
    <font size=7><a href="LogoutAction">退出系统</a></font><br>
    欢迎你${userinfo.name }!
    <table>
        <tr><td>发送人</td><td>发送时间</td><td>接受人</td><td>信息内容</td></tr>
        <c:forEach items="${messageList }" var="message">
         <tr><td>${message.sender.name }</td><td>${message.mesTime }</td><td>${message.getter.name }</td><td>${message.content}</td></tr>
        </c:forEach>
    </table>
  </body>
</html>

SendMessageUi.jsp
发布信息界面,在WEB-INF目录下

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()
            + "://"
            + request.getServerName()
            + ":"
            + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'SendMessageUi.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

</head>

<body>
    <font size=7><a href="SendMessageAction">发送信息</a></font>
    <font size=7><a href="LogoutAction">退出系统</a></font>
    <br>
    <form action="SendMessageAction" method="post">
        <table>
            <tr>
                <td>发送给:(id)</td>
                <td><input type="text" name="getterId" /></td>
            </tr>
            <tr>
                <td>内容:</td>
                <td><textarea rows="10" cols="20" name="content">请输入要发送的信息</textarea></td>
            </tr>
            <tr>
                <td><input type="submit" value="提交"></td>
                <td><input type="reset" value="重置"></td>
            </tr>
        </table>
    </form>
</body>
</html>

tem.jsp
发布成功界面。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'tem.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
        <h1>发布成功,点击<a href="GoMessageUi">这里</a>返回</h1>
  </body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>shTest_1.0</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>
</web-app>
原文地址:https://www.cnblogs.com/frankM/p/4399415.html