(MVC)javaBaen+jsp+servlet对数据的操作

时间:2022-11-13 15:01:19

运用MVC对数据进行一些简单的处理,基本实现数据的增删改查,达到前端和后台的数据之间的交互。

1.开始界面

 <%@page import="com.zdsofe.work.Student"%>
<%@page import="java.util.List"%>
<%@page import="com.zdsofe.work.ReadData"%>
<%@ 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>
<script type="text/javascript" src="../js/jquery-1.7.2.js"></script>
<script type="text/javascript">
function fun1() {
$(":checkbox").attr("checked","checked");
} function fun2() {
$(":checkbox").attr("checked",false);
} </script>
</head>
<body>
<% ReadData rd=new ReadData();
List<Student> list= rd.findInfo(); %>
<form action="../MoreDeleteServlet" >
<table border="1">
<tr> <td colspan="4"><button type="button" onclick="fun1()">全选</button>
<button type="button" onclick="fun2()">全不选</button></td></tr>
<tr>
<th>序号</th>
<th>名字</th>
<th>密码</th>
<th>操作</th>
</tr> <%
for(int i=0;i<list.size();i++)
{
%>
<tr>
<td><%=list.get(i).getId()%></td>
<td><%=list.get(i).getUserName()%></td>
<td><%=list.get(i).getMima()%></td>
<td>
<input type="checkbox" name="c" value="<%=list.get(i).getId()%>"/>
<a href="../servlet?userI=<%=list.get(i).getId()%>">修改</a>
<a href="../DeleteServlet?userI=<%=list.get(i).getId()%>">删除</a>
</td>
</tr>
<%
} %>
<tr>
<td colspan="4"><a href="addData.jsp" style="text-decoration: none;">增加</a>
<button type="submit">批量删除</button>
</td>
</tr>
</table>
</form>
<form action="../DimServlet">
<select name="se">
<option value="id">序号</option>
<option value="name">姓名</option>
</select>
<input type="text" name="in"/>
<button type="submit">模糊查询</button>
</form>
</body> </html>

2.增加数据的界面

 <%@ 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>
</head>
<body>
<form action="../AddServlet" method="post"> 用户名:<input type="text" name="userName" ><br/>
密码:<input type="password" name="mima" ><br/>
ID:<input type="text" name="id" />
<button type="submit">提交</button> </form>
</body>
</html>

3.修改数据的界面

 <%@page import="com.zdsofe.work.Student"%>
<%@ 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>
</head> <%
//获取用户信息
Student stu=(Student)session.getAttribute("user");
%>
<body> <form action="../EditServlet" method="post"> 用户名:<input type="text" name="userName" value="<%=stu.getUserName()%>"><br/>
密码:<input type="password" name="mima" value="<%=stu.getMima()%>"><br/>
ID:<input type="text" name="id" value="<%=stu.getId()%>"/>
<button type="submit">提交</button> </form> </body>
</html>

4.模糊查询后的界面

 <%@page import="com.zdsofe.work.Student"%>
<%@page import="java.util.List"%>
<%@page import="com.zdsofe.work.ReadData"%>
<%@ 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>
</head>
<% ReadData rd=new ReadData();
String se=session.getAttribute("se").toString();
String in=session.getAttribute("in").toString();
List<Student> list= rd.findDim(se,in); %>
<body>
<table border="1">
<tr>
<th>序号</th>
<th>名字</th>
<th>密码</th>
<th>操作</th>
</tr> <%
for(int i=0;i<list.size();i++)
{
%>
<tr>
<td><%=list.get(i).getId()%></td>
<td><%=list.get(i).getUserName()%></td>
<td><%=list.get(i).getMima()%></td> <td>
<a href="../servlet?userI=<%=list.get(i).getId()%>">修改</a>
<a href="../DeleteServlet?userI=<%=list.get(i).getId()%>">删除</a>
</td>
</tr> <%
} %>
<tr>
<td colspan="4"><a href="addData.jsp">增加</a> </td>
</tr>
</table>
</body>
</html>

5.连接数据库的工具类

 package com.zdsofe.util;

 import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException; public class DBUtil {
private static String DRIVER="com.mysql.jdbc.Driver";
private static String URL="jdbc:mysql://localhost:3306/mysql";
private static String user="root";
private static String key="775297";
public static Connection conn; //加载驱动
static{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//连接数据库
public static Connection getConnection(){
try {
conn = DriverManager.getConnection(URL, user, key);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}

6.实体类

 package com.zdsofe.work;

 public class Student {
public String id;
public String userName;
public String mima; public Student(String id, String userName, String mima) {
super();
this.id = id;
this.userName = userName;
this.mima = mima;
} public Student(String userName, String mima) { this.userName = userName;
this.mima = mima;
} public Student() {
super();
} public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getMima() {
return mima;
}
public void setMima(String mima) {
this.mima = mima;
} }

7.一些实现功能的静态方法

 package com.zdsofe.work;

 import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List; import com.zdsofe.util.DBUtil; public class ReadData { //查询信息
public static List<Student> findInfo() {
List <Student>list=new ArrayList<>();
//调用连接并创建SQL语句
try {
Statement stam= DBUtil.getConnection().createStatement();
String sql="SELECT id,userName,mima FROM denglu;";
ResultSet rs=stam.executeQuery(sql); while(rs.next())
{
String id=rs.getString("id");
String userName=rs.getString("userName");
String mima=rs.getString("mima");
Student stu=new Student(id,userName,mima);
list.add(stu);
} } catch (SQLException e) {
e.printStackTrace();
} return list;
} //模糊查询
public static List<Student> findDim(String se,String in ) {
List <Student>list=new ArrayList<>(); if(se.equals("id"))
{ //调用连接并创建SQL语句
try {
Statement stam= DBUtil.getConnection().createStatement();
String sql="select * from denglu where id like '%"+in+"%'";
ResultSet rs=stam.executeQuery(sql);
while(rs.next())
{
String id=rs.getString("id");
String userName=rs.getString("userName");
String mima=rs.getString("mima");
Student stu=new Student(id,userName,mima);
list.add(stu);
} } catch (SQLException e) {
e.printStackTrace();
}
}
if(se.equals("name"))
{
try {
Statement stam= DBUtil.getConnection().createStatement();
String sql="select * from denglu where userName like '%"+in+"%'"; ResultSet rs=stam.executeQuery(sql); while(rs.next())
{
String id=rs.getString("id");
String userName=rs.getString("userName");
String mima=rs.getString("mima");
Student stu=new Student(id,userName,mima);
list.add(stu);
} } catch (SQLException e) {
e.printStackTrace();
}
} return list;
}
/* 根据用户名查询用户信息
* @param userName
* @return
*/
public static Student findUserByName(String id)
{
Student stu=null;
//输出查询sql
String sql = "select * from denglu t where t.id='"+id+"'";
try {
//调用连接并创建SQL语句
Statement stam= DBUtil.getConnection().createStatement();
ResultSet rs=stam.executeQuery(sql);
if(rs.next())
{
String i=rs.getString("id");
String name=rs.getString("userName");
String mima=rs.getString("mima");
stu=new Student(i,name,mima);
} } catch (SQLException e) {
e.printStackTrace(); }
return stu;
} /**
* 根据编码修改用户信息
* @param user
* @return
*/
public static int update(Student stu)
{
//执行sql的结果
int result = 0;
//更新sql String sql = "update denglu t set t.userName='"+stu.getUserName()+"',t.mima = '"+stu.getMima()+"' where t.id ='"+stu.getId()+"'";
try {
Statement stam= DBUtil.getConnection().createStatement();
result=stam.executeUpdate(sql); } catch (SQLException e) {
e.printStackTrace();
} return result;
}
}

8.查询数据的servlet

 package com.zdsofe.work;

 import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; 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 javax.servlet.http.HttpSession; import com.zdsofe.util.DBUtil; /**
* Servlet implementation class servlet
*/
@WebServlet("/servlet")
public class servlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public servlet() {
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");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html charset=utf-8"); //获取用户id:
String userI = request.getParameter("userI"); //根据用户id查询某一条用户信息
Student stu=ReadData.findUserByName(userI);
HttpSession session = request.getSession();
session.setAttribute("user", stu);
session.setAttribute("title", "修改用户");
response.sendRedirect(request.getContextPath()+"/pages/edit.jsp");
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }

9..增加数据的servlet

 package com.zdsofe.work;

 import java.io.IOException;
import java.sql.SQLException;
import java.sql.Statement; 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.zdsofe.util.DBUtil; /**
* Servlet implementation class AddServlet
*/
@WebServlet("/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 {
// TODO Auto-generated method stub
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int i=0; //请求和响应页面的编码格式修改
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html charset=utf-8"); String sql="insert into denglu values('"+request.getParameter("id")+"','"+request.getParameter("userName")+"','"+request.getParameter("mima")+"')";
try {
Statement stam=DBUtil.getConnection().createStatement();
i=stam.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
if(i==1)
{
response.sendRedirect(request.getContextPath()+"/pages/student.jsp");
}
} }

10.删除数据的servlet

 package com.zdsofe.work;

 import java.io.IOException;
import java.sql.SQLException;
import java.sql.Statement; 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.zdsofe.util.DBUtil; /**
* Servlet implementation class DeleteServlet
*/
@WebServlet("/DeleteServlet")
public class DeleteServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public DeleteServlet() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取要删除的用户ID
String userId = request.getParameter("userI");
//删除的sql语句
String sql = "delete from denglu where id = "+userId+""; try {
Statement stam= DBUtil.getConnection().createStatement();
stam.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.sendRedirect(request.getContextPath()+"/pages/student.jsp");
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
} }

11.模糊查询的servlet

 package com.zdsofe.work;

 import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; 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.zdsofe.util.DBUtil; /**
* Servlet implementation class DimServlet
*/
@WebServlet("/DimServlet")
public class DimServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public DimServlet() {
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");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html charset=utf-8"); //获取输入的模糊数据
String se=request.getParameter("se");
String in=request.getParameter("in"); ReadData.findDim(se,in);
request.getSession().setAttribute("se", se);
request.getSession().setAttribute("in", in); /* request.getRequestDispatcher("/pages/newStudent.jsp").forward(request, response);*/
response.sendRedirect(request.getContextPath()+"/pages/newStudent.jsp");
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }

12.修改数据的servlet

 package com.zdsofe.work;

 import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map; 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 org.apache.commons.beanutils.BeanUtils; /**
* Servlet implementation class EditServlet
*/
@WebServlet("/EditServlet")
public class EditServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public EditServlet() {
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");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html charset=utf-8");
/*//获取表单中的所用控件name属性
Enumeration<String> en = request.getParameterNames();
Map<String, Object> mapObj = new HashMap<>();
//实例化一个Student对象
Student stu=new Student();
while(en.hasMoreElements())
{
String rs = en.nextElement();
mapObj.put(rs, request.getParameter("rs"));
}
try {
BeanUtils.populate(stu, mapObj); } catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}*/
String name=request.getParameter("userName");
String mima=request.getParameter("mima");
String id=request.getParameter("id"); Student stu=new Student(id,name,mima);
//根据条件修改用户信息,调用执行sql方法 int upResult = ReadData.update(stu); if(upResult==1)
{
response.sendRedirect(request.getContextPath()+"/pages/student.jsp");
} } /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
} }

13.删除多个的servlet

 package com.zdsofe.work;

 import java.io.IOException;
import java.sql.SQLException;
import java.sql.Statement; 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.zdsofe.util.DBUtil; /**
* Servlet implementation class MoreDeleteServlet
*/
@WebServlet("/MoreDeleteServlet")
public class MoreDeleteServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public MoreDeleteServlet() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] id=request.getParameterValues("c"); if(id.length>0)
{
for(int i=0;i<id.length;i++)
{
//删除的sql语句
String sql = "delete from denglu where id = "+id[i]+"";
try {
Statement stam= DBUtil.getConnection().createStatement();
stam.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
} }
}
response.sendRedirect(request.getContextPath()+"/pages/student.jsp");
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
} }