首页 > 网站 > WEB开发 > 正文

jsp+servlet+jdbc 实现crud 最简单的版本

2024-04-27 15:09:33
字体:
来源:转载
供稿:网友
史上最简单的jsp+servlet+jdbc实现CRUD项目,已经经历了千锤百炼的测试与修改,健壮性一级棒!没有任何问题。而且简明易懂,内附大量注释,是不可多得的好例子。为了保证简单,甚至没有把每个servlet里的jdbc连接单独拿出来,直观。数据库也一并给出。使用本项目时,首先访问的登录页面,即:http://localhost:8080/demo1/login.jsp,用户名root,密码root,也可以用库里面的其它用户名、密码。输入正确进入welcome页然后跳到查看学生信息页,输入错误进error.jsp,然后自动跳转回登录页。

目录结构:

先创建库。

写前端吧。

******************Jsp**********************

login.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title><style type="text/CSS">body {	background-image:url('images/yellowbg.png');	background-size: cover;  /* 图片平铺拉伸,适应屏幕 */}h1{  /* 标题居中  */	margin:100px auto;	text-align: center;}form{  /* 表单居中  */	width:300px;	height:220px;	margin: 100px auto;}.item{    /* item与itemV的设定纯粹是为了让出入框左对齐,名字右对齐    */	width:80px;	display:inline-block;	text-align: right;}.itemV{	width:180px;	display:inline-block;	text-align: right;}#btn{    /* 按钮居中  */	margin-left: 80px;}</style></head><body>	<h1>欢迎登录学生管理系统!</h1>		<form action="loginServlet" method="post">	<span class="item">用户名:</span> 	<input type="text" name="username" /></span><br><br>	<span class="item">密码:</span> 	<input type="text" name="passWord" /></span><br><br><br>	<div id="btn"> 	<input type="submit" value="登录" /> 	<input type="reset" value="重置" />	</div>	</form>	</body></html>

welcome.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title><style>body {	background-image:url('images/greenbg.png');	background-size: cover;}h1{	margin:150px auto;	text-align: center;}span{	color:red;	font-family:fantasy;}</style></head><body>	<h1>登录成功,欢迎<span><%=request.getAttribute("username") %></span>来到学生管理系统!</h1>	<center><p>5秒钟后系统会自动跳转到查看全部学生信息页面...</p></center>		<%response.setHeader("refresh","5;url=findAllServlet"); %></body></html>

error.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title><style>body {	background-image:url('images/yellowbg.png');	background-size: cover;}h1{	margin:150px auto;	text-align: center;}span{	color:red;	font-family:fantasy;}</style></head><body>	<h1>登录失败,<span><%=request.getAttribute("username") %></span>的用户名或者密码错误!</h1>	<center><p>5秒钟后系统会自动跳转到登录页面...</p></center>		<%response.setHeader("refresh","5;url=login.jsp"); %></body></html>listStudent.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><%@page import="java.util.List" %><%@page import="com.bean.Student" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title><style>body {	background-image:url('images/greenbg.png');	background-size: cover;  /* 图片平铺拉伸,适应屏幕 */}h1{	margin:50px auto;	text-align: center;}table {	width:600px;	margin:50px auto;    border-collapse: collapse;    text-align: center;}table,th,td{border:1px solid black;}th{height:50px;}a:link {color:black;}      /* 未访问链接*/a:visited {color:black;} a:hover {color:#f00;}  /* 鼠标移动到链接上 */a:active {color:#f60;}  /* 已点击 */#toAdd{ text-align: center;}</style></head><body>	<h1>欢迎来到查看学生页面</h1>	<table style="border: 1px">		<tr>			<th>ID</th>			<th>username</th>			<th>password</th>			<th>sex</th>			<th>address</th>			<th colspan="3">操作</th>		</tr>		<%  List<Student> ss = (List<Student>)request.getAttribute("ss"); 			for(Student s : ss){		%>		<tr>			<td><%=s.getId() %></td>			<td><%=s.getUsername() %></td>			<td><%=s.getPassword() %></td>			<td><%=s.getSex() %></td>			<td><%=s.getAddress() %></td>			<td colspan="3">				<a href="update.jsp?id=<%=s.getId()%>&username=<%=s.getUsername()%>&password=<%=s.getPassword()%>&sex=<%=s.getSex()%>&address=<%=s.getAddress()%>">修改</a>				  				<a href="deleteServlet?id=<%=s.getId()%>" onclick="return confirm('确定删除?')">删除</a>			</td>		</tr>		<% 			}		%>	</table>	<div id="toAdd"><a href="add.jsp">增加学生</a></div>		</body></html>add.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><%@page import="com.bean.Student" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title><style type="text/css">body {	background-image:url('images/greenbg.png');	background-size: cover;}h1{	margin:50px auto;	text-align: center;}form{	width:310px;	margin: 100px auto;}.item{	color:red;	width:100px;	display:inline-block; 	text-align:right;}.btn{	width:50px;}</style></head><body>	<h1>欢迎来到新增学生页面</h1>	<form action="addServlet" method="post">		<span class="item">ID:</span>       <span><input type="text" name="id" /></span><br>		<span class="item">username:</span> <span><input type="text" name="username" /></span><br>		<span class="item">password:</span> <span><input type="text" name="password" /></span><br>		<span class="item">sex:</span>      <span><input type="text" name="sex" /></span><br>		<span class="item">address:</span>  <span><input type="text" name="address" /></span><br>		<br><br>		<center>			<input class="btn" type="submit" value="提交" />			<input class="btn" type="reset" value="重置" />		</center>	</form></body></html>update.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><%@page import="com.bean.Student" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title><style type="text/css">body {	background-image:url('images/greenbg.png');	background-size: cover;}h1{	margin:50px auto;	text-align: center;}form{	width:310px;	margin: 100px auto;}.item{	color:red;	width:100px;	display:inline-block; 	text-align:right;}.btn{	width:50px;}</style></head><body>	<%		String id = request.getParameter("id");		String username = request.getParameter("username");		String password = request.getParameter("password");		String sex = request.getParameter("sex");		String address = request.getParameter("address");	%>		<!-- id是唯一定位元素的标识符,不能修改,但可以显示给人看,此时不要用disabled限制别人访问,因为		 它会使id的name连同value都作废,不能提交给servlet;用read-only,它可以提交。	 -->	<h1>欢迎来到修改学生信息页面</h1>	<form action="updateServlet" method="post">		<span class="item">ID:</span>       <span><input type="text" name="id" value="<%=id %>" readonly="readonly"/></span><br>		<span class="item">username:</span> <span><input type="text" name="username" value="<%=username %>" /></span><br>		<span class="item">password:</span> <span><input type="text" name="password" value="<%=password %>" /></span><br>		<span class="item">sex:</span>      <span><input type="text" name="sex" value="<%=sex %>" /></span><br>		<span class="item">address:</span>  <span><input type="text" name="address" value="<%=address %>" /></span><br>		<br><br>		<center>			<input class="btn" type="submit" value="提交" />			<input class="btn" type="reset" value="重置" />		</center>	</form></body></html>

******************web.xml**********************

web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" 	xmlns="http://java.sun.com/xml/ns/javaee" 	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">      <welcome-file-list>    <welcome-file>login.jsp</welcome-file>  </welcome-file-list>      <servlet>  	<servlet-name>UpdateServlet</servlet-name>  	<servlet-class>com.servlet.UpdateServlet</servlet-class>  </servlet>  <servlet-mapping>  	<servlet-name>UpdateServlet</servlet-name>  	<url-pattern>/updateServlet</url-pattern>  </servlet-mapping>      <servlet>  	<servlet-name>FindAllServlet</servlet-name>  	<servlet-class>com.servlet.FindAllServlet</servlet-class>  </servlet>  <servlet-mapping>  	<servlet-name>FindAllServlet</servlet-name>  	<url-pattern>/findAllServlet</url-pattern>  </servlet-mapping>      <servlet>    <servlet-name>LoginServlet</servlet-name>    <servlet-class>com.servlet.LoginServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>LoginServlet</servlet-name>    <url-pattern>/loginServlet</url-pattern>  </servlet-mapping>    	  <servlet>    <servlet-name>ListServlet</servlet-name>    <servlet-class>com.servlet.ListServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>ListServlet</servlet-name>    <url-pattern>/listServlet</url-pattern>  </servlet-mapping>	      <servlet>  	<servlet-name>DeleteServlet</servlet-name>  	<servlet-class>com.servlet.DeleteServlet</servlet-class>  </servlet>  <servlet-mapping>  	<servlet-name>DeleteServlet</servlet-name>  	<url-pattern>/deleteServlet</url-pattern>  </servlet-mapping>      <servlet>  	<servlet-name>AddServlet</servlet-name>  	<servlet-class>com.servlet.AddServlet</servlet-class>  </servlet>  <servlet-mapping>  	<servlet-name>AddServlet</servlet-name>  	<url-pattern>/addServlet</url-pattern>  </servlet-mapping>  </web-app>

******************Bean类**********************

Student.java

package com.bean;public class Student {	PRivate int id;	private String username;	private String password;	private int sex;	private String address;	public int getId() {		return id;	}	public void setId(int 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;	}	public int getSex() {		return sex;	}	public void setSex(int sex) {		this.sex = sex;	}	public String getAddress() {		return address;	}	public void setAddress(String address) {		this.address = address;	}}

******************Servlet类**********************

LoginServlet.java

package com.servlet;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoginServlet extends HttpServlet {		 protected void doGet(HttpServletRequest request,              HttpServletResponse response) throws ServletException, IOException {  		//第一步,先把字符集设定成utf-8,否则万一浏览器送来的是中文就会出现乱码		request.setCharacterEncoding("utf-8");		 		//先把浏览器输入的用户名、密码拿出来。         String un = request.getParameter("username");        String pw = request.getParameter("password");                //把用户名设置到request的属性里,这样得会儿跳转到欢迎或者错误页面时好知道叫什么        request.setAttribute("username", un);                //此时开始在数据库中搜寻有没有同时满足用户名、密码的行,有就对,没有就错:        //先加载lib目录下的java-connect-MySQL.jar驱动包		try {			Class.forName("com.mysql.jdbc.Driver");						//选择驱动类,连接地址、账号密码,连接MySQL			String driverClass="com.mysql.jdbc.Driver";			String url="jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8";			String sqlusername="root";			String sqlpassword="root";			Connection conn = DriverManager.getConnection(url, sqlusername,  			        sqlpassword);						//编写SQL语句,这里不要用statement了,换用preparedstatement,因为			//preparedstatement可以设置?为形参,然后set各个形参的实际值,statement没有此			//功能。最后执行更新语句。			//此外,?不要加单双引号,否则报错java.sql.SQLException: Parameter index out of range (0 < 1 ).			String sql = "select * from student where username = ? and password = ?";  			PreparedStatement ps = conn.prepareStatement(sql);  	        ps.setString(1, un);	        ps.setString(2, pw);	        ResultSet rs=ps.executeQuery();	        	        if(rs.next()){	        	request.getRequestDispatcher("welcome.jsp").forward(request, response);	        }else{	        	request.getRequestDispatcher("error.jsp").forward(request, response);	        }	        		} catch (ClassNotFoundException | SQLException e) {			e.printStackTrace();		}      }        protected void doPost(HttpServletRequest request,              HttpServletResponse response) throws ServletException, IOException {          doGet(request, response);      }  }

FindAllServlet.java

package com.servlet;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;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.bean.Student;public class FindAllServlet extends HttpServlet{		//重写doGet方法	protected void doGet(HttpServletRequest request,          HttpServletResponse response) throws ServletException, IOException {  				try {			//先加载lib目录下的java-connect-mysql.jar驱动包			Class.forName("com.mysql.jdbc.Driver");  						//选择驱动类,连接地址、账号密码,连接MySQL			String driverClass="com.mysql.jdbc.Driver";			String url="jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8";			String sqlusername="root";			String sqlpassword="root";			Connection conn = DriverManager.getConnection(url, sqlusername,  			        sqlpassword);									//编写SQL语句,执行,拿到结果集			String sql = "select * from student";  			Statement statement = conn.createStatement();            ResultSet resultSet = statement.executeQuery(sql);                        //把结果集的东西倒进ArrayList            List<Student> ss = new ArrayList<Student>();            while(resultSet.next()){            	Student s = new Student();				s.setId(resultSet.getInt("id"));				s.setUsername(resultSet.getString("username"));				s.setPassword(resultSet.getString("password"));				s.setSex(resultSet.getInt("sex"));				s.setAddress(resultSet.getString("address"));								//后台打印,试看有没有拿到				/*String ms = resultSet.getInt("id")+resultSet.getString("username");				System.out.println(ms);*/								ss.add(s);            }                        //ArrayList放进request的属性里,这样jsp页面就能request.getAttribute("ss")            //拿出ArrayList了。            request.setAttribute("ss", ss);              resultSet.close();            statement.close();					} catch (SQLException | ClassNotFoundException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}						//跳转到显示页面		request.getRequestDispatcher("listStudent.jsp")      	.forward(request, response);     }        protected void doPost(HttpServletRequest request,              HttpServletResponse response) throws ServletException, IOException {          doGet(request, response);      }  }

AddServlet.java

package com.servlet;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;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.bean.Student;public class AddServlet extends HttpServlet{		//重写doGet方法	protected void doGet(HttpServletRequest request,          HttpServletResponse response) throws ServletException, IOException {  		request.setCharacterEncoding("utf-8");				//从jsp页面获取要添加的新对象的各项值		int id = Integer.valueOf(request.getParameter("id"));		String username = request.getParameter("username");		String password = request.getParameter("password");		int sex = Integer.valueOf(request.getParameter("sex"));		String address = request.getParameter("address");						try {			//先加载lib目录下的java-connect-mysql.jar驱动包			Class.forName("com.mysql.jdbc.Driver");  						//选择驱动类,连接地址、账号密码,连接MySQL			String driverClass="com.mysql.jdbc.Driver";			String url="jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8";			String sqlusername="root";			String sqlpassword="root";			Connection conn = DriverManager.getConnection(url, sqlusername,  			        sqlpassword);						//编写SQL语句,这里不要用statement了,换用preparedstatement,因为			//preparedstatement可以设置?为形参,然后set各个形参的实际值,statement没有此			//功能。最后执行更新语句。			//此外,?不要加单双引号,否则报错java.sql.SQLException: Parameter index out of range (0 < 1 ).			String sql = "insert into student values("+id+",'"+username+"','"+password+"',"+sex+",'"+address+"')";  			PreparedStatement ps = conn.prepareStatement(sql);              ps.executeUpdate();                        //关闭连接            ps.close();              conn.close();  					} catch (SQLException | ClassNotFoundException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}						//跳转到显示页面		response.sendRedirect("findAllServlet");		/*request.getRequestDispatcher("listStudent.jsp")      	.forward(request, response); */    }        protected void doPost(HttpServletRequest request,              HttpServletResponse response) throws ServletException, IOException {          doGet(request, response);      }  }

DeleteServlet.java

package com.servlet;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;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.bean.Student;/** * 写DeleteServlet时遇到极大的困难,代码都对,前台jsp里<a href="deleteServlet?id=<%=s.getId()%>">删除</a> * 对,后台接收id的值,然后删除也对,但是就是进不来servlet,前台提示找不到404。后来关了服务器、清理、重启、前台改了若干数据、删除,问题好了。 * 可能是服务器没有重启的原因,也有可能是前台的缓存造成的找不到,仅仅刷新是不够的,缓存没有变,必须跳转页面,才有新缓存。 * @author Administrator * */public class DeleteServlet extends HttpServlet{		//重写doGet方法	protected void doGet(HttpServletRequest request,          HttpServletResponse response) throws ServletException, IOException {  				//从jsp页面获取要修改的元素的id和各项修改后的值		int id = Integer.valueOf(request.getParameter("id"));				try {			//先加载lib目录下的java-connect-mysql.jar驱动包			Class.forName("com.mysql.jdbc.Driver");  						//选择驱动类,连接地址、账号密码,连接MySQL			String driverClass="com.mysql.jdbc.Driver";			String url="jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8";			String sqlusername="root";			String sqlpassword="root";			Connection conn = DriverManager.getConnection(url, sqlusername,  			        sqlpassword);						//编写SQL语句,这里不要用statement了,换用preparedstatement,因为			//preparedstatement可以设置?为形参,然后set各个形参的实际值,statement没有此			//功能。最后执行更新语句。			//此外,?不要加单双引号,否则报错java.sql.SQLException: Parameter index out of range (0 < 1 ).			String sql = "delete from student where id = ?";  			PreparedStatement ps = conn.prepareStatement(sql);              ps.setInt(1, id);            ps.executeUpdate();                        //关闭连接            ps.close();              conn.close();  					} catch (SQLException | ClassNotFoundException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}						//跳转到显示页面		response.sendRedirect("findAllServlet");		/*request.getRequestDispatcher("listStudent.jsp")      	.forward(request, response); */    }        protected void doPost(HttpServletRequest request,              HttpServletResponse response) throws ServletException, IOException {          doGet(request, response);      }  }

UpdateServlet.java

package com.servlet;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;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.bean.Student;public class UpdateServlet extends HttpServlet{		//重写doGet方法	protected void doGet(HttpServletRequest request,          HttpServletResponse response) throws ServletException, IOException {  				request.setCharacterEncoding("utf-8");				//从jsp页面获取要修改的元素的id和各项修改后的值		int id = Integer.valueOf(request.getParameter("id"));		String username = request.getParameter("username");		String password = request.getParameter("password");		int sex = Integer.valueOf(request.getParameter("sex"));		String address = request.getParameter("address");				try {			//先加载lib目录下的java-connect-mysql.jar驱动包			Class.forName("com.mysql.jdbc.Driver");  						//选择驱动类,连接地址、账号密码,连接MySQL			String driverClass="com.mysql.jdbc.Driver";			String url="jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8";			String sqlusername="root";			String sqlpassword="root";			Connection conn = DriverManager.getConnection(url, sqlusername,  			        sqlpassword);						//编写SQL语句,这里不要用statement了,换用preparedstatement,因为			//preparedstatement可以设置?为形参,然后set各个形参的实际值,statement没有此			//功能。最后执行更新语句。			//此外,?不要加单双引号,否则报错java.sql.SQLException: Parameter index out of range (0 < 1 ).			String sql = "update student set username = ?, password = ?, sex = ?, address = ? where id = ?";  			PreparedStatement ps = conn.prepareStatement(sql);              ps.setString(1, username);            ps.setString(2, password);            ps.setInt(3, sex);            ps.setString(4, address);            ps.setInt(5, id);            ps.executeUpdate();                        //关闭连接            ps.close();              conn.close();  					} catch (SQLException | ClassNotFoundException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}						//跳转到显示页面		response.sendRedirect("findAllServlet");		/*request.getRequestDispatcher("listStudent.jsp")      	.forward(request, response); */    }        protected void doPost(HttpServletRequest request,              HttpServletResponse response) throws ServletException, IOException {          doGet(request, response);      }  }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表