web层(struts or jsp+servlet)
业务层domain service
数据持久层(hibernate)
数据库
内部留言板项目
开发步骤(struts+table(el)+hibernate)
1.根据需求,设计数据库,应该有两张表。
--users
create table users(id number primary key,name varchar2
(64) unique,passwd varchar2(128) not null); -md5
--message
create table message
(id number primary key,
sender varchar2(64) not null,
receiver varchar2(64) not null,
content varchar2(4000) not null,
senTime date default sysdate,
attachment varchar2(128));
2.创建web项目
3.引入struts开发包
4.使用MyEclipse Database Explorer中的db browser连接数据库
5.引入hibernate开发包
6.对hibernate升级
7.创建需要的包com.sina.domain.* com.sina.servie.*
com.sina.util.*
8.通过hibernate逆向工程创建domain和对象映射文件
http://localhost:8080/messageborad/
struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software
Foundation//DTD Struts Configuration 1.2//EN"
"http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<data-sources />
<form-beans >
<form-bean name="usersForm"
type="com.sina.struts.form.UsersForm" />
<form-bean name="messageForm"
type="com.sina.struts.form.MessageForm" />
</form-beans>
<global-exceptions />
<global-forwards >
<forward name="ok" path="/WEB-INF/ok.jsp" />
</global-forwards>
<action-mappings >
<action
attribute="usersForm"
input="/WEB-INF/login.jsp"
name="usersForm"
parameter="flag"
path="/login"
scope="request"
type="com.sina.struts.action.LoginAction"
validate="false" >
<forward name="loginok" path="/WEB-INF/main.jsp" />
<forward name="loginerr" path="/WEB-INF/login.jsp"
/>
</action>
<action
attribute="messageForm"
input="/WEB-INF/publish.jsp"
name="messageForm"
parameter="flag"
path="/message"
scope="request"
type="com.sina.struts.action.MessageAction"
validate="false">
<forward name="goPublishUI" path="/WEB-
INF/publish.jsp" />
</action>
</action-mappings>
<message-resources
parameter="com.sina.struts.ApplicationResources" />
</struts-config>
login.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 'login.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>用户登录</h1>
<form action="/messageborad/login.do?flag=login"
method="post">
u:<input type="text" name="name"/><br/>
p:<input type="password" name="passwd"/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>
main.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 'main.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>
<a href="/messageborad/message.do?flag=gotoPublish">
发布信息</a> <a href="##">退出信息</a><br/>
留言信息:<br/>
<table border="1">
<tr><td>发送人</td><td>时间</td><td>接收人</td><td>内
容</td><td>附件</td></tr>
<tr><td>发送人</td><td>时间</td><td>接收人</td><td>内
容</td><td>附件</td></tr>
<tr><td>发送人</td><td>时间</td><td>接收人</td><td>内
容</td><td>附件</td></tr>
</table>
</body>
</html>
publish.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 'publish.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>发布信息</h1>
<form action="??">
<table></table>
</form>
</body>
</html>
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD
3.0//EN"
"http://hibernate.sourceforge.net/hibernate-
configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.
-->
<hibernate-configuration>
<session-factory>
<property
name="connection.username">scott</property>
<property name="connection.url">
jdbc:oracle:thin:@127.0.0.1:1521:orcl
</property>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property
name="myeclipse.connection.profile">
myoracle
</property>
<property
name="connection.password">tiger</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<mapping
resource="com/sina/domain/Message.hbm.xml" />
<mapping
resource="com/sina/domain/Users.hbm.xml" />
</session-factory>
</hibernate-configuration>
Message.java
package com.sina.domain;
import java.util.Date;
/**
* Message generated by MyEclipse Persistence Tools
*/
public class Message implements java.io.Serializable {
// Fields
private Long id;
private String sender;
private String receiver;
private String content;
private Date sentime;
private String attachment;
// Constructors
/** default constructor */
public Message() {
}
/** minimal constructor */
public Message(String sender, String receiver,
String content) {
this.sender = sender;
this.receiver = receiver;
this.content = content;
}
/** full constructor */
public Message(String sender, String receiver,
String content,
Date sentime, String attachment)
{
this.sender = sender;
this.receiver = receiver;
this.content = content;
this.sentime = sentime;
this.attachment = attachment;
}
// Property accessors
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getSender() {
return this.sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {
return this.receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
public Date getSentime() {
return this.sentime;
}
public void setSentime(Date sentime) {
this.sentime = sentime;
}
public String getAttachment() {
return this.attachment;
}
public void setAttachment(String attachment) {
this.attachment = attachment;
}
}
Users.java
package com.sina.domain;
/**
* Users generated by MyEclipse Persistence Tools
*/
public class Users implements java.io.Serializable {
// Fields
private Long id;
private String name;
private String passwd;
// Constructors
/** default constructor */
public Users() {
}
/** minimal constructor */
public Users(String passwd) {
this.passwd = passwd;
}
/** full constructor */
public Users(String name, String passwd) {
this.name = name;
this.passwd = passwd;
}
// Property accessors
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPasswd() {
return this.passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}
Message.hbm.xml
```xml
<?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">
<!--
Mapping file autogenerated by MyEclipse Persistence
Tools
-->
<hibernate-mapping>
<class name="com.sina.domain.Message" table="MESSAGE"
schema="SCOTT">
<id name="id" type="java.lang.Long">
<column name="ID" precision="22" scale="0" />
<generator class="sequence" />
</id>
<property name="sender" type="java.lang.String">
<column name="SENDER" length="64" not-
null="true" />
</property>
<property name="receiver"
type="java.lang.String">
<column name="RECEIVER" length="64" not-
null="true" />
</property>
<property name="content" type="java.lang.String">
<column name="CONTENT" length="4000" not-
null="true" />
</property>
<property name="sentime" type="java.util.Date">
<column name="SENTIME" length="7" />
</property>
<property name="attachment"
type="java.lang.String">
<column name="ATTACHMENT" length="128" />
</property>
</class>
</hibernate-mapping>
Users.hbm.xml
<?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">
<!--
Mapping file autogenerated by MyEclipse Persistence
Tools
-->
<hibernate-mapping>
<class name="com.sina.domain.Users" table="USERS"
schema="SCOTT">
<id name="id" type="java.lang.Long">
<column name="ID" precision="22" scale="0" />
<generator class="sequence" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="64" unique="true"
/>
</property>
<property name="passwd" type="java.lang.String">
<column name="PASSWD" length="128" not-
null="true" />
</property>
</class>
</hibernate-mapping>
MessageService.java
package com.sina.service;
import com.sina.domain.Users;
import com.sina.util.*;
import java.util.*;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class MessageService {
}
UsersService.java
package com.sina.service;
import java.util.List;
import com.sina.domain.Users;
import com.sina.util.HibernateUtil;
public class UsersService {
//验证用户是否合法
public Users checkUser(Users users){
/*
* String sql... it doesn't need do this
anymore,we use hibernate
Session session=null;
Transaction ts=null;
try {
session=HibernateUtil.getCurrentSession();
ts=session.beginTransaction();
List<Users>
list=session.createQuery("from User where name='"
+users.getName
()+"' and passwd='"+users.getPasswd()+"'").list();
if(list.size()==1){
users=list.get(0);
}else{
users=null;
}
ts.commit();
} catch (Exception e) {
// TODO: handle exception
if(ts!=null){
ts.rollback();
}
throw new RuntimeException("ERROR
404");
}finally{
if(session.isOpen() && session!
=null){
session.close();
}
}
return users;*/
String hql="from Users where name='"
+users.getName()+"' and
passwd='"+users.getPasswd()+"'";
List<Users>
list=HibernateUtil.executeQuery(hql);
if(list.size()==1){
return list.get(0);
}else{
return null;
}
}
}
LoginAction.java
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.sina.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import com.sina.struts.form.UsersForm;
import com.sina.domain.Users;
import com.sina.service.UsersService;
/**
* MyEclipse Struts
* Creation date: 02-19-2020
*
* XDoclet definition:
* @struts.action path="/login" name="usersForm"
parameter="flag" scope="request"
*/
public class LoginAction extends DispatchAction {
/*
* Generated Methods
*/
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward login(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
UsersForm usersForm = (UsersForm) form;//
TODO Auto-generated method stub
//这里需要调用service完成验证
//根据用户输入创建users对象
Users user=new Users();
user.setName(usersForm.getName());
user.setPasswd(usersForm.getPasswd());
//创建service
UsersService usersService=new
UsersService();
user=usersService.checkUser(user);
if(user!=null){
request.getSession
().setAttribute("userInfo", user);
return mapping.findForward
("loginok");
}else{
return mapping.findForward
("loginerr");
}
/*简单判断连通没有
* *if(usersForm.getName().equals("aaa")){
return mapping.findForward("loginok");
}else{
return mapping.findForward("loginerr");
}*/
}
}
MessageAction.java
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.sina.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.sina.struts.form.MessageForm;
/**
* MyEclipse Struts
* Creation date: 02-19-2020
*
* XDoclet definition:
* @struts.action path="/message" name="messageForm"
parameter="flag" scope="request"
*/
public class MessageAction extends Action {
/*
* Generated Methods
*/
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward gotoPublish(ActionMapping
mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
//MessageForm messageForm = (MessageForm)
form;// TODO Auto-generated method stub
return mapping.findForward
("goPublishUI");
}
}
MessageForm.java
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.sina.struts.form;
import org.apache.struts.action.ActionForm;
/**
* MyEclipse Struts
* Creation date: 02-19-2020
*
* XDoclet definition:
* @struts.form name="messageForm"
*/
public class MessageForm extends ActionForm {
}
UsersForm.java
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.sina.struts.form;
import org.apache.struts.action.ActionForm;
/**
* MyEclipse Struts
* Creation date: 02-19-2020
*
* XDoclet definition:
* @struts.form name="usersForm"
*/
public class UsersForm extends ActionForm {
private String name;
private String passwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}
HibernateUtil.java
package com.sina.util;
import java.util.List;
import com.sina.domain.Users;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.sina.domain.Users;
final public class HibernateUtil {
private static SessionFactory
sessionFactory=null;
//使用线程局部模式
private static ThreadLocal<Session>
threadLocal=new ThreadLocal<Session>();
private HibernateUtil(){};
static {
sessionFactory=new Configuration
().configure().buildSessionFactory();
}
//获取全新的全新的sesession
public static Session openSession(){
return sessionFactory.openSession();
}
//获取和线程关联的session
public static Session getCurrentSession(){
Session session=threadLocal.get();
//判断是否得到
if(session==null){
session=sessionFactory.openSession();
//把session对象设置到
threadLocal,相当于该session已经和线程绑定
threadLocal.set(session);
}
return session;
}
//统一的一个修改和删除(批量 hql) hql"delete upate
...??"
public static void executeUpdate(String
hql,String [] parameters){
Session s=null;
Transaction tx=null;
try {
s=openSession();
tx=s.beginTransaction();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&&
parameters.length>0){
for(int
i=0;i<parameters.length;i++){
query.setString
(i, parameters[i]);
}
}
query.executeUpdate();
tx.commit();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException
(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
}
//统一的添加的方法
public static void save(Object obj){
Session s=null;
Transaction tx=null;
try {
s=openSession();
tx=s.beginTransaction();
s.save(obj);
tx.commit();
} catch (Exception e) {
if(tx!=null){
tx.rollback();
}
throw new RuntimeException
(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null && s.isOpen()){
s.close();
}
}
}
//提供一个统一的查询方法(带分页) hql 形式 from 类
where 条件=? ..
public static List executeQueryByPage(String
hql,String [] parameters,int pageSize,int pageNow){
Session s=null;
List list=null;
try {
s=openSession();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&&
parameters.length>0){
for(int
i=0;i<parameters.length;i++){
query.setString
(i, parameters[i]);
}
}
query.setFirstResult((pageNow-1)
*pageSize).setMaxResults(pageSize);
list=query.list();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException
(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return list;
}
/*提供一个统一的查询方法 hql 形式 from 类 where
条件=? ..
public static List executeQuery(String hql,String
[] parameters){
Session s=null;
List list=null;
try {
s=openSession();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&&
parameters.length>0){
for(int
i=0;i<parameters.length;i++){
query.setString
(i, parameters[i]);
}
}
list=query.list();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException
(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return list;
}
*/
//提供一个统一的查询方法
public static List executeQuery(String hql){
//String sql... it doesn't need do this
anymore,we use hibernate
Session session=null;
Transaction ts=null;
List list=null;
try {
session=HibernateUtil.getCurrentSession();
ts=session.beginTransaction();
list=session.createQuery
(hql).list();
ts.commit();
} catch (Exception e) {
// TODO: handle exception
if(ts!=null){
ts.rollback();
}
throw new RuntimeException("错
误");
}finally{
if(session.isOpen() && session!
=null){
session.close();
}
}
return list;
}
}