javaweb+servlet+mysql登录+注册+增删改查源码
一.项目功能简介
功能流程图
源码:
百度网盘链接:https://pan.baidu.com/s/1QpbX1Sz0nZJwlvzEvx7zEw
提取码:ynzu
数据库:
链接:https://pan.baidu.com/s/1p2LIfcOeQ1EKdCDS4D29PA
提取码:mbpc
二.项目详解
1.创建javaweb项目
2.创建目录
src/com.neusoft.dao存放实体类和数据库操作的java文件
src/com.neusoft.servlet存放servlet的文件,用来接收前台发来的请求和数据,传到数据库,再返回给前台
webContent文件夹一般存放jsp、html、js等文件
web.xml存放在WEB-INF文件夹下
3.login.jsp(JSP页面用了Bootstrap http://www.bootcss.com/,联网状态加入下边标签,然后标签的class中引入Bootstrap中已有的class即可)
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<%@ 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>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body style="background:url('http://localhost:8080/webDomo2/login4.jpg') no-repeat;background-size: cover;">
<div style="width:30% ;height:376px;margin:136px 10px 10px 825px;border-radius:25px;box-shadow: 5px 5px 5px 5px #888888;background-color:">
<div style="height:70px;margin-left: 172px;margin-top:3px;float:left;">
<h1 style="font: bold em Brush Script MT ; color:#222; text-shadow: 0px 2px 3px #666;float:left;"> Login<h1/>
</div>
<form name="myform" method="post" action="LoginServlet" class="form-group"style="position:absolute;left:889px;top:216px;">
用户名: <input type="text" name="username" class="form-control" style="width:285px;"/><br/><br/>
密码:<input type="text" name="userpwd" class="form-control" style="width:285px;"/><br/><br/>
<input type="submit" class="btn btn-default" value="登录"/>
<a href="registerStudent.html">注册</a>
</form>
</div>
</body>
</html>
4.LoginServlet.java,接收login.jsp发来的请求,调用数据库文件StudentDAO.java中的doLogin()方法,查询数据返回回来后,根据查询结果跳转页面。
package com.neusoft.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.neusoft.dao.StudentDAO;
import com.neusoft.dao.StudentPO;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String username=request.getParameter("username");
String userpwd=request.getParameter("userpwd");
StudentDAO sd = new StudentDAO();
try {
StudentPO sp=sd.doLogin(username, userpwd);;
if(sp==null){
response.sendRedirect("/login.jsp");
}else{
request.setAttribute("student", sp);
if(sp.getUserPower()==1)
request.getRequestDispatcher("/main.jsp").forward(request, response);//request对象提供了一个getRequestDispatcher方法,该方法返回一个RequestDispatcher对象,调用这个对象的forward方法可以实现请求转发。
else if(sp.getUserPower()==0)
request.getRequestDispatcher("/user.jsp").forward(request, response);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
5.StudentDAO.java 存放数据库操作的java文件,由servlet调用
package com.neusoft.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class StudentDAO {
//链接数据库
public Connection getConnection(){
// 数据库连接对象
Connection conn = null;
//JDBC驱动
String driverName="com.mysql.jdbc.Driver";
// 数据库连接地址
String connectionString="jdbc:mysql://localhost:3306/test?"+"user=root&password=123456&useUnicode=true&characterEncoding=utf-8";
try{
//加载驱动
Class.forName(driverName);
//通过DriverManager类的getConenction方法指定三个参数,连接数据库
conn=DriverManager.getConnection(connectionString);
//conn.close();
}catch(ClassNotFoundException e){
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
//用户登录
public StudentPO doLogin(String username,String userpwd) throws SQLException{
//定义SQL语句
String sql="select * from test where loginname=? and loginpwd=?";
//获取连接
Connection conn = getConnection();
PreparedStatement ps = null; //向数据库中发送数据集
ResultSet rs = null; //接受返回的数据集对象-结果集
StudentPO sp = null; //将传回的行封装为列对象
try {
ps=conn.prepareStatement(sql);// 创建一个Statement对象
ps.setString(1, username); //向sql语句的问号添加数据
ps.setString(2, userpwd);
//返回结果集
rs = ps.executeQuery();
/*用Connection接口的createStatement()方法获得Statement对象传递Sql语句
* 用它的ExecuteQuery()方法获取单个ResultSet对象.
* String Sql = "select * from login";
*stt = conn.createStatement();
*set = stt.executeQuery(Sql);
*/
//获取数据,遍历结果集,将数据封装到集合中
while(rs.next()){
sp = new StudentPO();
sp.setUserName(rs.getString("loginname"));/*********/
sp.setUserPwd(rs.getString("loginpwd"));
sp.setuserPower(rs.getInt("power"));
sp.setUserId(rs.getInt("id"));
sp.setRealName(rs.getString("name"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
rs.close();
ps.close();
conn.close();
}
return sp;
}
//按id查找
public StudentPO selectbyid(int id) throws SQLException{
//定义SQL语句
String sql="select * from test where id=?";
//获取连接
Connection conn = getConnection();
PreparedStatement ps = null; //向数据库中发送数据集
ResultSet rs = null; //接受返回的数据集对象-结果集
StudentPO sp = null; //将传回的行封装为列对象
try {
ps=conn.prepareStatement(sql);// 创建一个Statement对象
ps.setInt(1, id); //向sql语句的问号添加数据
//返回结果集
rs = ps.executeQuery();
/*用Connection接口的createStatement()方法获得Statement对象传递Sql语句
* 用它的ExecuteQuery()方法获取单个ResultSet对象.
* String Sql = "select * from login";
*stt = conn.createStatement();
*set = stt.executeQuery(Sql);
*/
//获取数据,遍历结果集,将数据封装到集合中
while(rs.next()){
sp = new StudentPO();
sp.setUserName(rs.getString("loginname"));/*********/
sp.setUserPwd(rs.getString("loginpwd"));
sp.setuserPower(rs.getInt("power"));
sp.setUserId(rs.getInt("id"));
sp.setRealName(rs.getString("name"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
rs.close();
ps.close();
conn.close();
}
return sp;
}
public int executeNonQuery(String sql,Object[]args) throws SQLException{
Connection conn = getConnection();
PreparedStatement ps=null;
int result=0;
try {
ps = conn.prepareStatement(sql);
if(args!=null){
for(int i=0;i<args.length;i++){
System.err.println("2T "+args[i]);
ps.setObject(i+1, args[i]);
}
}
result=ps.executeUpdate();//返回执行成功的记录的条数 int
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
ps.close();
conn.close();
}
return result;
}
//用户注册
public int add(int id,String name,String loginpwd,int userage,String realname,int userpower) throws SQLException{
String sql="insert into test(id,loginname,loginpwd,age,name,power)"
+"values(?,?,?,?,?,?)";
Object[] args={id,name,loginpwd,userage,realname,userpower};
for(int i=0;i<5;i++)
System.err.println("1T "+args[i]);
int result=executeNonQuery(sql, args);
return result;
}
//刷新用户(在哪调用)
public int update(int id,String username,String loginpwd,int age,String name) throws SQLException{
String sql="update test set loginname=? ,loginpwd=? ,name=?,age=?"
+" where id=?";
Object[] args={username,loginpwd,name,age,id};
int result = executeNonQuery(sql, args);
return result;
}
//删除用户信息
public int delete(int id) throws SQLException{
String sql="delete from test where id="+id;
int result=executeNonQuery(sql, null);
return result;
}
//封装数据集
public List<StudentPO> queryAllStudent() throws SQLException{
String sql="select * from test";
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
List<StudentPO> list = new ArrayList<StudentPO>();
try {
ps=conn.prepareStatement(sql);
rs = ps.executeQuery();
//遍历结果集,将数据封装到集合中
while(rs.next()){
int userid=rs.getInt("id");//***********
int userage=rs.getInt("age");
int userpower=rs.getInt("power");
String username = rs.getString("loginname");
String userpwd = rs.getString("loginpwd");
String realname=rs.getString("name");
StudentPO sp = new StudentPO();
sp.setUserId(userid);
sp.setUserName(username);
sp.setRealName(realname);
sp.setUserPwd(userpwd);
sp.setUserAge(userage);
sp.setuserPower(userpower);
list.add(sp);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
rs.close();
ps.close();
conn.close();
}
return list;
}
//注册检索
public List<StudentPO> queryStudentById(int id) throws SQLException{
String sql="select * from test where id="+id;
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
List<StudentPO> list = new ArrayList<StudentPO>();
try {
ps=conn.prepareStatement(sql);
rs = ps.executeQuery();
//遍历结果集,将数据封装到集合中
while(rs.next()){
int userid=rs.getInt("id");//**************/
int userage=rs.getInt("age");
int userpower=rs.getInt("power");
String username = rs.getString("loginname");
String userpwd = rs.getString("loginpwd");
String realname=rs.getString("name");
StudentPO sp = new StudentPO();
sp.setUserId(userid);
sp.setUserName(username);
sp.setUserPwd(userpwd);
sp.setUserAge(userage);
sp.setRealName(realname);
sp.setuserPower(userpower);
list.add(sp);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
rs.close();
ps.close();
conn.close();
}
return list;
}
}
6.registerStudent.html 注册页面
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>registerStudent.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body style="background:url('http://localhost:8080/webDomo2/login4.jpg') no-repeat;background-size: cover;">
<center>
<form name="myform" method="post" action="RegisterServlet" style="margin-top:200px">
用户ID : <input type="text" name="userid"><br/>
用户姓名:<input type="text" name="username"/><br/>
真实姓名:<input type="text" name="realname"><br/>
用户密码:<input type="text" name="userpwd"><br/>
用户年龄:<input type="text" name="userage"><br/>
<input type="radio" name="power" value="0" checked>员工
<input type="radio" name="power" value="1" checked="true">管理员<br/>
<input type="submit" value="注册"/>
</form>
</center>
</body>
</html>
7.RegisterServlet.java 接收注册页面传来的请求,调用数据库的add()方法,将用户信息添加至数据库,然后跳转登录页面
package com.neusoft.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
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 com.neusoft.dao.StudentDAO;
public class RegisterServlet extends HttpServlet{
/*
* HttpServlet中有两个方法需要我们自己重写
* 需要在web.xml文件中进行注册
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.err.println("进入POST");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//1.接受客户端数据
//按照客户端调教数据的name-value的形式来提取数据
String userid=req.getParameter("userid");
String username = req.getParameter("username");
String realname=req.getParameter("realname");
String userpwd=req.getParameter("userpwd");
String userage=req.getParameter("userage");
String userpower=req.getParameter("power");
System.err.println("查到power"+userage);
int id = Integer.parseInt(userid);
int age = Integer.parseInt(userage);
int power=Integer.parseInt(userpower);
//2.使用JDBC,将数据添加到数据库中
StudentDAO sd = new StudentDAO();
//3.HttpServletResponse对象
//将HTML代码以数据流的形式响应给客户端
//客户端使用IE浏览器来解析响应的HTML数据流
//获得一个输出流对象
// PrintWriter out = resp.getWriter();
//
// out.println("<html>");
// out.println("<head>");
// out.println("<meta http-equiv='content-type' content='text/html; charset=UTF-8'>");
// out.println("</head>");
// out.println("<body>");
try {
int result=sd.add(id,username,userpwd,age,realname,power);
System.err.println(result);
if(result>0){
//1.站内跳转,请求转发
//只能转发网站内部的资源
//转发的是同一个请求和响应对象
req.getRequestDispatcher("/login.jsp").forward(req, resp);
//2.重定向跳转
//可以请求外部资源
//由于是客户端重新发起的请求,所以请求和响应对象不是同一个
//resp.sendRedirect("/webDemo/success.jsp");
//out.println("添加成功");
}else{
//out.println("添加失败");
}
} catch (SQLException e) {
//out.println("添加失败");
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
}
8.main.jsp 管理员主页面 调用QueryAllStudent.java
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="com.neusoft.dao.StudentPO"%>
<%
//java脚本
//写java的代码
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
StudentPO stu=(StudentPO)request.getAttribute("student");
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'main.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body style="background:url('http://localhost:8080/webDomo2/login4.jpg') no-repeat;background-size: cover;">
<div style="height:70px;margin-left: 458px;margin-top:261px;float:left;">
<h1 style="font: bold em Brush Script MT ; color:#222; text-shadow: 0px 2px 3px #666;float:left;"> User Management<h1/>
</div>
<a href="QueryAllStudent" style="float:left;margin-left: 15px;margin-top: 281px;">
<button type="button" class="btn btn-default btn-lg">
<span class="glyphicon glyphicon-user"></span> <%=stu.getUserName() %>
</button>
</a>
</body>
</html>
9.QueryAllStudent.java 查询出所有用户信息,跳转至用户信息列表页面
package com.neusoft.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.neusoft.dao.StudentDAO;
import com.neusoft.dao.StudentPO;
public class QueryAllStudent extends HttpServlet {
/**
* 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 {
StudentDAO sd = new StudentDAO();
try {
List<StudentPO> list=sd.queryAllStudent();
request.setAttribute("students", list);
request.getRequestDispatcher("/showStudent.jsp").forward(request, response);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
10.showStudents.jsp 用户信息页面,实现查询、更新、删除功能,分别调用各自servlet文件,分别为select.java Edit.java Delete.java
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="com.neusoft.dao.StudentPO"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
List<StudentPO> list=(List<StudentPO>)request.getAttribute("students");
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'showStudents.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body style="background:url('http://localhost:8080/webDomo2/login4.jpg') no-repeat;background-size: cover;">
<div style="width:80%;margin:10px auto">
<div style="height:70px;margin-left: 390px;margin-top: 30px;">
<h1 style="font: bold em Brush Script MT ; color:#222; text-shadow: 0px 2px 3px #666;float:left;">User Management</h1>
<img src="http://localhost:8080/webDomo2/List.png" style="width: 50px;height: 50px;float:left;margin-top: 13px;"/>
</div>
<form id="select" method="post" action="Select" style="margin-left: 631px">
<input id="selectbyname" class="form-control" type="text" name="id" placeholder="请输入用户id" style="width:200px;float:left;margin-top: 19px;"/>
<div class="col-sm-offset-2 col-sm-10 form-group" style="width:202px;margin:10px auto;float:left">
<button type="submit" class="btn btn-default btn-info" style="width:170px; margin:10px auto">查询</button>
</div>
</form>
<form method="POST" id="form">
<table align="center" class="table table-hover table-striped" style="height:70px;margin-top: 50px;filter:alpha(opacity=50,Style=0);">
<tr>
<th>用户ID</th>
<th>真实姓名</th>
<th>用户姓名</th>
<th>用户年龄</th>
<th>用户权限</th>
<th>操作</th>
</tr>
<%
for(StudentPO s :list){
%>
<tr>
<td><%=s.getUserId() %></td>
<td><%=s.getRealName() %>></td>
<td><%=s.getUserName() %></td>
<td><%=s.getUserAge() %></td>
<td><%=s.getUserPower() %></td>
<td>
<div class="btn btn-default" onclick="update('<%=s.getUserId() %>')">更新</div>
<div class="btn btn-default" onclick="deleteUser('<%=s.getUserId() %>')">删除</div>
</td>
</tr>
<%
}
%>
</table>
<input id="user_id" type="hidden" name="userid" />
</form>
</div>
</body>
<script src="https://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
var update=function(id){
$("#user_id").val(id);
$("#form").attr("action","Edit");
$("#form").submit();
};
var deleteUser=function(id){
$("#user_id").val(id);
$("#form").attr("action","Delete");
$("#form").submit();
};
</script>
</html>
11.Edit.java 跳转至编辑页面,调用Edit.jsp文件
package com.neusoft.servlet;
import java.io.IOException;
import java.sql.SQLException;
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 com.neusoft.dao.StudentDAO;
import com.neusoft.dao.StudentPO;
public class Edit extends HttpServlet {
private static final long serialVersionUID = 1L;
public Edit() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.err.println("进到servlet");
request.setCharacterEncoding("utf-8");
String id=request.getParameter("userid");
System.err.println("获取id为"+id);
int userid = Integer.parseInt(id);
StudentDAO sd = new StudentDAO();
try {
StudentPO sp=sd.selectbyid(userid);
if(sp==null){
}else{
request.setAttribute("student", sp);
request.getRequestDispatcher("/Edit.jsp").forward(request, response);//request对象提供了一个getRequestDispatcher方法,该方法返回一个RequestDispatcher对象,调用这个对象的forward方法可以实现请求转发
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
12.Edit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<title>修改用户信息页面</title>
</head>
<body style="background:url('http://localhost:8080/webDomo2/login4.jpg') no-repeat;background-size: cover;">
<div style="width:80%;margin:10px auto">
<div style="height:70px;margin-left: 390px;">
<h1 style="font: bold em Brush Script MT ; color:#222; text-shadow: 0px 2px 3px #666;float:left;">User Management<h1/>
<img src="http://localhost:8080/maven02/resources/img/List.png" style="width: 50px;height: 50px;float:left;margin-top: 13px;"/>
</div>
<form class="form-horizontal" action="Editend" method="POST">
<div class="form-group">
<label class="col-sm-2 control-label">用户名:</label>
<div class="col-sm-10 center-block">
<input type="text" class="form-control" name="username" id="inputEmail3" value="${student.getUserName()}">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">密码</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" name="password" value="${student.getUserPwd()}">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">年龄</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" name="age" value="${student.getUserAge()}">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">真实姓名:</label>
<div class="col-sm-10 center-block">
<input type="text" class="form-control" name="name" id="inputEmail3" value="${student.getRealName()}">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">确定</button>
</div>
</div>
<input id="user_id" type="hidden" name="userid" value="${student.getUserId()}" />
</form>
</div>
<!-- jQuery (Bootstrap 的 JavaScript 插件需要引入 jQuery) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- 包括所有已编译的插件 -->
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function(){
if(""=="${code}"){
console.log("没有异常");
}else if("500"=="${code}"){
alert("${msg}");
}
});
</script>
</body>
</html>
13.Editend.java 编辑页面调用Editend.java
package com.neusoft.servlet;
import java.io.IOException;
import java.sql.SQLException;
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 com.neusoft.dao.StudentDAO;
/**
* Servlet implementation class Editend
*/
public class Editend extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Editend() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
System.err.println("进入POST");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//1.接受客户端数据
//按照客户端调教数据的name-value的形式来提取数据
String userid=req.getParameter("userid");
String username = req.getParameter("username");
String realname=req.getParameter("name");
String userpwd=req.getParameter("password");
String userage=req.getParameter("age");
String userpower=req.getParameter("power");
System.err.println("查到power"+userage);
int id = Integer.parseInt(userid);
int age = Integer.parseInt(userage);
//2.使用JDBC,将数据添加到数据库中
StudentDAO sd = new StudentDAO();
//3.HttpServletResponse对象
//将HTML代码以数据流的形式响应给客户端
//客户端使用IE浏览器来解析响应的HTML数据流
//获得一个输出流对象
// PrintWriter out = resp.getWriter();
//
// out.println("<html>");
// out.println("<head>");
// out.println("<meta http-equiv='content-type' content='text/html; charset=UTF-8'>");
// out.println("</head>");
// out.println("<body>");
try {
int result=sd.update(id,username,userpwd,age,realname);
System.err.println(result);
if(result>0){
//1.站内跳转,请求转发
//只能转发网站内部的资源
//转发的是同一个请求和响应对象
req.getRequestDispatcher("/QueryAllStudent").forward(req, resp);
//2.重定向跳转
//可以请求外部资源
//由于是客户端重新发起的请求,所以请求和响应对象不是同一个
//resp.sendRedirect("/webDemo/success.jsp");
//out.println("添加成功");
}else{
//out.println("添加失败");
}
} catch (SQLException e) {
//out.println("添加失败");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
14.select.java 接收查询请求
package com.neusoft.servlet;
import java.io.IOException;
import java.sql.SQLException;
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 com.neusoft.dao.StudentDAO;
import com.neusoft.dao.StudentPO;
/**
* Servlet implementation class Select
*/
public class Select extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Select() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.err.println("进到servlet");
request.setCharacterEncoding("utf-8");
String id=request.getParameter("id");
System.err.println("获取id为"+id);
int userid = Integer.parseInt(id);
StudentDAO sd = new StudentDAO();
try {
StudentPO sp=sd.selectbyid(userid);
if(sp==null){
}else{
System.err.println("sp"+sp.getRealName());
request.getRequestDispatcher("QueryOnlyOne?userid="+sp.getUserId()).forward(request, response);//request对象提供了一个getRequestDispatcher方法,该方法返回一个RequestDispatcher对象,调用这个对象的forward方法可以实现请求转发
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
15.delete.java 接收删除请求
package com.neusoft.servlet;
import java.io.IOException;
import java.sql.SQLException;
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 com.neusoft.dao.StudentDAO;
import com.neusoft.dao.StudentPO;
/**
* Servlet implementation class delete
*/
public class Delete extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Delete() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.err.println("进到servlet");
request.setCharacterEncoding("utf-8");
String id=request.getParameter("userid");
System.err.println("获取id为"+id);
int userid = Integer.parseInt(id);
StudentDAO sd = new StudentDAO();
try {
int result=sd.delete(userid);
if(result>0){
//1.站内跳转,请求转发
//只能转发网站内部的资源
//转发的是同一个请求和响应对象
request.getRequestDispatcher("/QueryAllStudent").forward(request, response);
//2.重定向跳转
//可以请求外部资源
//由于是客户端重新发起的请求,所以请求和响应对象不是同一个
//resp.sendRedirect("/webDemo/success.jsp");
//out.println("添加成功");
}else{
//out.println("添加失败");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
16.QueryOnlyOne.java 接收普通用户的主页面的请求
package com.neusoft.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.neusoft.dao.StudentDAO;
import com.neusoft.dao.StudentPO;
public class QueryOnlyOne extends HttpServlet {
/**
* 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 {
StudentDAO sd = new StudentDAO();
StudentPO sp = new StudentPO();
String id=request.getParameter("userid");
int userid = Integer.parseInt(id);
try {
//将对象保存在请求对象中
List<StudentPO> list=sd.queryStudentById(userid);
request.setAttribute("students", list);
request.getRequestDispatcher("/showStudent.jsp").forward(request, response);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
17.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.neusoft.servlet.RegisterServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>Edit</servlet-name>
<servlet-class>com.neusoft.servlet.Edit</servlet-class>
</servlet>
<servlet>
<servlet-name>Select</servlet-name>
<servlet-class>com.neusoft.servlet.Select</servlet-class>
</servlet>
<servlet>
<servlet-name>Delete</servlet-name>
<servlet-class>com.neusoft.servlet.Delete</servlet-class>
</servlet>
<servlet>
<servlet-name>Editend</servlet-name>
<servlet-class>com.neusoft.servlet.Editend</servlet-class>
</servlet>
<servlet>
<servlet-name>QueryOnlyOne</servlet-name>
<servlet-class>com.neusoft.servlet.QueryOnlyOne</servlet-class>
</servlet>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.neusoft.servlet.LoginServlet</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>QueryAllStudent</servlet-name>
<servlet-class>com.neusoft.servlet.QueryAllStudent</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>QueryOnlyOne</servlet-name>
<url-pattern>/QueryOnlyOne</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>QueryAllStudent</servlet-name>
<url-pattern>/QueryAllStudent</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Edit</servlet-name>
<url-pattern>/Edit</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Select</servlet-name>
<url-pattern>/Select</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Delete</servlet-name>
<url-pattern>/Delete</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Editend</servlet-name>
<url-pattern>/Editend</url-pattern>
</servlet-mapping>
</web-app>
18.StudentPO.java 实体类
package com.neusoft.dao;
import java.util.List;
public class StudentPO {
private int userId;
private String userName;
private int userAge;
private String userPwd;
private String realName;
private int userPower;
public int getUserPower(){
return userPower;
}
public void setuserPower(int userpower) {
this.userPower = userpower;
}
public String getRealName(){
return realName;
}
public void setRealName(String realname) {
this.realName = realname;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userpwd) {
this.userPwd = userpwd;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserAge() {
return userAge;
}
public void setUserAge(int userAge) {
this.userAge = userAge;
}
}
完成!
三.效果图展示
1.登录界面——用户的登录注册
2.主页面——按钮跳转用户信息列表页
3.用户信息列表——实现用户信息的查询、修改、删除
4.编辑页面——编辑用户信息
5.注册页面——实现用户的增加
还没有评论,来说两句吧...