JavaBean+servlet+jsp——>对数据进行增删改查

1.开始页面(查询数据)

 1 <%@page import="com.zdsofe.work.Student"%>
 2 <%@page import="java.util.List"%>
 3 <%@page import="com.zdsofe.work.ReadData"%>
 4 <%@ page language="java" contentType="text/html; charset=UTF-8"
 5     pageEncoding="UTF-8"%>
 6 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 7 <html>
 8 <head>
 9 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
10 <title>Insert title here</title>
11 </head>
12 <body>
13 <% ReadData rd=new ReadData();
14   List<Student> list= rd.findInfo();
15 %>
16
17 <table border="1">
18 <tr>
19 <th>序号</th>
20 <th>名字</th>
21 <th>密码</th>
22 <th>操作</th>
23 </tr>
24
25
26 <%
27 for(int i=0;i<list.size();i++)
28 {
29     %>
30     <tr>
31     <td><%=list.get(i).getId()%></td>
32     <td><%=list.get(i).getUserName()%></td>
33     <td><%=list.get(i).getMima()%></td>
34     <td><a href="../servlet?userN=<%=list.get(i).getUserName()%>">修改</a>
35         <a href="../DeleteServlet?userI=<%=list.get(i).getId()%>">删除</a>
36     </td>
37     </tr>
38 <%
39   }
40 %>
41
42 </table>
43 </body>
44 </html>

2.获取数据的servlet

 1 package com.zdsofe.work;
 2
 3 import java.io.IOException;
 4 import java.sql.ResultSet;
 5 import java.sql.SQLException;
 6 import java.sql.Statement;
 7
 8 import javax.servlet.ServletException;
 9 import javax.servlet.annotation.WebServlet;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import javax.servlet.http.HttpSession;
14
15 import com.zdsofe.util.DBUtil;
16
17 /**
18  * Servlet implementation class servlet
19  */
20 @WebServlet("/servlet")
21 public class servlet extends HttpServlet {
22     private static final long serialVersionUID = 1L;
23
24     /**
25      * @see HttpServlet#HttpServlet()
26      */
27     public servlet() {
28         super();
29         // TODO Auto-generated constructor stub
30     }
31
32     /**
33      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
34      */
35     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
36         //解决乱码问题
37         request.setCharacterEncoding("utf-8");
38         response.setCharacterEncoding("utf-8");
39         response.setContentType("text/html charset=utf-8");
40
41        //获取用户名:
42         String userName = request.getParameter("userN");
43
44        //根据用户名查询某一条用户信息
45         Student stu=ReadData.findUserByName(userName);
46         HttpSession session = request.getSession();
47         session.setAttribute("user", stu);
48         session.setAttribute("title", "修改用户");
49         response.sendRedirect("/webProject2/pages/edit.jsp");
50     }
51
52     /**
53      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
54      */
55    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
56
57
58     }
59
60 }

3.修改页面

 1 <%@page import="com.zdsofe.work.Student"%>
 2 <%@ page language="java" contentType="text/html; charset=UTF-8"
 3     pageEncoding="UTF-8"%>
 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <title>Insert title here</title>
 9 </head>
10
11 <%
12 //获取用户信息
13    Student stu=(Student)session.getAttribute("user");
14 %>
15 <body>
16
17 <form action="../EditServlet" method="get">
18
19 用户名:<input type="text" name="userName" value="<%=stu.getUserName()%>"><br/>
20 密码:<input type="password" name="mima" value="<%=stu.getMima()%>"><br/>
21 <button type="submit">提交</button>
22
23 </form>
24
25 </body>
26 </html>

4.修改数据的servlet

 1 package com.zdsofe.work;
 2
 3 import java.io.IOException;
 4 import java.lang.reflect.InvocationTargetException;
 5 import java.util.Enumeration;
 6 import java.util.HashMap;
 7 import java.util.Map;
 8
 9 import javax.servlet.ServletException;
10 import javax.servlet.annotation.WebServlet;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14
15 import org.apache.commons.beanutils.BeanUtils;
16
17 /**
18  * Servlet implementation class EditServlet
19  */
20 @WebServlet("/EditServlet")
21 public class EditServlet extends HttpServlet {
22     private static final long serialVersionUID = 1L;
23
24     /**
25      * @see HttpServlet#HttpServlet()
26      */
27     public EditServlet() {
28         super();
29         // TODO Auto-generated constructor stub
30     }
31
32     /**
33      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
34      */
35     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
36                 //请求和响应页面的编码格式修改
37
38                 request.setCharacterEncoding("UTF-8");
39                 response.setCharacterEncoding("utf-8");
40                 response.setContentType("text/html charset=utf-8");
41                 /*//获取表单中的所用控件name属性
42                 Enumeration<String> en = request.getParameterNames();
43                 Map<String, Object> mapObj = new HashMap<>();
44                 //实例化一个Student对象
45                 Student stu=new Student();
46                 while(en.hasMoreElements())
47                 {
48                     String rs = en.nextElement();
49                     mapObj.put(rs, request.getParameter("rs"));
50                 }
51                 try {
52                     BeanUtils.populate(stu, mapObj);
53
54
55                 } catch (IllegalAccessException | InvocationTargetException e) {
56                     e.printStackTrace();
57                 }*/
58                 String name=request.getParameter("userName");
59                 String mima=request.getParameter("mima");
60                 Student stu=new Student(name,mima);
61                 //根据条件修改用户信息,调用执行sql方法
62
63                 int upResult = ReadData.update(stu);
64
65                 if(upResult==1)
66                 {
67                     response.sendRedirect(request.getContextPath()+"/pages/student.jsp");
68                 }
69
70     }
71
72     /**
73      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
74      */
75     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
76         // TODO Auto-generated method stub
77     }
78
79 }

5.删除数据的servlet

 1 package com.zdsofe.work;
 2
 3 import java.io.IOException;
 4 import java.sql.SQLException;
 5 import java.sql.Statement;
 6
 7 import javax.servlet.ServletException;
 8 import javax.servlet.annotation.WebServlet;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12
13 import com.zdsofe.util.DBUtil;
14
15 /**
16  * Servlet implementation class DeleteServlet
17  */
18 @WebServlet("/DeleteServlet")
19 public class DeleteServlet extends HttpServlet {
20     private static final long serialVersionUID = 1L;
21
22     /**
23      * @see HttpServlet#HttpServlet()
24      */
25     public DeleteServlet() {
26         super();
27         // TODO Auto-generated constructor stub
28     }
29
30     /**
31      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
32      */
33     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
34
35                 //获取要删除的用户ID
36                 String userId = request.getParameter("userI");
37                 //删除的sql语句
38                 String sql = "delete from denglu  where id = "+userId+"";
39
40             try {
41                 Statement stam=    DBUtil.getConnection().createStatement();
42                 stam.executeUpdate(sql);
43             } catch (SQLException e) {
44                 // TODO Auto-generated catch block
45                 e.printStackTrace();
46             }
47             response.sendRedirect(request.getContextPath()+"/pages/student.jsp");
48     }
49
50     /**
51      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
52      */
53     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
54         // TODO Auto-generated method stub
55     }
56
57 }

6.javaBean(实体类)

 1 package com.zdsofe.work;
 2
 3 public class Student {
 4  public String id;
 5  public  String userName;
 6  public  String mima;
 7
 8 public Student(String id, String userName, String mima) {
 9     super();
10     this.id = id;
11     this.userName = userName;
12     this.mima = mima;
13 }
14
15 public Student(String userName, String mima) {
16
17     this.userName = userName;
18     this.mima = mima;
19 }
20
21 public Student() {
22     super();
23 }
24
25 public String getId() {
26     return id;
27 }
28 public void setId(String id) {
29     this.id = id;
30 }
31 public String getUserName() {
32     return userName;
33 }
34 public void setUserName(String userName) {
35     this.userName = userName;
36 }
37 public String getMima() {
38     return mima;
39 }
40 public void setMima(String mima) {
41     this.mima = mima;
42 }
43
44
45
46
47 }

7.方法

 1 package com.zdsofe.work;
 2
 3 import java.sql.ResultSet;
 4 import java.sql.SQLException;
 5 import java.sql.Statement;
 6 import java.util.ArrayList;
 7 import java.util.List;
 8
 9 import com.zdsofe.util.DBUtil;
10
11
12
13 public class ReadData {
14
15     //查询信息
16     public static List<Student> findInfo() {
17
18
19         List <Student>list=new ArrayList<>();
20         //调用连接并创建SQL语句
21         try {
22             Statement stam= DBUtil.getConnection().createStatement();
23             String sql="SELECT id,userName,mima FROM  denglu;";
24             ResultSet rs=stam.executeQuery(sql);
25             while(rs.next())
26             {
27                 String id=rs.getString("id");
28                 String userName=rs.getString("userName");
29                 String mima=rs.getString("mima");
30                 Student stu=new Student(id,userName,mima);
31                 list.add(stu);
32             }
33
34         } catch (SQLException e) {
35             e.printStackTrace();
36
37         }
38         return list;
39     }
40
41      /* 根据用户名查询用户信息
42      * @param userName
43      * @return
44      */
45     public static Student findUserByName(String userName)
46     {
47         Student stu=null;
48         //输出查询sql
49         String sql = "select * from denglu t where t.userName=‘"+userName+"‘";
50         try {
51             //调用连接并创建SQL语句
52             Statement stam= DBUtil.getConnection().createStatement();
53
54             ResultSet rs=stam.executeQuery(sql);
55             if(rs.next())
56             {
57                 String id=rs.getString("id");
58                 String name=rs.getString("userName");
59                 String mima=rs.getString("mima");
60                 stu=new Student(id,name,mima);
61             }
62
63         } catch (SQLException e) {
64             e.printStackTrace();
65
66         }
67         return stu;
68     }
69
70     /**
71      * 根据编码修改用户信息
72      * @param user
73      * @return
74      */
75     public static int update(Student stu)
76     {
77         //执行sql的结果
78         int result = 0;
79         //更新sql
80
81         String sql = "update denglu t set t.mima = ‘"+stu.getMima()+"‘ where t.userName =‘"+stu.getUserName()+"‘";
82         try {
83         Statement stam=    DBUtil.getConnection().createStatement();
84             result=stam.executeUpdate(sql);
85
86         } catch (SQLException e) {
87             e.printStackTrace();
88         }
89
90
91         return result;
92     }
93 }

8.连接数据库的包装类

 1 package com.zdsofe.util;
 2
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.SQLException;
 6
 7 public class DBUtil {
 8     private static String DRIVER="com.mysql.jdbc.Driver";
 9     private static String URL="jdbc:mysql://localhost:3306/mysql";
10     private static String user="root";
11     private static String key="775297";
12     public static Connection conn;
13
14     //加载驱动
15         static{
16             try {
17                 Class.forName(DRIVER);
18             } catch (ClassNotFoundException e) {
19                 e.printStackTrace();
20             }
21         }
22         //连接数据库
23         public static Connection getConnection(){
24          try {
25             conn = DriverManager.getConnection(URL, user, key);
26         } catch (SQLException e) {
27             e.printStackTrace();
28         }
29             return conn;
30         }
31 }

时间: 2024-12-31 04:45:23

JavaBean+servlet+jsp——>对数据进行增删改查的相关文章

java:JSP(JSPWeb.xml的配置,动态和静态导入JSP文件,重定项和请求转发,使用JSP实现数据库的增删改查实例)

1.JSP的配置: <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":&qu

数据的增删改查(三层)

进行数据操作必然少了对数据的增删改查,用代码生成器生成的代码不是那么满意!方便在今后使用,这里就主要写“数据访问层(Dal)” 注:这里由于是用于用于测试时,临时建的数据库用于测试使用,在实际使用过程中些许改点参数就可以使用了 /// <summary> /// 是否存在该记录 /// </summary> public bool Exists(long Id) { string sql = "select count(*) Name from t_temp where

yii中数据的"增删改查"相关工作!(此文比较乱,需细看)

使用findByPk()根据数据表主键查询的是对象,不需要使用foreach()循环出来 但是使用findall()和find()查询的是对象类型的数组需要使用foreach()循环出来 ======================================= public function getMinLimit () { $sql = "..."; $result = yii::app()->db->createCommand($sql); $query = $r

Mybatis学习总结(二)—使用接口实现数据的增删改查

在这一篇中,让我们使用接口来实现一个用户数据的增删改查. 完成后的项目结构如下图所示: 在这里,person代表了一个用户的实体类.在该类中,描述了相关的信息,包括id.name.age.id_num信息.而personMapper则是该实体类的一个配置文件.需要注意的是,在上一篇博文中,namespace属性的值是其本身,而在这一篇中,使用的是接口.那么两者有什么区别呢?使用接口,那么相关的操作方法不用自己去实现,只需要调用该接口的相关的方法就能够实现相应的功能. 那么,在这里就有一个问题,接

ios CoreData框架的使用,对上下文数据的增删改查,表与表之间的关联,1对多,1对1,谓词查询,多表连接

这里是只是代码,因为博客插入图片效果不是很好,我自己写的总结比较详细,有兴趣的朋友可以在评论里留下邮箱,我收到后会发给大家. 转载注明出处,重视原创者的劳动成果,谢谢! - (void)viewDidLoad { [super viewDidLoad]; [self _creatTable];//插入数据 //    [self _query];// 查询数据 // KVC很霸道,即使readonly通过kvc也可赋值,kvo精华 //    Book * book = [[Book alloc

Node.js + MySQL 实现数据的增删改查

通过完成一个 todo 应用展示 Node.js + MySQL 增删改查的功能.这里后台使用 Koa 及其相应的一些中间件作为 server 提供服务. 初始化项目 $ mkdir node-crud && cd $_ $ yarn init -y && npx gitignore node 上面的命令创建了一个空文件夹 node-crud,进入之后初始化一个 package.json 以及创建 .gitignore 文件. 安装 Koa 并创建 app.js 以启动一个

web项目总结——通过jsp+servlet实现对oracle的增删改查功能

1.DAO模式 分包:依次建立 entity:实体包,放的是跟oracle数据库中表结构相对应的对象的属性,也就是这个对象有什么 dao:增删改查接口,实现增删改查的具体方法 service:同dao,也是一个接口,一个接口的实现类,方法什么的都跟dao差不多 servlet:新建servlet类,继承HttpServlet类,一个方法建立一个servlet类,根据不同的方法选择使用doGet().doPost()方法 .services()既包含doGet 又包含doPost 新建jsp页面

SpringMVC框架下数据的增删改查,数据类型转换,数据格式化,数据校验,错误输入的消息回显

在eclipse中javaEE环境下: 这儿并没有连接数据库,而是将数据存放在map集合中: 将各种架包导入lib下... 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使用三层架构(显示层、业务逻辑层、数据访问层)实现数据的增删改查

实例: 1.功能描述 实现一个简易新闻发布系统,包括查看.添加.修改和删除新闻等基本功能 2.具体要求 (1) 创建数据库 newssystem,创建表 news,要求如下: (2) 程序运行时,显示'发布新闻'页面(如图 1),输入相关内容,单击'提交'按钮,将新闻内容添加到数据库 (3) 单击图 1 中的'查看'按钮,显示'查看新闻'页面(如图 2),增加'修改'和'删除'链接 (4) 单击图 2 中的'update'链接,显示'修改新闻'页面(如图 3),修改后单击'修改'按钮确认,单击'