欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java-web实现简单留言板(含代码)

程序员文章站 2022-03-16 14:54:44
文章目录一、目标二、相关知识三、实现思路四、代码实现一、目标用户可以登录并记住密码进入留言板,添加留言,点击留言列表中的标题可显示该条留言全部内容。二、相关知识使用Cookie实现自动登录用户第一次登录网站,服务器将用户名和密码以Cookie的形式发送到客户端。当客户之后再次访问该网站时,浏览器自动将Cookie文件中的用户名和密码随请求一起发送到服务器,服务器从Cookie中取出用户名和密码并且通过验证。java类的定义与使用定义java类时注意属性的定义、构造方法的重写,定义两个方法,一...

一、目标

用户可以登录并记住密码进入留言板,添加留言,点击留言列表中的标题可显示该条留言全部内容。

二、相关知识

  1. 使用Cookie实现自动登录
    用户第一次登录网站,服务器将用户名和密码以Cookie的形式发送到客户端。当客户之后再次访问该网站时,浏览器自动将Cookie文件中的用户名和密码随请求一起发送到服务器,服务器从Cookie中取出用户名和密码并且通过验证。
  2. java类的定义与使用
    定义java类时注意属性的定义、构造方法的重写,定义两个方法,一个是访问方法(getter),一个是修改方法(setter)。

三、实现思路

  1. 登录
    输入用户名、密码登录,对应检测登录BoardLoginServlet
    可实现记住登录信息 Cookie实现
    登录成功显示留言板标题列表页面board-title.jsp,登录失败返回登录页面
  2. 显示留言标题
    标题列表为上下文变量lists,其中标题为链接,点击可显示留言具体信息界面(跳转到MessageServlet处理)。
 list = username+":"+"<a href='MessageServlet?title="+title+"'target='_parent'>"+title+"</a>";

页面下方有新增留言的链接,点击后跳转到写留言页面

 <a href="board-write.jsp">新增留言</a>
  1. 添加留言
    输入标题、内容 post给WriteServlet
  2. 显示留言具体信息
    在MessageServlet中遍历查找留言并传递变量,显示留言信息在board-message.jsp

四、代码实现

  1. board-login.jsp
<form action="board.do" method="post">
    <br>
    <h1 class="text" >登录界面</h1>
            昵称:<input type="text" name="username" value="${cookie.username.value}"/><br>
            密码:<input type="password" name="password" value="${cookie.password.value}"/><br><br>
            <input type="checkbox" name="check" value="check"/>记住密码<br>  <br>
            <input type="submit" value="登录"/>
            <input type="reset" value="取消"/>
</form>
  1. board-title.jsp
 <h2>留言板</h2>
    ${lists}
    <a href="board-write.jsp">新增留言</a>
  1. boarrd-write.jsp
<form action="write.do" method="post">
    标题:<input type="text" name="title"/><br>
    内容:<input type="text" name="text"/><br>
    <input type="submit"/>
</form>
  1. board-message.jsp
<h2>留言详情</h2>
    用户名:${name}<br>
    标题:${title}<br>
    内容:${text}<br>
    时间:${date}<br>
  1. Message.java(将留言信息存储在Message类中)
package board;

import java.util.Date;

public class Message {
    private String title;//标题
    private String time;//时间
    private String username;//用户名
    private String text;//内容
    public Message(){}
    //初始化
    public Message(String title,String time,String username,String text){
        this.title = title;
        this.time = time;
        this.username = username;
        this.text = text;
    }

    public String getTitle(){
        return title;
    }
    public String getUsername(){
        return username;
    }
    public String getTime(){
        return time;
    }
    public String getText(){
        return text;
    }
}


  1. BoardLoginServlet.java(用Cookie登录)
package board;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

@javax.servlet.annotation.WebServlet(name = "BoardLoginServlet",urlPatterns = "/board.do")
public class BoardLoginServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset = utf-8");
        request.setCharacterEncoding("UTF-8");
        HttpSession session=request.getSession();
        String username = request.getParameter("username").trim();
        String password = request.getParameter("password").trim();
        session.setAttribute("username",username);
        if (!(username.equals("admin") &&password.equals("admin"))&&!(username.equals("123") &&password.equals("123"))) {
            response.sendRedirect("board-login.jsp");
        } else {

            if ((request.getParameter("check") != null) && (request.getParameter("check").equals("check"))) {
                Cookie nameCookie = new Cookie("username", username);
                Cookie pswdCookie = new Cookie("password", password);
                nameCookie.setMaxAge(60 * 60);
                pswdCookie.setMaxAge(60 * 60);
                nameCookie.setPath("/");
                pswdCookie.setPath("/");
                response.addCookie(nameCookie);
                response.addCookie(pswdCookie);
                String value1 = "", value2 = "";
                Cookie cookie = null;
                Cookie[] cookies = request.getCookies();
                if (cookies != null) {
                    for (int i = 0; i < cookies.length; i++) {
                        cookie = cookies[i];
                        if (cookie.getName().equals("username"))
                            value1 = cookie.getValue();
                        if (cookie.getName().equals("password"))
                            value2 = cookie.getValue();
                    }
                    if (value1.equals("admin") && value2.equals("admin")||value1.equals("123") && value2.equals("123")) {
                        response.sendRedirect("board-title.jsp");
                    } else {
                        response.sendRedirect("board-login.jsp");
                    }

                }
            }
            else
            {
                response.sendRedirect("board-title.jsp");
            }
        }

    }
}

  1. WriteServlet.java(新增留言)
package board;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet(name = "WriteServlet",urlPatterns = "/write.do")
public class WriteServlet extends HttpServlet {
	//messages列表中存放Message类对象
    public List<Message> messages = new ArrayList<Message>();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        ServletContext context = request.getServletContext();
        HttpSession session = request.getSession();
        //用户名存储到session中
        String username =(String)session.getAttribute("username");
        String title = request.getParameter("title");
        String text = request.getParameter("text");
        //获取当前时间
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String time = formatter.format(date);
		//在messages列表中添加留言对象
        messages.add(new Message(title,time,username,text));
        context.setAttribute("messages",messages);

        String list = new String();
        //list中存放留言用户名+留言标题,标题为链接,可跳转到留言具体信息,并传参title
        list = username+":"+"<a href='MessageServlet?title="+title+"'target='_parent'>"+title+"</a>";
        String lists = new String();
        //将留言标题列表信息存到上下文对象
        if(context.getAttribute("lists")!=null){
            lists = context.getAttribute("lists") + list + "<br>";
        }
        else{
            lists = list + "<br>";
        }
        context.setAttribute("lists", lists);
        request.setAttribute("lists", lists);
		//转发
        RequestDispatcher dispatcher = request.getRequestDispatcher("/board-title.jsp");
        dispatcher.forward(request, response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

  1. MessageServlet.java
package board;

import com.sun.net.httpserver.HttpContext;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "MessageServlet",urlPatterns = "/MessageServlet")
public class MessageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        ServletContext context = request.getServletContext();
        List<Message> messages = new ArrayList<Message>();
        //获取列表
        messages = (List<Message>)context.getAttribute("messages");
        //获取链接中的参数title
        String title =request.getParameter("title");
        String name = new String();
        String date = new String();
        String text = new String();
		//遍历列表,查找该title的具体信息
        for(Message message : messages){
            if((message.getTitle()).equals(title)){
                name = message.getUsername();
                date = message.getTime();
                text = message.getText();
                title = message.getTitle();
                request.setAttribute("name",name);
                request.setAttribute("title",title);
                request.setAttribute("text",text);
                request.setAttribute("date",date);
                break;
            }
        }
        //将留言信息转发到board-message.jsp
        RequestDispatcher dispatcher = request.getRequestDispatcher("/board-message.jsp");
        dispatcher.forward(request, response);




    }
}

(以上仅为部分代码)

本人原创,欢迎转载~

本文地址:https://blog.csdn.net/weixin_46041475/article/details/109930277