一 需求
增加添加消息功能。
二 所有代码整合
1 com.sina.domain
1.1 Message
package com.sina.domain;
public class Message {
private Integer mesId;
private java.util.Date mesTime;
private String content;
//对象
private Users sender;
private Users 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 Users getSender() {
return sender;
}
public void setSender(Users sender) {
this.sender = sender;
}
public Users getGetter() {
return getter;
}
public void setGetter(Users getter) {
this.getter = getter;
}
}
1.2 Users
package com.sina.domain;
import java.util.List;
import java.util.Set;
public class Users {
private Integer userid;
private String userpwd;
private String name;
//这里一个用户可以发送多个消息,也可以接收多个消息. one-to-many
private Set<Message> sendMessages;
private Set<Message> getMessages;
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUserpwd() {
return userpwd;
}
public void setUserpwd(String userpwd) {
this.userpwd = userpwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Message> getSendMessages() {
return sendMessages;
}
public void setSendMessages(Set<Message> sendMessages) {
this.sendMessages = sendMessages;
}
public Set<Message> getGetMessages() {
return getMessages;
}
public void setGetMessages(Set<Message> getMessages) {
this.getMessages = getMessages;
}
}
1.3 Message.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";>
<hibernate-mapping package="com.sina.domain">
<class name="Message">
<!-- 主键属性 -->
<id name="mesId" type="java.lang.Integer">
<generator class="increment">
</generator>
</id>
<!-- 普通属性 -->
<property name="content" type="java.lang.String">
<column name="content" length="2000"/>
</property>
<property name="mesTime" type="java.util.Date">
<column name="mesTime" />
</property>
<!-- 配置getter属性 -->
<many-to-one name="getter" column="getter_id" />
<!-- 配置sendder -->
<many-to-one name="sender" column="sender_id"/>
</class>
</hibernate-mapping>
1.4 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";>
<hibernate-mapping package="com.sina.domain">
<class name="Users" table="users" lazy="false">
<id name="userid" type="java.lang.Integer">
<generator class="increment">
</generator>
</id>
<property name="name" type="java.lang.String">
<column name="name" length="64"/>
</property>
<property name="userpwd" type="java.lang.String">
<column name="userpwd" length="64"/>
</property>
<!-- getMessages属性 -->
<!--
<list name="sendMessages">
<list-index column=""/>
<key column="sender_id" />
<one-to-many class="Message"/>
</list>-->
<set name="sendMessages">
<key column="sender_id" />
<one-to-many class="Message"/>
</set>
<set name="getMessages">
<key column="getter_id" />
<one-to-many class="Message"/>
</set>
</class>
</hibernate-mapping>
2 com.sina.filter
2.1 MyFilter1
package com.sina.filter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.sina.util.HibernateUtil;
public class MyFilter1 extends HttpServlet implements Filter {
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
// TODO Auto-generated method stub
Session s = null;
Transaction tx = null;
try {
s = HibernateUtil.getCurrentSession();
tx = s.beginTransaction();
arg2.doFilter(arg0, arg1);
// System.out.println("ok");
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw new RuntimeException(e.getMessage());
// TODO: handle exception
} finally {
HibernateUtil.closeCurrentSession();
}
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
2.2 MyFilter2
package com.sina.filter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyFilter2 extends HttpServlet implements Filter {
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
// TODO Auto-generated method stub
arg0.setCharacterEncoding("utf-8");
arg2.doFilter(arg0, arg1);
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
3 com.sina.service.imp
3.1 BaseServiceImp
package com.sina.service.imp;
import java.io.Serializable;
import java.util.List;
import com.sina.service.inter.BaseInterface;
import com.sina.util.HibernateUtil;
public abstract class BaseServiceImp implements BaseInterface {
public Object findById(Class clazz, Serializable id) {
// TODO Auto-generated method stub
return HibernateUtil.findById(clazz, id);
}
//根据id删除...
public void save(Object obj){
try {
HibernateUtil.save(obj);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}
}
public List<Object> getListObject(String hql, String[] parameters) {
// TODO Auto-generated method stub
return null;
}
public Object getUniqueObject(String hql, String[] parameters) {
// TODO Auto-generated method stub
return null;
}
}
3.2 MessageServiceImp
package com.sina.service.imp;
import java.util.List;
import com.sina.domain.Message;
import com.sina.domain.Users;
import com.sina.service.inter.BaseInterface;
import com.sina.service.inter.MessageServiceInter;
import com.sina.util.HibernateUtil;
public class MessageServiceImp extends BaseServiceImp implements MessageServiceInter {
public List<Message> showMessage(Users user) {
// TODO Auto-generated method stub
String hql="from Message where getter.userid=? or getter.userid=4";
String parameters[]={user.getUserid()+""};
List<Message> messages=HibernateUtil.executeQuery(hql, parameters);
return messages;
}
}
3.3 UsersServiceImp
package com.sina.service.imp;
import java.util.List;
import com.sina.domain.Users;
import com.sina.service.inter.UsersServiceInter;
import com.sina.util.HibernateUtil;
import com.sina.util.MyTools;
//这个一个业务层的类,完成对users domian对象的各种操作.
public class UsersServiceImp extends BaseServiceImp implements UsersServiceInter{
//验证用户是否合法
/**
* @author 顺平
* @function: 完成用户验证
* @参数说明
* @return 如果验证合法,返回完整的user信息,如果失败返回null
*/
public Users checkUser(Users user){
String hql="from Users where userid=? and userpwd=?";
String parameters[]={user.getUserid()+"",MyTools.MD5(user.getUserpwd())};
//这里体现hibernate的鲁棒性
List<Users> list=HibernateUtil.executeQuery(hql, parameters);
if(list.size()==0){
return null;
}else{
return list.get(0);
}
}
public Users getUserByName(String name) {
// TODO Auto-generated method stub
String hql="from Users where name=?";
String parameters[]={name};
Users user=null;
try {
user=(Users) HibernateUtil.uniqueQuery(hql, parameters);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}
return user;
}
}
4 com.sina.service.inter
4.1 BaseInterface
package com.sina.service.inter;
import java.util.List;
public interface BaseInterface {
//把一些通用的方法,声明到该基础接口
//通过id号,来获取一个对象实例
public Object findById(Class clazz,java.io.Serializable id);
//findById(Users.class,12);//因为我们所有的包装类都实现了该接口
//保存对象
public void save(Object obj);
//通过hql语句获取List
public List<Object> getListObject(String hql,String[] parameters);
//通过hql语句获取一个对象.
public Object getUniqueObject(String hql,String [] parameters);
}
4.2 MessageServiceInter
package com.sina.service.inter;
import java.util.List;
import com.sina.domain.Message;
import com.sina.domain.Users;
public interface MessageServiceInter extends BaseInterface{
//显示用户接收到的所有message
public List<Message> showMessage(Users user);
}
4.3 UsersServiceInter
package com.sina.service.inter;
import com.sina.domain.Users;
public interface UsersServiceInter extends BaseInterface{
//这里定义方法
public Users checkUser(Users user);
//定义通过用户名来获取User
public Users getUserByName(String name);
}
5 com.sina.struts.action
5.1 GoMessageUiAction
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.sina.struts.action;
import java.util.List;
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.domain.Message;
import com.sina.domain.Users;
import com.sina.service.imp.MessageServiceImp;
import com.sina.service.inter.MessageServiceInter;
/**
* MyEclipse Struts
* Creation date: 05-30-2011
*
* XDoclet definition:
* @struts.action parameter="flag"
*/
public class GoMessageUiAction extends DispatchAction {
/*
* Generated Methods
*/
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
//去获取应该显示的留言信息,完成显示
//取出该用户收到的信息
MessageServiceInter messageServiceInter=new MessageServiceImp();
//取出当前用户
Users loginUser=(Users) request.getSession().getAttribute("userinfo");
List<Message> list=messageServiceInter.showMessage(loginUser);
//现在应当list集合放到 session request, application? request
request.setAttribute("messageList", list);
return mapping.findForward("goMessageUi");
}
}
5.2 GoPublishMessageUIAction
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.sina.struts.action;
import java.util.Date;
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.domain.Message;
import com.sina.domain.Users;
import com.sina.service.imp.MessageServiceImp;
import com.sina.service.imp.UsersServiceImp;
import com.sina.service.inter.MessageServiceInter;
import com.sina.service.inter.UsersServiceInter;
import com.sina.struts.form.MessageForm;
/**
* MyEclipse Struts
* Creation date: 05-31-2011
*
* XDoclet definition:
* @struts.action parameter="flag"
*/
public class GoPublishMessageUIAction extends DispatchAction {
/*
* Generated Methods
*/
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward goPublishMessageUi(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
return mapping.findForward("goPublishMessageUi");
}
public ActionForward publishMessage(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
//获取表单
MessageForm messageForm=(MessageForm)form;
//创建Message对象
Message message=new Message();
message.setContent(messageForm.getContent());
UsersServiceInter usersServiceInter=new UsersServiceImp();
message.setGetter(usersServiceInter.getUserByName(messageForm.getGetter()));//需要一个方法,通过用户名字来获取该对象
message.setMesTime(new Date());
message.setSender((Users)request.getSession().getAttribute("userinfo"));
//保存的是message对象
//MessageServiceInter messageServiceInter=new MessageServiceImp();
//messageServiceInter.save(message);
//保存的是message对象
usersServiceInter.save(message);
//这我们使用了全局跳转
return mapping.findForward("ok");
}
}
5.3 LoginAction
/*
* 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.domain.Users;
import com.sina.service.imp.UsersServiceImp;
import com.sina.service.inter.UsersServiceInter;
import com.sina.struts.form.UserForm;
/**
* MyEclipse Struts
* Creation date: 05-30-2011
*
* XDoclet definition:
* @struts.action parameter="flag"
*/
public class LoginAction extends DispatchAction {
/*
* Generated Methods
*/
/**
* 这里我们响应login请求
*/
public ActionForward login(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
UserForm userForm=(UserForm)form;
//使用service完成到数据库的验证
// UsersServiceImp usersService=new UsersServiceImp();//?这里直接使用对象,有定义耦合 web<-->业务层
//通过接口来调用.
UsersServiceInter usersServiceInter= new UsersServiceImp();
//构建一个Users对象
Users user=new Users();
//String ->Integer
user.setUserid(Integer.parseInt(userForm.getUserid()));
user.setUserpwd(userForm.getUserpwd());
user=usersServiceInter.checkUser(user);
if(user!=null){
//合法,将user对象放入session,后有用
request.getSession().setAttribute("userinfo", user);
return mapping.findForward("loginok");
}else{
return mapping.findForward("goLoginUi");
}
}
/**
* 这里我们响应logout请求
*/
public ActionForward logout(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
//清空session
request.getSession().invalidate();
return mapping.findForward("goLoginUi");
}
}
6 com.sina.struts.form
6.1 MessageForm
/*
* 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: 05-31-2011
*
* XDoclet definition:
* @struts.form name="messageForm"
*/
public class MessageForm extends ActionForm {
private String content;
private String getter;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getGetter() {
return getter;
}
public void setGetter(String getter) {
this.getter = getter;
}
}
6.2 UserForm
/*
* 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: 05-30-2011
*
* XDoclet definition:
* @struts.form name="userForm"
*/
public class UserForm extends ActionForm {
private String userid;
private String userpwd;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getUserpwd() {
return userpwd;
}
public void setUserpwd(String userpwd) {
this.userpwd = userpwd;
}
}
7 com.sina.util
7.1 HibernateUtil
package com.sina.util;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
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;
}
public static void closeCurrentSession(){
Session s=getCurrentSession();
if(s!=null&& s.isOpen() ){
s.close();
threadLocal.set(null);
}
}
//这里提供一个根据id返回对象的方法
public static Object findById(Class clazz,java.io.Serializable id){
Session s=null;
Transaction tx=null;
Object obj=null;
try {
s=openSession();
tx=s.beginTransaction();
obj=s.load(clazz, id);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return obj;
}
//统一的一个修改和删除(批量 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();
}
}
}
//如果要配置openSessionInView
//统一的一个修改和删除(批量 hql) hql"delete upate ...??"
public static void executeUpdateOpenInView(String hql,String [] parameters){
Session s=getCurrentSession();
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();
}
//统一的添加的方法
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 Object uniqueQuery(String hql,String [] parameters){
Session s=null;
Object obj=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]);
}
}
obj=query.uniqueResult();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return obj;
}
}
7.2 MyTools
package com.sina.util;
import java.security.*;
import java.security.spec.*;
public class MyTools {
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;
}
}
}
8 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="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/users
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
org.gjt.mm.mysql.Driver
</property>
<property name="show_sql">true</property>
<!-- 配置让hibernate自动创建关系模型(表) -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/sina/domain/Message.hbm.xml" />
<mapping resource="com/sina/domain/Users.hbm.xml" />
</session-factory>
</hibernate-configuration>
9 web层
9.1 login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";>
<html>
<head>
<title>My JSP 'login.jsp' starting page</title>
</head>
<body>
<h1>用户登录</h1>
<form action="/NoteBook/login.do?flag=login" method="post">
<table>
<tr><td>用户id</td><td><input type="text" style="width: 100px" name="userid" /></td></tr>
<tr><td>用户pw</td><td><input type="password" style="width: 100px" name="userpwd" /></td></tr>
<tr><td><input type="submit" value="登录" /></td><td><input type="reset" value="重新填写" /></td></tr>
</table>
</form>
</body>
</html>
9.2 ok.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";>
<html>
<head>
<title>My JSP 'ok.jsp' starting page</title>
</head>
<body>
操作成功,<a href="${pageContext.request.contextPath }/goMessageUi.do">返回留言界面</a>
</body>
</html>
9.3 publishMessage.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";>
<html>
<head>
<title>My JSP 'publishMessage.jsp' starting page</title>
</head>
<body>
<font size="6"><a href="#">查看信息</a></font> <font size="6"><a href="#">退出系统</a></font>
<form action="${pageContext.request.contextPath }/goPublishMessageUI.do?flag=publishMessage" method="post">
<table>
<tr><td>接收人</td><td><input type="text" name="getter" /></td></tr>
<tr><td>发送内容</td><td><textarea name="content" rows="5" cols="20">请输入内容</textarea></td></tr>
<tr><td><input type="submit" value="发布" /></td><td><input type="reset" value="重新填写"/></td></tr>
</table>
</form>
</body>
</html>
9.4 showMessage.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"; prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";>
<html>
<head>
<title>My JSP 'showMessage.jsp' starting page</title>
</head>
<body>
<font size="6"><b><a href="${pageContext.request.contextPath}/goPublishMessageUI.do?flag=goPublishMessageUi">发布信息</a></b></font>
<font size="6"><b><a href="/NoteBook/login.do?flag=logout">退出系统</a></b></font><br/>
欢迎${userinfo.name } 留言信息:
<table width="500px">
<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>
9.5 struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd";>
<struts-config>
<form-beans >
<form-bean name="userForm" type="com.sina.struts.form.UserForm" />
<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="userForm"
input="/WEB-INF/login.jsp"
name="userForm"
parameter="flag"
path="/login"
scope="request"
type="com.sina.struts.action.LoginAction"
validate="false" >
<forward name="loginok" path="/goMessageUi.do" />
<forward name="goLoginUi" path="/WEB-INF/login.jsp" />
</action>
<action
parameter="flag"
path="/goMessageUi"
type="com.sina.struts.action.GoMessageUiAction"
validate="false" >
<forward name="goMessageUi" path="/WEB-INF/showMessage.jsp" />
</action>
<action
attribute="messageForm"
input="/WEB-INF/showMessage.jsp"
name="messageForm"
parameter="flag"
path="/goPublishMessageUI"
scope="request"
type="com.sina.struts.action.GoPublishMessageUIAction"
validate="false">
<forward name="goPublishMessageUi" path="/WEB-INF/publishMessage.jsp" />
</action>
</action-mappings>
<message-resources parameter="com.sina.struts.ApplicationResources" />
</struts-config>
9.6 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"; version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd";>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>MyFilter1</servlet-name>
<servlet-class>com.sina.filter.MyFilter1</servlet-class>
</servlet>
<filter>
<filter-name>MyFilter2</filter-name>
<filter-class>com.sina.filter.MyFilter2</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>MyFilter1</servlet-name>
<url-pattern>/MyFilter1</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
三 测试结果