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即可)
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'login.jsp' starting page
Login
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 queryAllStudent() throws SQLException{
String sql="select * from test";
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
List list = new ArrayList();
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 queryStudentById(int id) throws SQLException{
String sql="select * from test where id="+id;
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
List list = new ArrayList();
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 注册页面
registerStudent.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("");
// out.println("");
// out.println("");
// out.println("");
// out.println("");
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");
%>
My JSP 'main.jsp' starting page
User Management
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.
*
* 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 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 list=(List)request.getAttribute("students");
%>
My JSP 'showStudents.jsp' starting page
User Management
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"%>
修改用户信息页面
User Management
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("");
// out.println("");
// out.println("");
// out.println("");
// out.println("");
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.
*
* 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 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
index.jsp
RegisterServlet
com.neusoft.servlet.RegisterServlet
Edit
com.neusoft.servlet.Edit
Select
com.neusoft.servlet.Select
Delete
com.neusoft.servlet.Delete
Editend
com.neusoft.servlet.Editend
QueryOnlyOne
com.neusoft.servlet.QueryOnlyOne
LoginServlet
com.neusoft.servlet.LoginServlet
This is the description of my J2EE component
This is the display name of my J2EE component
QueryAllStudent
com.neusoft.servlet.QueryAllStudent
QueryOnlyOne
/QueryOnlyOne
RegisterServlet
/RegisterServlet
LoginServlet
/LoginServlet
QueryAllStudent
/QueryAllStudent
Edit
/Edit
Select
/Select
Delete
/Delete
Editend
/Editend
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.注册页面——实现用户的增加