这是我些的JSP+Bean结构同大家共同探讨

steeven 2001-07-18 10:02:42
总体思想是一个基础Bean Common, 提供和JSP配合的基本功能, 包括数据库, 出错处理, 权限, 速度测试, debug, 常用日期, 文字处理.

具体的Bean从Common上扩展, 提供自己的功能, 一般数据库处理不外乎处理用户post new, modify, delete, List. 其它应用简单修改就成.

JSP页面上对Bean引用, 出错转向专门的Error提示页面. POST成功后重新定向本页面, 以避免刷新提示.

很少见有人讨论JSP结构, 这里抛砖引玉, 希望大家共同探讨.

Guestbook.java:
===================================================

package steeven;

import java.sql.*;
import java.util.*;
import java.text.*;
import javax.servlet.http.*;

public class Guestbook extends Common {

public int id; // 数据id
public int type; // 留言分类
public String subject,body; // 标题, 内容
public java.util.Date postat,last; // 留言时间, 最后修改

ResultSet list; //分页显示的记录集
public Guestbook cur; //分页显示的当前记录

String table = "guestbook"; //要操作的表名

public Guestbook() {}
public Guestbook(int id) throws Exception{
read(id);
}
public Guestbook(ResultSet rs) throws Exception{
readFromRs(rs);
}
public void read(int id) throws Exception{
String q = "select * from "+table+" where id="+id;
ResultSet rs= Common.query(q);
if (!rs.next())
throw new Exception("记录没有找到: "+id);
this.readFromRs(rs);
}
public void readFromRs(ResultSet rs) throws Exception{
id = rs.getInt("id");
type = rs.getInt("type");
subject = rs.getString("subject");
body = rs.getString("body");
ip = rs.getString("ip");
host = rs.getString("host");
user = rs.getString("user");
postat = rs.getTimestamp("postat");
last = rs.getTimestamp("last");
}
public void setRequest() throws Exception{
action = myParseInt(request.getParameter("action"));
id = myParseInt(request.getParameter("id"));
subject = echo(request.getParameter("subject"));
body = echo(request.getParameter("body"));
type = myParseInt(request.getParameter("type"));

// 必须检查
// if (type<1)
// info.add("没有指定项目编号");
}

public boolean postInsert() throws Exception{
if (subject.length()==0)
info.add("没有填写主题");
if (body.length()==0)
this.info.add("没有填写内容");
if (!this.info.isEmpty())
return false;

String q = "insert into "+table+" (type,subject,body,ip,host,user,postat) values("+
type+","+
"\""+addSqlSlash(subject)+"\","+
"\""+addSqlSlash(body)+"\","+
"\""+ip+"\","+
"\""+host+"\","+
"\""+addSqlSlash(user)+"\","+
"\""+this.getSQLTime()+"\""+
")";
Common.update(q);
id = Common.lastInsertId();
return true;
}

public boolean postUpdate() throws Exception{
// to be finished
return true;
}

public boolean postDelete() throws Exception{
Guestbook todo = new Guestbook(id);
//不是作者要作权限检查
if (!this.isAuthor(todo))
this.info.add("不是作者, 不能删除");
if (this.id < 1 )
this.info.add("没有指定要删除的编号");

if (this.info.size()>0)
return false;

String q = "delete from "+table+" where id="+id;
update(q);
return true;
}
public void getList() throws Exception{
String query = "select * from "+table+" where type="+type+" order by postat desc";
list = query(query);
}
public boolean next() throws Exception{
if (this.list == null)
this.getList();
if (list.next()){
cur = new Guestbook(list);
return true;
}else
return false;
}

public String toString(){
return
"[ id:" +id
+",type:"+type
+",subject:"+subject
+",body:"+body
+",ip:"+ip
+",host:"+host
+",user:"+user
+",postat:"+postat
+",last:"+last
+",action:"+action
+"]";
}

public boolean checkAction() throws Exception{
this.setRequest();
// checkPriv(table+":"+type);
if (this.action == this.INSERT)
return this.postInsert();
if (this.action == this.UPDATE)
return this.postUpdate();
if (this.action == this.DELETE)
return this.postDelete();
return false;
}
public static void main(String[] args) throws Exception{}
}
...全文
55 点赞 收藏 5
写回复
5 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
luodi 2001-07-18
这么多代码呀。
留个索引先。:)
回复
steeven 2001-07-18
error.jsp (出错显示页面)
==============================

<%@ page contentType="text/html;charset=GBK" %>
<%@ page isErrorPage="true" %>
<%@ page import="java.sql.*,java.text.*,java.util.*" %>
<html>
<head>
<title><%=steeven.Common.getTitle()%></title>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
</head>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<br>
<table align="center" cellspacing=0 width="95%">
<tr><td><p>发现错误:</p>
<blockquote><%=steeven.Common.htmlEcho(exception.getMessage())%></blockquote>
<textarea cols=100 rows=20>
<% exception.printStackTrace(response.getWriter()); %>
</textarea>
</td></tr>
</table>
</body>
</html>
回复
steeven 2001-07-18
faq.jsp (我用Guestboook实现FAQ列表)
===================================

<%@ page contentType="text/html;charset=GBK" %>
<%@ page errorPage="../inc/error.jsp" %>
<%@ page import="java.sql.*,java.text.*,java.util.*" %>
<jsp:useBean id="gb" scope="page" class="steeven.Guestbook" >
<jsp:setProperty name="gb" property="pageContext" value="<%=pageContext%>" />
</jsp:useBean>

<%
gb.setDebug(true);
if (gb.checkAction())
response.sendRedirect("faq.jsp?type="+gb.type);
%>
<body background="/images/bg-steeven.gif">
<table border=0 cellpadding=0 cellspacing=5 width="90%" align="center">
<tbody>
<tr>
<td>
<center>
<a href="http://www/"><img border=0 height=74
src="/images/steeven2.gif" width=70></a>
</center>
</td>
<td valign=bottom align="right">更新日: 2001-07-17 </td>
</tr>
<tr>
<td></td>
<td>
<div align=right></div>
</td>
</tr>
</tbody>
</table>
<br>
<h2 align=center>FAQ</h2>
<%=gb.printInfo()%>
<hr size="1">
<blockquote style="BACKGROUND-COLOR: white">
<% while(gb.next()) { %>
<blockquote>● <%=gb.htmlEcho(gb.cur.subject)%> - <small><%=gb.htmlEcho(gb.cur.user)%>
<%=gb.formatTime(gb.cur.postat,6)%>
<% if (gb.isAuthor(gb.cur)) { %>
<a href=?type=<%=gb.type%>&id=<%=gb.cur.id%>&action=<%=gb.DELETE%>>删除</a>
<% } %>
</small><br>
<ul><%=gb.htmlEcho(gb.cur.body)%></ul>
<hr size="1">
</blockquote>
<% } %>
<form name="form1" method="post" action="">
<p align="center">
<input type="text" name="subject" size="60" maxlength="60">
<input type="hidden" name="type" value="<%=gb.type%>">
<input type="hidden" name="action" value="<%=gb.INSERT%>">
</p>
<p align="center">
<textarea name="body" cols="60" rows="10"></textarea>
</p>
<p align="center">
<input type="submit" name="Submit" value=" 提 交 ">
</p>
</form>
<p> </p>
</blockquote>
<hr>
<div align="center"><img height=16 src="/images/konami.gif" width=89><br>
<font color=#191970
size=2>(C)2001 Steeven ALL RIGHTS RESERVED.</font> </div>
<h2 align=center> </h2>


回复
steeven 2001-07-18
//Common.java

package steeven;

import java.sql.*;
import java.util.*;
import java.text.*;
import javax.servlet.http.*;


public class Common {

// private final static String dbDriver = "sun.jdbc.odbc.JdbcOdbcDriver"; // ODBC驱动
// private static String url = "jdbc:odbc:steeven";
private static String dbDriver = "org.gjt.mm.mysql.Driver"; // mysql驱动
private static String url = "jdbc:mysql://localhost/steeven";

private final static String userName = "root"; // 数据库用户密码
private final static String userPswd = "";

private static String title = "中国制造";

public int action; // JSP请求动作
public static final int INSERT = 1;
public static final int NEW = 1;
public static final int UPDATE = 2;
public static final int DELETE = 3;
public static final int REPLY = 4;

public String ip,user,host; // 用户参数

javax.servlet.jsp.PageContext pageContext; // JSP参数
javax.servlet.http.HttpServletRequest request;
javax.servlet.http.HttpServletResponse response;
javax.servlet.http.HttpSession session;
javax.servlet.jsp.JspWriter out;

public ArrayList info = new ArrayList(); // 返回页面的信息提示

public static boolean debug; // 是否处于调试状态
private static Connection con = null; // 数据库连接
java.text.SimpleDateFormat timeFormatter = new java.text.SimpleDateFormat();
java.util.ArrayList speed; //速度测试

// 项目代号,名称
public static String[][] prodList =
{
{"10","测试"},
{"20","NBA"},
{"30","Frogger"},
{"40","Imode"}
};
String domain = "NTDOMAIN\\"; //RemoteUser中要过滤的NT域名

public Common() {}
public static String getTitle(){
// 返回 标题
return title;
}
public static void dbc() throws Exception{
// 数据库连接
if (con == null || con.isClosed()){
Class.forName(dbDriver);
con = DriverManager.getConnection(url, userName, userPswd);
if (debug) error("Database connected");
}
}
public static ResultSet query(String query) throws Exception{
// 返回查询结果
dbc();
if (debug) error(query);
// ResultSet rs = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY).executeQuery(query);
ResultSet rs = con.createStatement().executeQuery(query);
return rs;
}
public static ResultSet query(String query,int scroll,int read) throws Exception{
// 返回查询结果,指定游标类型,只读类型
dbc();
if (debug) error(query);
ResultSet rs = con.createStatement(scroll,read).executeQuery(query);
return rs;
}
public static int lastInsertId() throws Exception{
String q1= "select last_insert_id()";
ResultSet rs = query(q1);
rs.next();
return rs.getInt(1);
}
public static int update(String query) throws Exception{
// 执行SQL的Update
dbc();
if (debug) error(query);
return con.createStatement().executeUpdate(query);
}
public static String getSQLTime(){
// 取得符合sql的日期加时间字符串
java.util.Date now = new java.util.Date();
//java.sql.Timestamp time= new java.sql.Timestamp(now.getTime());
java.sql.Date date= new java.sql.Date(now.getTime());
java.sql.Time time = new java.sql.Time(now.getTime());
//error(time.toString());
return date.toString()+ " " +time.toString();
}
public static String getSQLDate(java.util.Date date){
// 取得符合sql的日期
java.sql.Date d= new java.sql.Date(date.getTime());
return d.toString();
}
public static void setDebug(boolean ifdebug) throws Exception{
// 设定调试状态
debug = ifdebug;
}
public static String echo(String s){
// 将null过滤为空字串
if (s==null) return "";
else return s;
}
public static Integer echo(Integer s){
// 将null过滤为0
if (s ==null) return new Integer(0);
else return s;
}
public static int myParseInt(String s){
// String->int, null->0
if (s ==null) return 0;
else return Integer.parseInt(s);
}
public float myParseFloat(String s){
// String->floast , null->0
try{
if (s ==null)
return 0;
else return Float.parseFloat(s);
}catch (Exception e){
info.add("无效的浮点数字: "+e.getMessage());
return 0;
}
}
public java.util.Date myParseDate(String s, int n) throws Exception{
// String->Date, null->0
if (s==null)
return new java.util.Date(0);
try{
SimpleDateFormat df = new SimpleDateFormat();
switch(n){
case 1:
return DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.SHORT).parse(s);
case 2:
return DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.MEDIUM).parse(s);
case 3:
return DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.LONG).parse(s);
case 4:
//日期: 07-28
df.applyPattern("MM-dd");
return df.parse(s);
case 5:
//日期: 2001-07-28
df.applyPattern("yyyy-MM-dd");
return df.parse(s);
default:
return DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL).parse(s);
}
}catch (Exception e){
info.add("无效的日期: "+s+e.getMessage());
return new java.util.Date(0);
}
}

public static String htmlEcho(String s){
// 过滤HTML
s = echo(s);
s = replace(s,"\"",""");
s = replace(s,"<","<");
s = replace(s,">",">");
s = replace(s,"\n","\n<br>");
return s;
}
public static String addSlash(String s){
// 将\替换成\ return replace(s,"\\","\\\\");
}
public static String addSqlSlash(String s){
// 对应mysql的替换: \->\\ "->\" '->\' null->\0
s = replace(s,"\\","\\\\");
s = replace(s,"\"","\\\"");
s = replace(s,"'","\\'");
s = replace(s,"\0","\\0");
return s;
}
public static String replace( String str, String pattern, String replace) {
// 字符串替换
int s = 0;
int e = 0;
StringBuffer result = new StringBuffer();
while ((e = str.indexOf(pattern, s)) >= 0) {
result.append(str.substring(s, e));
result.append(replace);
s = e+pattern.length();
}
result.append(str.substring(s));
return result.toString();
}
public static String formatTime(java.util.Date time,int n){
// 按指定类型格式化时间
SimpleDateFormat df = new SimpleDateFormat();
switch(n){
case 1:
//2001年6月28日 上午9:02
return DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.SHORT).format(time);
case 2:
//2001年6月28日 9:02:32
return DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.MEDIUM).format(time);
case 3:
return DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.LONG).format(time);
case 4:
//日期: 07-28
df.applyPattern("MM-dd");
return df.format(time);
case 5:
//日期: 2001-07-28
df.applyPattern("yyyy-MM-dd");
return df.format(time);
case 6:
//日期: 7-28 21:54
df.applyPattern("MM-dd kk:mm");
return df.format(time);
default:
return DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL).format(time);
}

}
public boolean isAuthor(Common c) throws Exception{
// 判断用户是否相同, 比较IP,User,Host
if (c.ip.equals(ip) && c.user.equals(user) && c.host.equals(host))
return true;
return false;
}
public void getAuthor() throws Exception{
// 取得用户资料, IP,User,Host
this.ip=echo(request.getRemoteAddr());
this.user=replace(echo(request.getRemoteUser()),domain,"");
this.host=java.net.InetAddress.getByName(echo(request.getRemoteHost())).getHostName();
}
public static String repeat(String s, int n){
// 重复字符串
int i;
String r = "";
for (i=0; i<n; i++)
r += s;
return r;
}
public static void error(String message){
// 打印错误
message = "发现错误: "+message;
System.err.println(message);
}
public void error(String message,java.lang.Exception e){
// 打印错误和Exception的内容
error(message+"\n错误内容如下: \n"+e.getMessage());
}
public void println(String s) throws Exception {
//在输出html中显示
out.println(s);
}
public String printInfo(){
//显示info中的错误提示
if (info.isEmpty()) return "";
String r = "<table align=center class=warn cellspacing=3 cellpadding=3 border=1><tr><td>";
for (int i=0; i<info.size(); i++)
r += "<li>"+info.get(i)+"</li>";
r += "</table>";
return r;
}
public void setPageContext(javax.servlet.jsp.PageContext p) throws Exception{
// 设定PageContext, 在bean中取得Jsp的相关引用
this.pageContext = p;
this.request = (javax.servlet.http.HttpServletRequest)p.getRequest();
this.response = (javax.servlet.http.HttpServletResponse)p.getResponse();
this.session = request.getSession();
this.out = p.getOut();
this.getAuthor(); //defautl get all user information
}
public static String getProdTitle(int prodid){
// 根据项目编号取得项目名称
for (int i=0;i<prodList.length;i++)
if (String.valueOf(prodid).equals(prodList[i][0]))
return prodList[i][1];
return "没有指定产品别";
}
public static String getProdList(int id) throws Exception{
// 显示用于<select>的<option>list. Id 为缺省值
String r = "";
for (int i=0;i<prodList.length;i++)
r += "<option"+(String.valueOf(id).equals(prodList[i][0])?" selected":"")+" value="+prodList[i][0]+">"+prodList[i][1]+"</option>";
return r;
}
public String getSession(String key){
// 返回Session中的变量
return echo((String)session.getAttribute(key));
}
public String getCookie(String key){
// 取得Cookie变量
Cookie myCookie[]=request.getCookies();
for(int n=0;n<myCookie.length;n++){
Cookie newCookie= myCookie[n];
if(newCookie.getName().equals(key))
return newCookie.getValue();
}
return "";
}
public void cutTime(Calendar c){
// 去掉日历中的时间部分
c.set(Calendar.HOUR_OF_DAY,0);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND,0);
c.set(Calendar.MINUTE,0);
}
public void cutDate(Calendar c){
// 去掉日历中的日期部分
c.set(Calendar.YEAR,0);
c.set(Calendar.MONTH,0);
c.set(Calendar.DAY_OF_MONTH,0);
}
public void speedTest(){
//速度测试
if (speed == null) speed = new java.util.ArrayList();
speed.add(new java.util.Date());
}
public void speedPrint(){
//速度显示
if (speed == null)
echo("No speed has been setted before");
else{
java.util.Date first = (java.util.Date)speed.get(0);
java.util.Date last = (java.util.Date)speed.get(0);
for (int i=0;i<speed.size();i++){
java.util.Date speedI = (java.util.Date)speed.get(i);
error((i+1)+": "+(speedI.getTime()-last.getTime())+"<br>");
last = (java.util.Date)speed.get(i);
}
error("Total: "+(last.getTime()-first.getTime())+"<br>");
}
}
public boolean getPriv(String point) throws Exception{
//测试当前用户是否对指定内容Point有权限. 其中Point一般为"功能+项目id"
//用户名和组名可以使用"*"
String q = "select 1 from priv left join usergroup on priv.grp=usergroup.name where (point='"+point+"' and (priv.user='*' or priv.grp='*' or priv.user='"+user+"' or usergroup.user='"+user+"'))"+
" or (point='*' and (priv.user='*' or priv.grp='*' or priv.user='"+user+"' or usergroup.user='"+user+"'))";
ResultSet r = query(q);
if (r.next()) return true;
return false;
}

public void checkPriv(String point) throws Exception{
//检查用户是否有操作权限
if (!getPriv(point))
throw new Exception("没有操作权限("+point+")");
}
public static void main(String[] args) throws Exception {
Common t = new Common();
System.out.println(t.addSqlSlash("0"+'\u0000'));
}
}
回复
steeven 2001-07-18
一共才4个文件
回复
相关推荐
发帖
Web 开发
创建于2007-09-28

8.0w+

社区成员

Java Web 开发
申请成为版主
帖子事件
创建了帖子
2001-07-18 10:02
社区公告
暂无公告