JSP Simple Message Board

Source: Internet
Author: User

Write in front

The meaning and common methods of JSP's 9 built-in objects are introduced in the JSP built-in object in the previous blog post, but they are all knowledge of comparative theory. Today for everyone to bring a small application, made with application simple message boards.

Includes three function modules: Message submission, view display, view message boards. Using 3 JSP pages to present the information (the view layer), a servlet handles the user's request (the control layer) because it is relatively simple to use JavaBean as the model layer. There is also a filter initialization application.

Form submission

This example uses the Submit.jsp page to submit a message. Submits the user's request parameters with the form, and the action parameter handles the path of the user requestor. There are two notes about form submission:

1. Path

In the JSP page, it is recommended to use an absolute path, such as: <%=request.getcontextpath ()%>/msgpane,request.getcontextpath () to represent the root directory of the project. The reason is that the absolute path is simple and not error prone. In writing a JSP program is often a mistake to make a path, just do not understand some basic concepts.

In the HTML tag, "/" is the root directory of the server: The shape: http://localhost:8080/

In the JSP script, the root directory of the "/" Web App: Shape: http://localhost:8080/yourwebapp/

In order to unify the use of the front and back end path, the IDE will add the <base> tag to the new JSP, this time the relative path is not working, and when the browser resolves it, it will precede it with the value of the href attribute of base. For example:

With the presence of <base> tags, <form action= "Msgpane" method= "POST" > Browser parsing path is "http://localhost:8080/yourwebapp/" + Msgpane.

2. Methods

When the post is submitted, the parameter is not appended to the URL, and security is higher, and the form submission recommends using Post.

submit.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
Handling User Requests

We typically use Servlets to process user requests, and Servlets are used for process control, which is what we often call MVC C (Control layer).

1. Handle the Chinese characters of the form parameter, which can be added in the servlet rewrite request method.

Request.setcharacterencoding ("UTF-8"); Response.setcharacterencoding ("UTF-8");

2.application objects are built into the JSP, and in the servlet, you need to instantiate them yourself.

ServletContext application = Request.getservletcontext ();

3.application is a common method, in fact, the underlying implementation is map.

Application.setattribute (String key,object obj); Application.getattribute (String key); Object, need type strong turn!

4.session is similar to application commonly used, except that the scope is limited to the same user, and application is the entire application, instantiated using the following method.

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, Ioexceptio        n {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 = "Untitled"; } if (msg = = NULL | | ". Equals (msg)) {Request.getrequestdispatcher ("/msgpane/submit.jsp "). Forward (Request, RESPO        NSE);            } else {count++; String tmsg = "<br><br><br>no." + COunt + "&nbsp;&nbsp;&nbsp;"            + Date + "<br><br> Name:" + name + "<br> title:" + title + "<br> content:" + 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 Servletex    Ception, 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 (); }}
Filter initialization

When the app is launched, the message board content is read from the file and stored in the Application object.

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 I  NIT (Filterconfig filterconfig) throws servletexception {} @Override public void DoFilter (ServletRequest request, Servletresponse response, Filterchain chain) throws IOException, servletexception {String objfile = re        Quest.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; }}

about the message display and view the message board I will not post code, very simple. This small example of the code I packed, here is the link:

Msgpane : Http://files.cnblogs.com/files/klguang/msgpane.rar

JSP Simple Message Board

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.