JSP简易留言板

写在前面

在上篇博文JSP内置对象中介绍JSP的9个内置对象的含义和常用方法,但都是比较理论的知识。今天为大家带来一个小应用,用application制作的简易留言板。

包括三个功能模块:留言提交、留言展示、查看留言板。用3个JSP页面展示信息(视图层),一个servlet处理用户的请求(控制层),因为比较简单没有用到javaBean作为模型层。还有一个filter初始化应用。

表单提交

本例中用submit.jsp页面提交留言。用表单提交用户的请求参数,action参数处理用户请求程序的路径。关于表单提交有两点说明:

1.路径

在JSP页面中,建议用绝对路径,形如:<%=request.getContextPath()%>/MsgPane,request.getContextPath()代表项目的根目录。其原因是绝对路径简单不容易出错。在写JSP程序是经常会犯路径的错误,就是没明白一些基本的概念。

在html标签中,“/”是代表服务器的根目录:形如:http://localhost:8080/

在JSP脚本中,“/”Web应用的根目录:形如:http://localhost:8080/yourwebapp/

为了统一前后端路径的使用,IDE在新建JSP的会加入<base>标签,这个时候相对路径是不起作用的,浏览器解析时会在其前面加上base的href属性值。例如:

有<base>标签的存在,<form action="MsgPane" method="post"> 浏览器解析的路径为“http://localhost:8080/yourwebapp/”+Msgpane。

2.方法

post提交时,参数不会附加在URL中,安全性更高,表单提交建议使用post。

submit.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>  
  <body>
    <form action="<%=request.getContextPath()%>/MsgPane" method="post">
        请输入你的姓名:<br><input type="text" name="name"><br>
        请输入你的标题:<br><input type="text" name="title"><br>
        留言内容:<br><textarea rows="15" cols="20" name="message"></textarea><br><br>       
        <input type="submit" value="提交信息"><br>
    </form>
    <form action="<%=request.getContextPath()%>/msgpane/messages.jsp">
        <input type="submit" value="查看留言板">
    </form>
<%--  </body>--%>
</html>

处理用户请求

我们一般用servlet处理用户请求,servlet多用于流程控制,也就是我们常说得MVC中C(控制层)。

1.处理表单参数的中文乱码,可在servlet重写的请求方法中加入

request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");

2.application对象在JSP中是内置的,而在servlet中,需要自己去实例化。

ServletContext application = request.getServletContext();

3.application的常用方法,其实底层实现是Map。

application.setAttribute(String key,Object obj); 
application.getAttribute(String key); //Object,需要类型强转!

4.session与application常用方法类似,只是作用范围限于同一用户,而application是整个应用,用下面方法实例化。

HttpSession session=request.getSession(); 

MsgPane.java

package servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class MsgPane extends HttpServlet {
    List<String> msgs;
    int count;
    String objfile="";
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        objfile=request.getServletContext().getRealPath("/")+"msgpane\\Msgpane.obj";
        System.out.println(objfile);
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        ServletContext application = request.getServletContext();
        HttpSession session=request.getSession();
        if(application.getAttribute("msgs")!=null){
            msgs=(List<String>)application.getAttribute("msgs");
        }else{
            msgs=new ArrayList();
            System.out.println("New");
        }
        count = msgs.size();
        String date = new Date().toLocaleString();
        String name = request.getParameter("name");
        String title = request.getParameter("title");
        String msg = request.getParameter("message");
        if (name == null || "".equals(name)) {
            name = "guest";
        }
        if (title == null || "".equals(title)) {
            title = "无标题";
        }
        if (msg == null || "".equals(msg)) {
            request.getRequestDispatcher("/msgpane/submit.jsp").forward(request,
                    response);
        } else {
            count++;
            String tmsg = "<br><br><br>No." + count + "&nbsp;&nbsp;&nbsp;"
                    + date + "<br><br>姓名:" + name + "<br>标题:" + title
                    + "<br>内容:" + msg;
            msgs.add(tmsg);
            saveMsgPane(objfile);            
            application.setAttribute("msgs", msgs);
            session.setAttribute("msg", tmsg);
            request.getRequestDispatcher("/msgpane/msgpane.jsp").forward(request,
                    response);            
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doGet(req, resp);
    }

    public void saveMsgPane(String filename) {
        try {
            saveObject(filename, msgs);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void saveObject(String filename, Object obj) throws IOException {
        File f = new File(filename);
        if (!f.exists()) {
            f.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(f);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(obj);
        fos.close();
        oos.close();
    }
}

初始化应用

在启动应用时,将留言板内容从文件读取,存入application对象。

MsgpaneFilter.java

package filter;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MsgpaneFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        String objfile = request.getServletContext().getRealPath("/")+"msgpane\\Msgpane.obj";
        System.out.println(objfile);
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        ServletContext application = request.getServletContext();
        if (application.getAttribute("msgs") == null) {
            File f = new File(objfile);
            if (f.exists()) {
                try {
                    application.setAttribute("msgs", readObject(objfile));
                    System.out.println("read");
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("File not found!");
                req.getRequestDispatcher("/msgpane/submit.jsp").forward(req,
                        resp);
            }
        }
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
    }

    public Object readObject(String filename) throws IOException,
            ClassNotFoundException {
        Object obj = null;
        File ft = new File(filename);
        if (ft.exists()) {
            FileInputStream fis = new FileInputStream(ft);
            ObjectInputStream ois = new ObjectInputStream(fis);
            obj = ois.readObject();
            fis.close();
            ois.close();
        } else {
            // do something
        }
        return obj;
    }
}

关于留言展示和查看留言板我就不贴代码了,非常简单。这个小例子的代码我打包好了,下面是链接:

msgpanehttps://files.cnblogs.com/files/klguang/msgpane.rar

posted @ 2015-08-08 14:02  klguang  阅读(12258)  评论(5编辑  收藏  举报