index.jsp
<%@ page language="java" contentType="text/html" pageEncoding="GBK"%>
<%@page import="java.util.List"%><%@page import="com.lyq.model.Message"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>主页</title> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <div style="text-align: left; vertical-align: middle;"> <% List<Message> list = (List<Message>)application.getAttribute("messages"); if(list != null && list.size() > 0){ for(Message m : list){ %> <div style="width: 500px; border: 1px solid;"> <div style=" font-size: 14px; height: 22px; color: white; padding-left: 10px;"> <b><%=m.getTitle()%></b> </div> <div style="font-size: 12px; height: 20px;padding-left: 10px; margin: 5px;"> <%=m.getContent()%> <br> </div> </div> <% } } %> <form action="MessageServlet" method="post"> <div style="width: 500px; border: 1px solid;"> <span>留言标题:</span> <span><input type="text" name="title"></span> <br> <span>留言内容:</span> <span><textarea name="content" cols="30" rows="5"></textarea></span> <br> <input type="submit" value="留 言"> </div> </form> </div> </body></html>javaBean Message.java
package com.lyq.model;
public class Message { private int id; private String title; private String content; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
servlet MessageServlet.java
package com.lyq.controller;
import java.io.IOException;import java.util.ArrayList;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 com.lyq.model.Message;public class MessageServlet extends HttpServlet { private static final long serialVersionUID = -3822345405086497551L; public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); request.setCharacterEncoding("GBK"); String title=request.getParameter("title"); String content=request.getParameter("content"); if (title!=null&&content!=null) { Message message=new Message(); message.setTitle(title); message.setContent(content); ServletContext application=getServletContext(); List<Message> list=(List<Message>) application.getAttribute("messages"); if (list!=null) { list.add(message); }else { list=new ArrayList<Message>(); list.add(message); } application.setAttribute("messages", list); } request.getRequestDispatcher("index.jsp").forward(request, response); }}P108