Servlet --简单用户留言系统
1.创建用户表和留言表
2.编写数据库连接工具类
public class SqlserverDBConn {
private Statement stmt;
private Connection conn;
public ResultSet rs; public SqlserverDBConn(){
stmt=null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databasename=TEST","sa","5loveme.");
//if(!conn.isClosed()){
// System.out.println("success!");
//}
} catch (Exception e) {
e.printStackTrace();
}
rs=null;
}
public Connection getConnection(){
//if(conn.isClosed()){
return conn;
//}
}
public ResultSet executeQuery(String sql){
try {
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs=stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
} public void closeStmt(){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
} public void closeConn(){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2.测试之
package org.test; import org.jdbc.SqlserverDBConn; public class Test {
public static void main(String[] args) {
SqlserverDBConn dbConn=new SqlserverDBConn();
}
}
3.编写数据表对应的pojo类
public class UserTable {
private Integer id;
private String username;
private String password;
public UserTable(){ }
public UserTable(Integer id, String username, String password) {
super();
this.id = id;
this.username = username;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "UserTable [id=" + id + ", username=" + username + ", password="
+ password + "]";
} }
public class LyTable {
private Integer id;
private Integer userId;
private Date date;
private String title;
private String content;
public LyTable(){ }
public LyTable(Integer id, Integer userId, Date date, String title,
String content) {
super();
this.id = id;
this.userId = userId;
this.date = date;
this.title = title;
this.content = content;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
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;
}
@Override
public String toString() {
return "LyTable [id=" + id + ", userId=" + userId + ", date=" + date
+ ", title=" + title + ", content=" + content + "]";
} }
***记得编写无参数构造函数
4.编写login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title>登录页面</title> </head> <body>
<form action="MainServlet" method="post">
<caption>用户登录</caption>
<table>
<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="重置" />
<a href="registerServlet"><input type="button" value="注册" /></a>
</form>
</body>
</html>
5.添加对应的servlet——MainServlet
public class MainServlet extends HttpServlet { /**
* Constructor of the object.
*/
public MainServlet() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { request.setCharacterEncoding("utf-8");
String username=request.getParameter("username");
String password=request.getParameter("password"); boolean validated=false; SqlserverDBConn DBConn=new SqlserverDBConn();
HttpSession session=request.getSession();
UserTable user=null; user=(UserTable)session.getAttribute("user"); if(user==null){
String sql="select * from TEST..userTable";
ResultSet rs=DBConn.executeQuery(sql);
try {
while(rs.next()){
if(rs.getString("username").equals(username)&&rs.getString("password").equals(password)){
user=new UserTable(rs.getInt(1),rs.getString(2),rs.getString(3));
//user.setId(rs.getInt(1));
//user.setUsername(rs.getString(2));
//user.setPassword(rs.getString(3));
session.setAttribute("user", user);
validated=true;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DBConn.closeStmt();
}
else{
validated=true;
} if(validated){
ArrayList al=new ArrayList(); String sql="select * from TEST..lyTable";
ResultSet rs=DBConn.executeQuery(sql);
try {
while(rs.next()){
LyTable ly=new LyTable();
ly.setId(rs.getInt(1));
ly.setUserId(rs.getInt(2));
ly.setDate(rs.getDate(3));
ly.setTitle(rs.getString(4));
ly.setContent(rs.getString(5));
al.add(ly);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
session.setAttribute("al", al);
DBConn.closeStmt();
DBConn.closeConn();
response.sendRedirect("main.jsp");
}
else{
response.sendRedirect("error.jsp");
} } /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }
6.web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>MainServlet</servlet-name>
<display-name>This is the display name of my J2EE component</display-name>
<description>This is the description of my J2EE component</description>
<servlet-class>org.servlet.MainServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<display-name>This is the display name of my J2EE component</display-name>
<description>This is the description of my J2EE component</description>
<servlet-class>org.servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MainServlet</servlet-name>
<url-pattern>/page/MainServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/page/RegisterServlet</url-pattern>
</servlet-mapping>
</web-app>
***<url-pattern>映射路径 “/”代表WEBROOT</url-pattern>
7.编写留言板界面main.jsp
<%@ page language="java" import="java.util.*,java.sql.*,org.jdbc.*,org.pojo.*" pageEncoding="utf-8"%>
<!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>
<form action="add.jsp" method="post">
<table border="1">
<caption>留言信息</caption>
<tr>
<th>留言人姓名</th>
<th>留言时间</th>
<th>留言标题</th>
<th>留言内容</th>
</tr>
<%
SqlserverDBConn DBConn=new SqlserverDBConn();
Connection conn=DBConn.getConnection();
PreparedStatement pstmt=null;
ArrayList al=(ArrayList)session.getAttribute("al");
Iterator it=al.iterator();
while(it.hasNext()){
LyTable ly=(LyTable)it.next();
String username=null;
String sql="select username from TEST..userTable where id=?";
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1, ly.getUserId());
ResultSet rs=pstmt.executeQuery();
//String username=rs.getString(1);
while(rs.next()){
username=rs.getString(1);
}
%>
<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>
8.编写添加留言页面add.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!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>
<form action="AddServlet" method="post">
<table border="1">
<caption>添加留言</caption>
<tr>
<td>留言标题</td>
<td>
<input type="text" name="title" />
</td>
</tr>
<tr>
<td>留言内容</td>
<td>
<textarea name="content" rows="10" cols="20"></textarea>
</td>
</tr>
</table>
<input type="submit" value="添加" />
<input type="reset" value="重置" />
</form>
</body>
</html>
9.编写AddServlet
public class AddServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public AddServlet() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
HttpSession session=request.getSession();
String title=request.getParameter("title");
String content=request.getParameter("content"); UserTable user=(UserTable)session.getAttribute("user");
LyTable ly=new LyTable();
ly.setUserId(user.getId());
ly.setDate(new Date(System.currentTimeMillis()));
ly.setTitle(title);
ly.setContent(content);
ArrayList al=(ArrayList)session.getAttribute("al");
al.add(ly); SqlserverDBConn DBConn=new SqlserverDBConn();
String sql="insert into TEST..lyTable (userId,date,title,content) values(?,?,?,?)";
PreparedStatement pstmt=null;
Connection conn=DBConn.getConnection();
try {
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1, ly.getUserId());
pstmt.setDate(2, ly.getDate());
pstmt.setString(3, ly.getTitle());
pstmt.setString(4, ly.getContent());
pstmt.executeUpdate();
response.sendRedirect("main.jsp");
} catch (SQLException e) {
e.printStackTrace();
response.sendRedirect("ad.jsp");
} } /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
} }
10.实现注册功能,编写注册页面
<html>
<head>
<title>注册</title>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body>
<form action="RegisterServlet" method="post">
<table>
<caption>用户注册</caption>
<tr>
<td>用户名</td>
<td>
<input type="text" name="regName" />
</td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="regPass" /></td>
</tr>
</table>
<input type="submit" value="确认" />
<input type="reset" value="重置" />
</form>
</body>
</html>
11.编写RegisterServlet
public class RegisterServlet extends HttpServlet { /**
* Constructor of the object.
*/
public RegisterServlet() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
HttpSession session=request.getSession();
String regName=request.getParameter("regName");
String regPass=request.getParameter("regPass"); SqlserverDBConn DBConn=new SqlserverDBConn();
Connection conn=DBConn.getConnection();
PreparedStatement pstmt=null;
String sql="insert into TEST..userTable (username,password) values(?,?)";
try {
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, regName);
pstmt.setString(2, regPass); pstmt.executeUpdate();
response.sendRedirect("login.jsp");
pstmt.close();
DBConn.closeConn();
} catch (SQLException e) {
e.printStackTrace();
response.sendRedirect("error.jsp");
} } public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }
Servlet --简单用户留言系统的更多相关文章
- php建立简单的用户留言系统
php建立简单的用户留言系统 样例 addMsg.php--添加留言页面 doAction.php--响应添加留言页面 . viewMsg.php--显示留言页面 目录结构 addMsg.php--添 ...
- Servlet——简单用户登录实例+http协议解析
编写项目.用户登录系统1.0版本号 登录界面Servlet: package com.gavin.view; import java.io.IOException; import java.io.Pr ...
- DBCP(MySql)+Servlet+BootStrap+Ajax实现用户登录与简单用户管理系统
目 录 简介 本次项目通过Maven编写 本文最后会附上代码 界面截图 登录界面 注册界面 登录成功进入主页 增加用户操作 删除用户操作 修改用户操作 主要代码 Dao层代码 DBCP代码 Se ...
- JavaWeb基础之Servlet简单实现用户登陆
学习javaweb遇到了一些坑,一些问题总结下来,记个笔记. 学习servlet遇到的一些坑: servlet实现用户登陆遇到的坑解决办法: https://www.cnblogs.com/swxj/ ...
- Springboot - 建立简单的用户登录系统
在开始编码前,先建立几个Package(可以按个人习惯命名),如图 1.Controllers 用于存放控制器类 2.Models 用于存放数据实体类 3.Repositories 用于存放数据库操作 ...
- SSM框架的整合与使用——实现简单的转账系统
一.整合思路 SSM框架即SpringMVC + Spring + MyBati框架集,是一种轻量级的Web开源框架.它们各自在JAVA三层架构中负责的模块如下图所示: 其中,SpringMVC与Sp ...
- 纯jsp用户登录系统
用纯jsp技术实现用户登录系统,需要用到三个.jsp文件.在文本目录下新建三个.jsp文件,分别命名为login.jsp,logincl.jsp和wel.jsp. 1.login.jsp文件用来放界面 ...
- 使用jsp/servlet简单实现文件上传与下载
使用JSP/Servlet简单实现文件上传与下载 通过学习黑马jsp教学视频,我学会了使用jsp与servlet简单地实现web的文件的上传与下载,首先感谢黑马.好了,下面来简单了解如何通过使用 ...
- Linux内核设计第三周——构造一个简单的Linux系统
Linux内核设计第三周 ——构造一个简单的Linux系统 一.知识点总结 计算机三个法宝: 存储程序计算机 函数调用堆栈 中断 操作系统两把宝剑: 中断上下文的切换 进程上下文的切换 linux内核 ...
随机推荐
- 各业务场景下的技术推荐 【.net】
后端: 1.webapi的token加密: 1)JWT验证算法,不推荐:2)RSA 2.集合的扩展:C5.dll 3.对象映射工具:AutoMapper .TinyMapper 4.任务调度框架:Q ...
- 是“帐”还是“账” --- 由 FastAdmin 用户中心引出的讨论
是"帐"还是"账" --- 由 FastAdmin 用户中心引出的讨论 有小伙伴对 FastAdmin 用户中心的"账号"提出异议,应该为& ...
- P2P Downloader
P2P Downloader , 当然就是 P2P 下载器了 , 就是和 比特精灵 差不多的那种 . ^ ^ 不过这个项目没有代码 , 懒得写代码了 , 就文字描述一下吧 . ^ ^ P2P 下 ...
- Revit api 创建族并加载到当前项目
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- wpf揭秘
2.4属性元素 以下c#和xaml是一致的 Rectangle r = new Rectangle(); r.Width = 40; r.Height = 40; r.Fill = Brushes.B ...
- Kafka 文件存储机制那些事 - 美团技术团队
出处:https://tech.meituan.com/2015/01/13/kafka-fs-design-theory.html 自己总结: Kafka 文件存储机制_结构图:https://ww ...
- create-react-app 知识点
用 create-react-app 创建项目时,最好FQ:否则有些安装包会安装不上,报超时错误. create-react-app 创建的项目,执行yarn eject后,按需引入antd的2种方式 ...
- ElasticeSearch(五)分布式索引架构
关于分布式架构 首先将ES默认每个索引是5个分片,这样做得目的是两个一个索引的时候速度更快(将数据写到小分片的尾部比写入大分片尾部更加快):另外一个是当数据量达到一定程度之后,分片查询,在汇总(sca ...
- 路由和HTTP方法
from flask import Flask app = Flask(__name__) # # 路由用法 # @app.route('/') def hello_world(): # 这种方法再不 ...
- centos7 tomcat自启动
第一步: vim /lib/systemd/system/tomcat.service [Unit] Description=tomcat After=network.target [Service] ...