断断续续大概做了一周左右 也算是把 留言板开发这一块吃透了
今天写一篇博客 记录学习过程
先写 jsp 再写jsp对应的servlet 类 我觉得可以更直接的感受到model2 使用servlet 接收数据并处理 然后再传给Jsp 显示的工作原理
<%-- login类--%>
<%--
Created by IntelliJ IDEA.
User: FX50J
Date: 2018/1/22
Time: 14:30
To change this template use File | Settings | File Templates.
--%>
<%-- 设定编码方法 在解码的时候 如果不解码 会报乱码 --%>
<%@ page contentType="text/html;charset=gb2312" language="java" %>
<html>
<head>
<title>登陆页面</title>
</head>
<body>
<form action="mainServlet" method="post">
<%-- action决定 该表收集到信息传到那个servlet类去 这里的mainServlet是只在xml文件配置中 定义的MainServlet类 --%>
<table>
<caption>用户登录</caption>
<tr>
<td>用户名 :</td>
<td>
<input type="text" name="username" size="20"/>
</td>
</tr>
<tr>
<td>密码 :</td>
<td>
<input type="password" name="password" size="21"/>
</td>
</tr>
</table>
<input type="submit" value="登录"/>
<input type="reset" value="重置"/>
</form>
如果没有注册点击<a href="register.jsp">这里</a>注册!
</body>
</html>
// MainServlet类 用来处理 login.jsp收集到的信息 并返回相应的jsp页面
package org.easybooks.test.servlet;
import javax.servlet.http.HttpServlet;
import java.sql.*;
import java.io.*;
import java.util.ArrayList;
import javax.servlet.*;
import javax.servlet.http.*;
import org.easybooks.test.jdbc.SqlSrvDBConn;
import org.easybooks.test.model.vo.*;
public class MainServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
request.setCharacterEncoding("gb2312");
String username = request.getParameter("username");
String pwd = request.getParameter("password");
boolean validated = false;
SqlSrvDBConn sqlSrvDBConn = new SqlSrvDBConn();
HttpSession session = request.getSession();
UserTable userTable = null;
userTable = (UserTable)session.getAttribute("userTable");
if(userTable==null){
String sql = "select * from usertable";
ResultSet rs = sqlSrvDBConn.executeQuery(sql);
try{
while(rs.next()){
if(rs.getString("username").trim().compareTo(username)==0 && rs.getString("password").trim().compareTo(pwd)==0){
userTable = new UserTable();
userTable.setUsername(rs.getString("username"));
userTable.setPassword(rs.getString("password"));
userTable.setId(rs.getInt("id"));
session.setAttribute("userTable",userTable);
validated = true;
}
}
rs.close();
}catch(SQLException e){
e.printStackTrace();
}
sqlSrvDBConn.closeStmt();
}
else{
validated = true;
}
if(validated==true){
ArrayList al = new ArrayList();
String sql = "select * from lyTable";
ResultSet rs = sqlSrvDBConn.executeQuery(sql);
try{
//从数据库lyTable中获取留言信息
while(rs.next()){
lyTable ly = new lyTable();
ly.setId(rs.getInt("id"));
ly.setUserId(rs.getInt("userId"));
ly.setDate(rs.getDate("date"));
ly.setTitle(rs.getString("title"));
ly.setContent(rs.getString("content"));
al.add(ly);
}
rs.close();
}catch (SQLException e){
e.printStackTrace();
}
sqlSrvDBConn.closeStmt();
//留言存入会话
session.setAttribute("al",al);
response.sendRedirect("main.jsp");
}
else{
//登录失败
response.sendRedirect("error.jsp");
}
sqlSrvDBConn.closeConn();
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
doGet(request,response);
}
// public void doPost(HttpServletRequest request,HttpServletResponse response)
// throws ServletException,IOException{
// doGet(request,response);
// }
}
<%--
留言版页面 从mysql 中提取出相应的评论
--%>
<%@ page import="java.sql.*,java.util.*" %>
<%@ page import="org.easybooks.test.jdbc.SqlSrvDBConn" %>
<%@ page import="org.easybooks.test.model.vo.lyTable" %><%--
Created by IntelliJ IDEA.
User: FX50J
Date: 2018/1/22
Time: 14:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=gb2312" language="java" %>
<html>
<head>
<title>留言版</title>
</head>
<body>
<form action="liuyan.jsp" method="post">
<table border="1">
<caption>所有留言信息</caption>
<tr>
<th>留言人姓名</th><th>留言时间</th><th>留言标题</th><th>留言内容</th>
</tr>
<%
PreparedStatement pstmt = null;
SqlSrvDBConn sqlSrvDBConn = new SqlSrvDBConn();
Connection conn = sqlSrvDBConn.getConn();
<%--
从保留下来的会话中 提取之前放进去的 al 属性
使用的是 JSP 写法
--%>
ArrayList al = (ArrayList) session.getAttribute("al");
Iterator iter = al.iterator();
while(iter.hasNext()){
lyTable ly = (lyTable)iter.next();
String username = null;
try{
pstmt = conn.prepareStatement("select username from userTable where id = ?");
pstmt.setInt(1,ly.getUserId());
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
username = rs.getString("username");
}
}catch(SQLException e){
e.printStackTrace();
}
%>
<tr>
<td><%=username%></td>
<td><%=ly.getDate()%></td>
<td><%=ly.getTitle()%></td>
<td><%=ly.getContent()%></td>
</tr>
<%
}
%>
</table>
<input type = "submit" value="留言"/>
</form>
</body>
</html>
<%--
发布留言页面 将收集到的信息 传入AddServlet类中的addServlet属性
--%>
<%@ page contentType="text/html;charset=gb2312" language="java" %>
<html>
<head>
<title>留言板</title>
</head>
<body>
<form action="addServlet" method="post">
<table border="1">
<caption>填写留言信息</caption>
<tr>
<td>留言标题</td>
<td><input type="text" name="title" size="20"/></td>
</tr>
<tr>
<td>留言内容</td>
<td><textarea name="content" rows="5" cols="35"></textarea></td>
</tr>
</table>
<input type="submit" value="提交"/>
<intpt type="reset" value="重置"/>
</form>
</body>
</html>
// AddServlet类 用来 处理liuyan.jsp传递来的信息
package org.easybooks.test.servlet;
import org.easybooks.test.jdbc.SqlSrvDBConn;
import org.easybooks.test.model.vo.UserTable;
import org.easybooks.test.model.vo.lyTable;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Date;
public class AddServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
//设置编码 否则会出现乱码
request.setCharacterEncoding("gb2312");
//获取liuyan.jsp所发送的信息
String title = request.getParameter("title");
String content = request.getParameter("content");
//获得session对象
HttpSession session = request.getSession();
UserTable userTable = (UserTable) session.getAttribute("userTable");
//建立lyTable信息
Integer userId = userTable.getId();
lyTable ly = new lyTable();
ly.setUserId(userId);
ly.setDate( new java.sql.Date(new java.util.Date().getTime()));
if(title!=null)System.out.println(title);
ly.setTitle(title);
ly.setContent(content);
//新添加的留言要保存一份到会话中 这种刷新主页时就无须每次都去查询数据库留言表了
ArrayList al = (ArrayList)session.getAttribute("al");
al.add(ly);
//没有放回去 也能 在main.jsp上看到
// session.setAttribute("al",al);
PreparedStatement pstmt = null;
SqlSrvDBConn sqlSrvDBConn = new SqlSrvDBConn();
Connection conn = sqlSrvDBConn.getConn();
try{
pstmt = conn.prepareStatement("insert into lytable values(?,?,?,?,?)");
pstmt.setInt(1,1);
pstmt.setInt(2,ly.getUserId());
pstmt.setDate(3,ly.getDate());
pstmt.setString(4,ly.getTitle());
pstmt.setString(5,ly.getContent());
pstmt.executeUpdate();
response.sendRedirect("main.jsp");
}catch(SQLException e){
e.printStackTrace();
response.sendRedirect("liuyan.jsp");
System.out.println("error");
}
sqlSrvDBConn.closeConn();
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
doGet(request,response);
}
}
<%--
register.jsp 用来处理 注册 信息
--%>
<%@ page contentType="text/html;charset=gb2312" language="java" %>
<html>
<head>
<title>注册用户</title>
</head>
<body>
<form action="registerServlet" method="post">
<%--
将输入的数据 传递到RegisterServlet类的registerServlet
--%>
<table>
<caption>用户注册:</caption>
<tr>
<td>登录名:</td>
<td>
<input type="text" name="username" size="20"/>
</td>
</tr>
<tr>
<td>密码:</td>
<td>
<input type="password" name="password" size="20"/>
</td>
</tr>
</table>
<input type="submit" value="注册"/>
<input type="reset" value="重置"/>
</form>
</body>
</html>
//用来处理 register.jsp传递来的数据 向数据库 中插入信息
package org.easybooks.test.servlet;
import org.easybooks.test.jdbc.SqlSrvDBConn;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
public class RegisterServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response )
throws ServletException,IOException{
request.setCharacterEncoding("gb2312");
String username=request.getParameter("username");
String password=request.getParameter("password");
SqlSrvDBConn sqlSrvDBConn = new SqlSrvDBConn();
Connection conn = sqlSrvDBConn.getConn();
PreparedStatement pstmt = null;
try{
pstmt = conn.prepareStatement("insert into usertable(username,password) values (?,?)");
pstmt.setString(1,username);
pstmt.setString(2,password);
pstmt.executeUpdate();
response.sendRedirect("login.jsp");
}catch (SQLException e){
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
doGet(request,response);
}
}
<%--
当在login.jsp输入密码错误时(在数据库中没有找到相符合的数据项)返回的页面
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
</body>
</html>
//处理 留言插入数据库的类
package org.easybooks.test.model.vo;
import java.io.Serializable;
import java.sql.Date;
public class lyTable implements Serializable{
//属性
private Integer id;
private Integer userId;
private java.sql.Date date;
private String title;
private String content;
public Integer getId(){
return this.id;
}
public void setId(Integer id){
this.id = id;
}
public Integer getUserId(){
return this.userId;
}
public void setUserId(Integer userId){
this.userId = userId;
}
public Date getDate(){
return date;
}
public void setDate(Date date){
this.date = date;
}
public void setTitle(String titlt){
this.title = title;
}
public String getTitle(){
return title;
}
public void setContent(String content){
this.content = content;
}
public String getContent(){
return content;
}
}
//用来处理 会话中存储的登陆信息对象
package org.easybooks.test.model.vo;
public class UserTable {
private Integer id;
private String username;
private String password;
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
//基础数据库操作类
package org.easybooks.test.jdbc;
import java.sql.*;
public class SqlSrvDBConn {
private Statement stmt;
private Connection conn;
private ResultSet rs;
public SqlSrvDBConn(){
stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e){
e.printStackTrace();
}
try{
String uri = "jdbc:mysql://localhost:3306/test?useSSL=true";
String user = "host";
String password = "HanDong85";
conn = DriverManager.getConnection(uri,user,password);
}catch(Exception e){
e.printStackTrace();
}
}
public ResultSet executeQuery(String sql){
try{
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
}catch (SQLException e){
e.printStackTrace();
}
return rs;
}
public Connection getConn(){
return conn;
}
public void closeStmt(){
try{
stmt.close();
}catch(SQLException e){
e.printStackTrace();
}
}
public void closeConn(){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
//将 AddServlet MainServlet RegisterServlet类创建变量并配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>mainServlet</servlet-name>
<servlet-class>org.easybooks.test.servlet.MainServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mainServlet</servlet-name>
<url-pattern>/mainServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>addServlet</servlet-name>
<servlet-class>org.easybooks.test.servlet.AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>addServlet</servlet-name>
<url-pattern>/addServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>registerServlet</servlet-name>
<servlet-class>org.easybooks.test.servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>registerServlet</servlet-name>
<url-pattern>/registerServlet</url-pattern>
</servlet-mapping>
</web-app>
项目总体结构图
感受: 陆陆续续做了几天 碰上了不少bug 有些是因为自己想当然的错误 也有些是因为对数据库和JSP的不熟悉导致的 我也把这些bug与解决的思路方法 一块了发了出来 希望 以后如果其他人碰到了与我相同或者类似的错误时 能够很快解决