JSP+Servlet+JavaBean传统方式实现简易留言板制作(注册、登录、留言)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_33171970/article/details/51357037

    学JavaEE也有一段时间了,跟着老师和教材做了不少东西,但是一直以来没时间写博客,今天就把以前写的一个简易留言板简单发一下吧。

 

  • 开发工具

        主要用的开发工具为 MyEclipse(2014、2016均可)、Tomcat 7.0、SQL Server 2016、SSMS数据库管理工具、浏览器等。

  • 下载地址

百度网盘链接:https://pan.baidu.com/s/1c2iCPQ4 提取码:7yxk 

 

  • 开发环境

 

        开发环境为windows系统,已安装配置Java最新版开发环境。

 

  • 主要功能与语言

        登录、注册、并可以在留言板留言,所有留言内容均可见。

 

        所采用JSP+Servlet+JavaBean传统方式,仅限于学习使用。

 

 

  • 主要代码实现

    JSP代码:

 

login.jsp

 

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>  
    <title>登录界面</title>
  </head>
  
  <body bgcolor="#ddd" style="font-family:Microsoft YaHei" >
  <div style="text-align:center;margin-top:120px">
    <h1 >请登录</h1>
    <form action="loginServlet" method="post">
    	<table style="margin-left:40%">
    		<caption>用户登录</caption>
    		<tr>
    			<td>登录名:</td>
    			<td><input name="name" type="text" size="20"></td>
    		</tr>
    		<tr>
    			<td>密码:</td>
    			<td><input name="password" type="password" size="21"></td>
    		</tr>
    	</table> 
    	<input type="submit" value="登录">
    	<input type="reset" value="重置"> 
    </form>
    <br>
    <a href="register.jsp">注册</a>
    </div>
  </body>
</html>


register.jsp

 

 

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>  
    <title>注册界面</title>
  </head>
  
  <body bgcolor="#ddd" style="font-family:Microsoft YaHei" >
  <div style="text-align:center;margin-top:120px">
    <h1 >请注册</h1>
    <form action="registerServlet" method="post">
    	<table style="margin-left:40%">
    		<caption>用户注册</caption>
    		<tr>
    		    <td>ID:</td>
    		    <td><input name="id" type="text" size="20"></td>
    		</tr>
    		<tr>
    			<td>登录名:</td>
    			<td><input name="name" type="text" size="20"></td>
    		</tr>
    		<tr>
    			<td>密码:</td>
    			<td><input name="password" type="password" size="21"></td>
    		</tr>
    	</table> 
    	<input type="submit" value="注册">
    	<input type="reset" value="重置"> 
    </form>
    <br>
    <a href="login.jsp">登录</a>
    </div>
  </body>
</html>


error.jsp

 

 

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>  
    <title>登录出错界面</title>
  </head>
  
  <body bgcolor="#ddd" style="font-family:Microsoft YaHei">
  <div style="text-align:center;margin-top:130px">
    <p>输入的用户名不存在或者密码错误</p>
    <a href="login.jsp">点我返回登陆界面</a>
    </div>
  </body>
</html>


main.jsp

 

 

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@page import="org.model.MessBoar" %>
<%@page import="org.dao.*" %>

<html>
  <head>  
    <title>留言板界面</title>
  </head>

  <body bgcolor="#ddd" >
  <div style="margin-left:35%;margin-top:100px;font-family:Microsoft YaHei">
   <h1 style="margin-left:5%">这里是留言板主界面</h1>
   <form  action="leavemessage.jsp" method="post">
  		<table border="1">
  			<caption>所有留言信息</caption>
  			<tr><th>留言人姓名</th><th>留言时间</th>
				<th>留言标题</th><th>留言内容</th></tr>
  		<%
  			ArrayList<MessBoar> al=new ArrayList<MessBoar>();
  			al= (ArrayList)session.getAttribute("al");
  			if(al!=null){
  				Iterator iter=al.iterator();
  				while(iter.hasNext()){
  				MessBoar mb=(MessBoar)iter.next();
  		%>
  				<tr><td><%= new LoginDao().getName(mb.getId()) %></td>
  					<td><%= mb.getTime().toString() %></td>
  					<td><%= mb.getTitle() %></td>
  					<td><%= mb.getMessage() %></td></tr>
  		<% 
  			}
  			}
  		 %>
  		</table>
  	</form>
   <a style="margin-left:22%" href="leavemessage.jsp">留言</a>
    </div>
  </body>
</html>


leavemessage.jsp

 

 

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@page import="org.model.MessBoar" %>
<%@page import="org.dao.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>  
    <title>留言界面</title>
  </head>
  
  <body bgcolor="#ddd" style="font-family:Microsoft YaHei">
  <div style="text-align:center;margin-top:140px">
    <h1 >请留言</h1>
   <form action="leaveMessageServlet" method="post">
  			<table style="margin-left: 37%" border="1">
  			<caption>填写留言信息</caption>
  		    	<tr><td>留言标题</td>
  				<td><input type="text" name="title"/></td></tr>
  			<tr><td>留言内容</td>
  				<td><textarea name="message" rows="5" cols="35"></textarea></td>
			</tr>
  			</table>
  		<input type="submit" value="提交"/>
  		<input type="reset" value="重置"/>
  	</form>
    <a href="main.jsp">返回留言板界面</a>
    </div>
  </body>
</html>


success.jsp

 

 

<%@ page language="java" pageEncoding="gb2312"%>
<html>
<head>
    	<title>成功界面 </title>
</head>
<body>
	<div bgcolor="#ddd" style="margin-left:42%;margin-top:240px;font-family:Microsoft YaHei"">
		留言成功,单击<a href="loginServlet">这里</a>返回主界面。
	</div>
</body>
</html>

 

 

 

 

 

web.xml(配置)

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <servlet>
  	<servlet-name>loginServlet</servlet-name>
  	<servlet-class>org.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>loginServlet</servlet-name>
  	<url-pattern>/loginServlet</url-pattern>
  </servlet-mapping>
  	<servlet>
    	<servlet-name>registerServlet</servlet-name>
    	<servlet-class>org.servlet.RegisterServlet</servlet-class>
	</servlet>
	<servlet-mapping>
   	 <servlet-name>registerServlet</servlet-name>
   	 <url-pattern>/registerServlet</url-pattern>
	</servlet-mapping>
  <servlet>
    	<servlet-name>leaveMessageServlet</servlet-name>
    	<servlet-class>org.servlet.LeaveMessageServlet</servlet-class>
	</servlet>
	<servlet-mapping>
   	 <servlet-name>leaveMessageServlet</servlet-name>
   	 <url-pattern>/leaveMessageServlet</url-pattern>
	</servlet-mapping>
  <display-name>messageBoard</display-name>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
</web-app>


DBconn.java

 

 

package org.db;
import java.sql.*;

public class DBconn {
	public static Connection conn;     //Connection对象(链接)
	//连接数据库
	public static Connection getConn(){
		try{
			//加载注册SQLSever的JDBC驱动
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			//编写链接字符串,创建并且获取链接
			conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=MessageBoard","sa","19961002happy");
			return conn;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	public static void CloseConn(){
		try{
			conn.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}


LoginDao.java

 

package org.dao;
import java.sql.*;
import org.model.*;
import org.db.*;
import java.util.ArrayList;
public class LoginDao {
	Connection conn=DBconn.getConn(); ;                                      //数据库连接对象
	PreparedStatement pstmt;
	public Login checkLogin(String name,String password){ //验证用户名密码
		try{
			pstmt=conn.prepareStatement("select*from[loginss] where name=? " + " and password=?");
			pstmt.setString(1, name);                     //设置SQL语句参数
			pstmt.setString(2, password);                 //设置SQL语句参数
			ResultSet rs=pstmt.executeQuery();            //执行查询,返回结果集
			if(rs.next()){                                //通过JavaBean保存值
				Login login=new Login();
				login.setId(rs.getInt(1));
				login.setName(rs.getString(2));
				login.setPassword(rs.getString(3));
				login.setRole(rs.getInt(4));
				return login;                             //返回JavaBean对象
			}
			return null;                                  //验证失败返回null
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	public  ArrayList<MessBoar> findMbInfo(){
		try{
			ArrayList<MessBoar> al=new ArrayList<MessBoar>();
			pstmt=conn.prepareStatement("select * from [messagess]");
			ResultSet rs=pstmt.executeQuery();
			while(rs.next()){
				MessBoar mb=new MessBoar();
				mb.setId(rs.getInt(1));
				mb.setName(rs.getString(2));
				mb.setTime(rs.getDate(3));
				mb.setTitle(rs.getString(4));
				mb.setMessage(rs.getString(5));
				al.add(mb);
			}
			return al;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
		public String getName(int id){
			String name=null;
			try{
				pstmt=conn.prepareStatement("select name from [loginss] where id=?");
				pstmt.setInt(1, id);
				ResultSet rs=pstmt.executeQuery();
				while(rs.next()){
					 name=rs.getString(1);
				}
				return name;
			}catch(Exception e){
				e.printStackTrace();
				return null;
			}
		}

		public boolean addInfo(MessBoar mb){
			try{
				pstmt=conn.prepareStatement("insert into [messagess] values(?,?,?,?,?)");
				pstmt.setInt(1, mb.getId());
				pstmt.setString(2, mb.getName());
				pstmt.setDate(3, mb.getTime());
				pstmt.setString(4, mb.getTitle());
				pstmt.setString(5, mb.getMessage());
				pstmt.executeUpdate();
				return true;
			}catch(Exception e){
				e.printStackTrace();
				return false;
			}
		}
		public boolean insertUser(int id,String name,String password){
			try{
				pstmt=conn.prepareStatement("insert into [loginss] values(?,?,?,?)");
				pstmt.setInt(1, id);
				pstmt.setString(2, name);				
				pstmt.setString(3, password);
				pstmt.setInt(4, 0);
				pstmt.executeUpdate();
				return true;
			}catch(Exception e){
				e.printStackTrace();
				return false;
			}
		}


}

 

 

 


Login.java

 

 

 

 

package org.model;

public class Login {
	private Integer id;
	private String name;
	private String password;
	private int role;
	public Integer getId(){
		return this.id;
	}
	public void setId(Integer id){
		this.id=id;
	}
	public String getName(){
		return this.name;
	}
	public void setName(String name){
		this.name=name;
	}
	public String getPassword(){
		return this.password;
	}
	public void setPassword(String password){
		this.name=password;
	}
	public int getRole(){
		return this.role;
	}
	public void setRole(int role){
		this.role=role;
	}
}


message.java

 

 

package org.model;
import java.sql.*;
public class MessBoar {
	private int id;
	private String name;
	private Date time;
	private String title;
	private String message;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id=id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name=name;
	}
	public Date getTime() {
		return time;
	}
	public void setTime(Date time) {
		this.time=time;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title=title;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message=message;
	}
}


LeaveMessageServlet.java

 

 

package org.servlet;

import java.io.IOException;
import java.sql.Date;

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

import org.dao.LoginDao;
import org.model.*;

public class LeaveMessageServlet extends HttpServlet{
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
		// 设置请求编码
				request.setCharacterEncoding("gb2312");
				// 设置响应编码
				response.setContentType("gb2312");
				// 获取title内容
				String title=request.getParameter("title");
				// 获取message内容
				String message=request.getParameter("message");
				// 从session中取出当前用户对象
				Login leaveMessageBoard=(Login) request.getSession().getAttribute("login");
				// 建立留言表对应JavaBean对象,把数据封装进去
				MessBoar mb=new MessBoar();
				mb.setId(leaveMessageBoard.getId());
				// 参数为获取的当前时间
				mb.setName(leaveMessageBoard.getName());
				mb.setTime(new Date(System.currentTimeMillis()));
				mb.setTitle(title);
				mb.setMessage(message);
				// 调DB类中的方法判断是否插入成功
				if(new LoginDao().addInfo(mb)){
					response.sendRedirect("success.jsp") ;
				}
		}
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
		doGet(request,response);
	}
}


LoginServlet.java

 

package org.servlet;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.model.*;
import org.dao.*;
public class LoginServlet extends HttpServlet{
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
		request.setCharacterEncoding("gb2312");           //设置请求编码
		response.setContentType("gb2312");                //设置响应编码
		LoginDao loginDao= new LoginDao();
		HttpSession session=request.getSession();         // 先获得user对象,如果是第一次访问该Servlet,用户对象肯定为空,但如果是第
		Login l=(Login) session.getAttribute("login");    // 二次甚至是第三次,就不应该再判断该用户的信息
		if(l==null)
			l = loginDao.checkLogin(request.getParameter("name"),request.getParameter("password"));
		if(l!=null){                                      //如果登陆成功
			session.setAttribute("login",l);              //将获取的对象保存在session中
			ArrayList al=loginDao.findMbInfo();           //获取留言板的内容,返回一个数组
			session.setAttribute("al", al);               //把数组保存起来
			response.sendRedirect("main.jsp");            //验证成功跳转到 main.jsp
		}
		else{                                             //验证失败跳转到 error.jsp
			response.sendRedirect("error.jsp");
		}
		}
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
		doGet(request,response);
	}
}

 

 

 

RegisterServlet.java

 

 

 

 

package org.servlet;
import java.io.IOException;
import org.dao.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegisterServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			request.setCharacterEncoding("gb2312");
			int id=Integer.valueOf(request.getParameter("id"));
			String name=request.getParameter("name");
			String password=request.getParameter("password");
			if(new LoginDao().insertUser(id ,name, password)){
				response.sendRedirect("login.jsp");
			}
		}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request,response);
	}
}

 

  • 简单介绍

    粘代码粘得都心累,比较忙就不做太多介绍了。数据库需要自己新建,对应数据类型建立就可以了。下次有空回头复习时再加上详细介绍吧。附上几张效果图。

 

 

 

  • 效果图

 

 

 

 

好好学习,天天向上~加油~~~

//LoginServlet.java错误已修改 2016/09/02

//数据库语句添加 2016/12/24

数据库创建语句:

 

create database messageBoard
go
use messageBoard

create table loginss
(
	id int not null primary key,
	name varchar(20) not null,
	password varchar(20) not null,
	role int not null
)

create table messagess
(
	id int not null,
	name varchar(20) not null,
	time datetime not null,
	title varchar(20) not null,
	message varchar(50) not null
)

 

上面的表名称需要与LoginDao.java里面的保持一致。

 

 

进阶篇:SpringBoot搭建简单留言板项目

 

展开阅读全文

没有更多推荐了,返回首页