jsp簡單留言板

網頁內容

新增留言postIt.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%
    request.setCharacterEncoding("UTF-8");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>發佈留言</title>
<script type="text/javascript"
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        $("#back").click(function() {
            //location.href ="display.jsp";
            history.back();
        });

        $('#myform').bind(
                'submit',
                function() {
                    //alert(123);
                    $('input[type=submit]', this).attr('disabled', 'disabled');

                    var value = {};
                    var x = 0;
                    var y = 0;
                    var temp = {};
                    var rtv = true;
                    //alert(123);
                    var elements = $(this).serializeArray();
                    //alert(123);
                    $.each(elements, function(i, element) {
                        var tempname = elements[i].name;
                        var tempvalue = elements[i].value;
                        if (rtv == true && tempname == "title"
                                && tempvalue.trim() == "") {
                            EmptyAlert("標題");

                            rtv = false;
                            //break;
                        }
                        if (rtv == true && tempname == "name"
                                && tempvalue.trim() == "") {
                            EmptyAlert("名字");

                            rtv = false;
                            //break;
                        }
                        if (rtv == true && tempname == "desc"
                                && tempvalue.trim() == "") {
                            EmptyAlert("內容");
                            rtv = false;
                            //break;

                        }

                    });
                    if (rtv == true)
                        createIFrame();

                    //alert(123);
                    //this.removeAttr('disabled');
                    $('input[type=submit]', this).removeAttr('disabled');
                    return rtv;
                });

    });
    function createIFrame() {
        if (!document.getElementById("_hiddenframe")) {
            var frame = document.createElement("iframe");
            frame.setAttribute("name", "_hiddenframe1");
            frame.setAttribute("src", "about:blank");
            frame.setAttribute("frameborder", "0");
            frame.setAttribute("height", "0");
            frame.setAttribute("width", "0");
            frame.setAttribute("id", "_hiddenframe");
            frame.name = "_hiddenframe";
            document.body.appendChild(frame);
            window.frames._hiddenframe.name = "_hiddenframe";
            document.getElementsByTagName("body")[0].appendChild(frame);

        }

    }

    function EmptyAlert(str) {
        alert(str + "不可為空白!");
    }
    function EmptyRadioAlert(str) {
        alert("請選擇一個" + str + "項目!");
    }
    function nvl(str, value) {
        if (str.blank())
            return value;
        else
            return str;
    }
</script>
<%=yslifes.tools.CommonDesc.script()%>
</head>
<body>
<form id="myform" name="myform" action="postAction.jsp" method="post"
    target="_hiddenframe">
<table>
    <tr>
        <td>*標題</td>
        <td><input type="text" name="title" /></td>
    </tr>
    <tr>
        <td>*名稱</td>
        <td><input type="text" name="name" /></td>
    </tr>
    <tr>
        <td>mail(不會公佈)</td>
        <td><input type="text" name="mail" /></td>
    </tr>
    <tr>
        <td>電話(不會公佈)</td>
        <td><input type="text" name="tel" /></td>
    </tr>
    <tr>
        <td colspan="2"><textarea cols="28" rows="10" name="desc"></textarea></td>
    </tr>
    <tr>
        <td colspan="2" align="right"><input type="submit" value="發表留言" /><input
            type="button" id="back" value="回留言區" /></td>
    </tr>
</table>
</form>
</body>
</html>

留言新增動作postAction.jsp

<%@page import="org.apache.commons.lang.StringUtils"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%><%!private org.apache.log4j.Logger logger = org.apache.log4j.Logger
            .getLogger(this.getClass());%>
<%
    request.setCharacterEncoding("UTF-8");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>留言</title>
<%=yslifes.tools.CommonDesc.script()%>
</head>
<body>
<script type="text/javascrip">
<%String error = "";
            String name = request.getParameter("name");
            if (name == null || name.trim().equals(""))
                error += "名稱必需填寫!\\r\\n";
            String title = request.getParameter("title");
            if (title == null || title.trim().equals(""))
                error += "標題必需填寫!\\r\\n";
            String mail = yslifes.tools.StringTool.nvl(
                    request.getParameter("mail"), "");
            String tel = yslifes.tools.StringTool.nvl(
                    request.getParameter("tel"), "");
            String desc = request.getParameter("desc");
            if (desc != null)
                desc = yslifes.tools.StringTool.reFormat(desc);
            if (desc == null || desc.trim().equals(""))
                error += "描述內容不可不填!\\r\\n";
            else if (desc.length() > 2000)
                error += "描述內容不可超過2000字元!\\r\\n";
            if (error.equals("")) {
                java.sql.Connection con = null;
                java.sql.PreparedStatement ps = null;
                try {
                    String sql = "insert into threads(post_name,post_title,post_mail,post_tel,post_desc) values(?,?,?,?,?)";
                    con = yslifes.db.DataSource.getConnection();
                    ps = con.prepareStatement(sql);
                    int idx = 0;
                    ps.setString(++idx, yslifes.tools.StringTool.reFormat(name));
                    ps.setString(++idx,
                            yslifes.tools.StringTool.reFormat(title));
                    ps.setString(++idx, yslifes.tools.StringTool.reFormat(mail));
                    ps.setString(++idx, yslifes.tools.StringTool.reFormat(tel));
                    ps.setString(++idx, desc);
                    logger.debug("PostAction:" + desc);
                    ps.executeUpdate();
                } catch (java.sql.SQLException e) {
                    logger.info(e);
                    e.printStackTrace();
                    error = "資料操作錯誤!";
                }
            }
            out.println("var message = '" + error + "'");%>
    if (message == "") {
        alert("存檔成功!");
        top.location.replace("display.jsp");
    } else {
        alert(message);
    }
</script>
</body>
</html>

留言列表及查詢功能

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%><%!private org.apache.log4j.Logger logger = org.apache.log4j.Logger
            .getLogger(this.getClass());%><%request.setCharacterEncoding("UTF-8"); %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html> 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>留言顯示</title>
<style>
.thread
{
    width:280px;
} 
.thread .title
{
    border:1px solid #00ff0a;
    width:100%;
    clear:both;
    height:46px;
}
.thread .title .Info
{
    float:left;
    width:70%;
    overflow:hidden;
    height:100%
}
.thread .title .Info .userInfo
{
    width:100%;
    height:50%
}
.thread .title .Info .titleInfo
{
    width:100%;
    height:50%
}
.thread .title .postTime
{
    float:left;
    width:30%;
    height:100%
    overflow:hidden;
}
.thread .description
{
    clear:both;
    width:100%;
    word-break: break-all;
    border:1px solid #a0ff0a;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js">
</script>
<script type="text/javascript">
$(function() {
    $("#postIt").click(function()
    {
        location.href ="postIt.jsp";
    });
});
</script>
<%=yslifes.tools.CommonDesc.script()%>
<%String s = yslifes.tools.StringTool.nvl(request.getParameter("s"),""); %>
</head>
<body>
<button id="postIt">我要留言</button>
<form ><input type="text" name="s" value="<%=s %>" /><input type="submit"  value="查詢"/></form>
<%
String where ="";
int per_page = 20;
int p = 1 ;
int p_num = 0;
String sp = request.getParameter("p");
if(sp!=null)
{
    try
    {
        p = (Integer.parseInt(sp));
        p_num = (p-1)*per_page;
    }catch(Exception e)
    {
        
    }
    
}
if(!s.equals(""))
{
    where = " and (x.post_title like ? or x.post_desc like ?) ";
}
String sql = "select x.* from threads x where x.post_state=1 and x.post_show = 1 "+where +" order by create_time desc limit ? ,"+per_page ;
String sqlCount = "select count(*) as totrec from threads x where x.post_state=1 and x.post_show = 1 "+where ;
logger.debug("SQL :"+sql);
logger.debug("SQL Count:"+sqlCount);
java.sql.Connection con = null;
java.sql.PreparedStatement ps = null;
java.sql.ResultSet rs =null;
int totrec = 0;
try
{
    con = yslifes.db.DataSource.getConnection();
    ps = con.prepareStatement(sqlCount);
    int idx = 0;
    if(!s.equals(""))
    {
        ps.setString(++idx,"%"+s+"%");
        ps.setString(++idx,"%"+s+"%");
    }
    
    rs = ps.executeQuery();
    
    if(rs.next())
        totrec = rs.getInt("totrec");

    yslifes.db.Close.Single(rs);
    yslifes.db.Close.Single(ps);
    if(totrec > 0 )    {
    ps =  con.prepareStatement(sql);
    idx = 0;
    if(!s.equals(""))
    {
        ps.setString(++idx,"%"+s+"%");
        ps.setString(++idx,"%"+s+"%");
    }
    ps.setInt(++idx,p_num);
    rs = ps.executeQuery();
    while(rs.next()){
        String title = rs.getString("post_title");
        String desc = rs.getString("post_desc");
        String name = rs.getString("post_name");
        //String tel = yslifes.tools.StringTool.nvl(rs.getString("post_tel"),"");
        //String phone = yslifes.tools.StringTool.nvl(rs.getString("post_tel"),"");
        logger.debug(title);
        logger.debug(desc);
        logger.debug(name);
        String create_time = yslifes.tools.DateTool.DateTimeFormat((rs.getTimestamp("create_time")));
        String time[] = create_time.split(" ");
%>
<div class="thread">
<div class="title"><div class="Info">
<div class="userInfo"><%=name %></div>
<div class="titleInfo"><%=title %></div>
</div><div class="postTime"><%=time[0] %> <br/><%=time[1] %></div></div>
<div class="description"><%=desc %></div>
</div><%}}
    }catch(java.sql.SQLException e){
    logger.info(e);
    e.printStackTrace();
}
    logger.debug(totrec);
    yslifes.tools.SubPages subpage = new yslifes.tools.SubPages(per_page, 41, p,
           6, "display.jsp?s="+s+"&p=");
    out.println("<div style='clear:both'>"+subpage.subPageCss2()+"</div>");
     %>
</body>
</html>

範例檢視
原始碼下載

11 thoughts to “jsp簡單留言板”

  1. 板大我試你的都跑不出來 以下問題
    postIt.jsp 有顯是送出後跳到postAction.jsp 這裡就沒動進囉 好像沒連到mysql

    都是copy

    以下是我設定mysql
    連線名稱:test
    localhost
    3306
    root
    123456

    建立board資廖庫

    建立標單threads 有結取sql那個

    不知到是那出錯
    mysql的是5.1板的jar檔都有放

    請板大次教

      1. @yku, tomcat都沒有問題但好像連不到mysql
        連機本的postAction.jsp 險是錯誤視窗都沒有動靜

        輸入後postAction.jsp 沒有任何東西

        沒輸入postAction.jsp 沒有任何東西

  2. 板大方便的話
    及時通加我(雖然很久沒用)
    4/24都可以
    我會先用好相關的東西
    等板大有空密我即可

    感謝板大

  3. 板大我測試可以連資料庫但postIt.jsp 33行有問題找不出來不資源屬性

    第二個問題是輸入中文後

    查詢會查不到變成亂碼
    TEXT況內變亂碼所以都查不到之前輸入的中文

    1. 第一點可以給我錯誤訊息嘛?
      第二點的部份
      你可以到tomcat設定檔apache-tomcat-6.0.29\conf\server.xml裡
      (如果是Eclipse請找到專案目錄名稱為Server的,打開結點,可以看到server.xml這個檔)

      然後在Connector這個xml結點裡加上一個attribute
      useBodyEncodingForURI=”true”  及
      URIEncoding=”UTF-8″

      應該就可以解決中文亂碼的問題了

發表迴響