Table of Contents
In zhu.jdbc.unit Create a class WebUtils.java under the package (class used to store parameter definitions)
class (class used to store parameter definitions)
Home Java javaTutorial The parameters of the form submitted in jsp are encapsulated into a method

The parameters of the form submitted in jsp are encapsulated into a method

Jun 23, 2017 pm 03:54 PM
javascript parameter submit form

It is recommended to take a look at the Servlet+JSP+JavaBean development model () written by Guao Canglang. What a big gain! I also learned from him how to encapsulate jsp delivery parameters into a method.

I think it is particularly useful,

especially in You can save a lot of code when doing projects

1:

Required packages

Based on the content of the previous article JDBC+Servlet+jsp(), add new function code.

As follows Instructions:

1: Code writing 1.

zhu.jdbc.unit

In zhu.jdbc.unit Create a class WebUtils.java under the package (class used to store parameter definitions)

The WebUtils code is as follows:

 1 package zhu.jdbc.unit; 2  3 import java.util.Enumeration; 4 import java.util.UUID; 5  6 import javax.servlet.http.HttpServletRequest; 7  8 import org.apache.commons.beanutils.BeanUtils; 9 10 /**11  * 把request对象中的请求参数封装到bean中12  * 
13  * @author Xiao_Zhu14  * 
15  */16 public class WebUtils {17 18     /**19      * 将request对象转换成T对象20      * 
21      * @param request22      * @param clazz23      * @return24      */25     public static <T> T request2Bean(HttpServletRequest request, Class<T> clazz) {26         /*27          * JDK中,普通的Class.newInstance()方法的定义返回Object,要将该返回类型强制转换为另一种类型;28          * 但是使用泛型的Class<T>,Class.newInstance()方法具有一个特定的返回类型;29          * java反射就是从Class<T>类开始的,Class<T>是没有公共的构造方法,虽然没有构造方法,但是有相应的方法可以获取类的变量和类型30          * “?”是一个匹配字符,匹配任意类型;“T”匹配的是某一具体的类型,如String。如果知道Class的具体类型,可以直接使用Class<T>,32          * 如Class<String>33          */34         try {// 创建对象(这里的是创建Tb_User的对象)35             T bean = clazz.newInstance();36             // 使用枚举获取 参数-->key-value 键值对37             Enumeration<String> e = request.getParameterNames();38             while (e.hasMoreElements()) {39                 String key = (String) e.nextElement();40                 String value = request.getParameter(key);41                 BeanUtils.setProperty(bean, key, value);42             }43             return bean;44         } catch (Exception e) {45             throw new RuntimeException(e);46         }47     }48 49     /**50      * 生成UUID51      * 
52      * @return53      */54     public static String makeId() {55         return UUID.randomUUID().toString();56     }57 }
Copy after login

In order to make it more clear, I will create another servlet and jsp

2. zhu.jdbc.servlet

Create one under the zhu.jdbc.servlet package

Servlet_TbUser2.java

class (class used to store parameter definitions)

The main difference is: when the method request2Bean of the WebUtils class is not called, the delivery The parameters are like this

After calling, they are like this:

Servlet_TbUser2

The code is as follows:

 1 package zhu.jdbc.servlet; 2  3 import java.io.IOException; 4 import java.sql.Date; 5 import java.text.ParseException; 6 import java.text.SimpleDateFormat; 7 import java.util.List; 8  9 import javax.servlet.ServletException;10 import javax.servlet.http.HttpServlet;11 import javax.servlet.http.HttpServletRequest;12 import javax.servlet.http.HttpServletResponse;13 14  15 16 import zhu.jdbc.domain.Tb_User;17 import zhu.jdbc.service.ITb_UserService;18 import zhu.jdbc.service.imp.ITb_UserServiceImpI;19 import zhu.jdbc.unit.WebUtils;20 21 public class Servlet_TbUser2 extends HttpServlet {22     /**23      * 
24      */25     private static final long serialVersionUID = 1L;26     ITb_UserService myITb_UserService = new ITb_UserServiceImpI();27 28     @Override29     protected void doGet(HttpServletRequest req, HttpServletResponse resp)30             throws ServletException, IOException {31         doPost(req, resp);32     }33 34     @Override35     protected void doPost(HttpServletRequest request,36             HttpServletResponse response) throws ServletException, IOException {37         request.setCharacterEncoding("UTF-8");// 解决乱码38         String type = request.getParameter("who");39         // 新增40         if ("Insert".equals(type)) {41             Insert(request, response);42         }43         //查询所有数据44         else if("queryAll".equals(type)){45             queryAll(request, response);46         } 
47     }48 49     // 新增50     public void Insert(HttpServletRequest request, HttpServletResponse response)51             throws ServletException, IOException {52         /*注册字符串到日期的转换器 
53          * ConvertUtils.register(new DateLocaleConverter(), java.util.Date.class); 
54          * */ 55                 //将jsp页面专递参数封装到 domain层的 Tb_User对象中56                  Tb_User tb_User=WebUtils.request2Bean(request, Tb_User.class); 
57                  System.out.println(tb_User.getName()); 
58                 // 把获取到的这些值放到user里59                 Tb_User user = new Tb_User();60                 try {61                     // 下面两句是把 string 转换为 sql类型的 时间格式62                     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");63                     String time=sdf.format(tb_User.getBirthday());64                      user.setBirthday(new Date(sdf.parse(time).getTime()));65                     user.setEmail(tb_User.getEmail());66                     user.setName(tb_User.getName());67                     user.setPassword(tb_User.getPassword()); 
68                     user.setSex(tb_User.isSex());69                     // 最后调用服务来添加70                     String message = null;71                     if (myITb_UserService.insertData(user) == true) {72                         queryAll(request, response);73                     } else {74                         message = "新增失败!!!";75                         request.setAttribute("msg", message);76                         request.getRequestDispatcher("/index.jsp").forward(request,    response);77                     }78                 } catch (Exception e1) {79                     e1.printStackTrace();80                 }81     }82      //查询所有的数据83      public void queryAll(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{84              List<Tb_User> lis=myITb_UserService.queryAllData(); 
85              request.setAttribute("list", lis);86                  request.getRequestDispatcher("/jsp/WebUtils_User.jsp").forward(request, response);87         }88       89 }
Copy after login

3.jsp

Create a

WebUtils_User.jsp

The code of WebUtils_User.jsp is as follows:

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 <!--    c标签要使用,那么就必须要有它 --> 7 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 8 <c:set scope="page" var="url" 9     value="${pageContext.request.contextPath }"></c:set>10  11 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">12 <html>13   <head>14     <base href="<%=basePath%>"> 15     <title>My JSP 'WebUtils_User.jsp' starting page</title> 16   </head>17   18   <body>19     <div align="center"20         style="width: 400px; position: relative;left:450px">21         <form action="${url}/zhu/Servlet_TbUser2?who=Insert" method="post">22             <h4>新增用户</h4>23             姓名: <input type="text" name="name"><br />24              密码: <input    type="text" name="password"><br /> 25              出生日期 : <input type="text" name="birthday"><br /> 26              性别: <select name="sex">27                 <option value="0">男</option>28                 <option value="1">女</option>29             </select><br /> 30             <input type="submit" value="新增"/>31             <hr />32         </form>33     </div> 34     <div align="center"style="width: 400px; position: relative;left:450px;">35         <form action="${url}/zhu/Servlet_TbUser2?who=queryAll" method="post"> 36              <input type="submit" value="查询所有的数据"/> <br/>37             <table border="1"  cellspacing="0"> 38                  <thead>39                   <tr><td>ID</td><td>姓名</td><td>密码</td><td>日期</td><td>性别</td><td>操作</td></tr>40                  </thead>41                  <tbody>42          <c:forEach items="${list}" var="list">43          <tr>44                 <td>${list.id }</td>45                 <td>${list.name }</td>46                 <td>${list.password }</td>47                 <td>${list.birthday }</td> 48                 <td><c:if test="${list.sex==false }">男</c:if>49                 <c:if test="${list.sex==true }">女</c:if></td>50                  <td><a  href= "${url}/zhu/Servlet_TbUser?who=queryById&id=${list.id}"     style=&#39;text-decoration:none&#39;       >修改 </a> 51                     <a    href= "${url}/zhu/Servlet_TbUser?who=delete&id=${list.id}"   style=&#39;text-decoration:none&#39;     >删除</a>  </td> 52          </tr>53          </c:forEach>54                  </tbody>55             </table>56             <hr />57         </form>58     </div> 59   </body>60 </html>
Copy after login

The effect is as follows

Two: Use jQuery to raise price form

Apply jquery- 2.1.4.min.js file

Use jQuery-2.1.4.min.js file in the WebUtils_User.jsp just now to use jQuery

The complete code of WebUtils_User.jsp is as follows:

##
 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 <!--    c标签要使用,那么就必须要有它 --> 7 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 8 <c:set scope="page" var="url" 9     value="${pageContext.request.contextPath }"></c:set>10  11 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">12 <html>13   <head>14     <base href="<%=basePath%>"> 15     <title>My JSP 'WebUtils_User.jsp' starting page</title> 16   <script type="text/javascript" src="${url}/js/jquery-2.1.4.min.js?1.1.11"></script>17   <script type="text/javascript">18   function funInsert(){19   //专递的参数和定义的变量必须要遵循驼峰形式的格式20   var userName=$("#name").val();21    var userPassword=$("#password").val();22     var userSex=$("#sex").val();23      var userBirthday=$("#birthday").val(); 
24      //那面的专递的参数 如:name,password...必须要与domain层的表的名称对应,25   $.post("${url}/zhu/Servlet_TbUser2",{who:'jQueryInsert',name:userName,password:userPassword,sex:userSex,birthday:userBirthday},  
26   function(getData){27         console.log(getData); 
28         alert(getData.msg); 
29         30      },"json");31   }32   33   </script>34   </head>35   36   <body>37   38     <div align="center"39         style="width: 400px; position: relative;left:450px">40         <form action="${url}/zhu/Servlet_TbUser2?who=Insert" method="post">41             <h4>新增用户</h4>42             姓名: <input type="text" name="name"><br />43              密码: <input    type="text" name="password"><br /> 44              出生日期 : <input type="text" name="birthday"><br /> 45              性别: <select name="sex">46                 <option value="0">男</option>47                 <option value="1">女</option>48             </select><br /> 49             <input type="submit" value="新增"/>50             <hr />51         </form>52     </div> 53     <div align="center"style="width: 400px; position: relative;left:450px;">54         <form action="${url}/zhu/Servlet_TbUser2?who=queryAll" method="post"> 55              <input type="submit" value="查询所有的数据"/> <br/>56             <table border="1"  cellspacing="0"> 57                  <thead>58                   <tr><td>ID</td><td>姓名</td><td>密码</td><td>日期</td><td>性别</td><td>操作</td></tr>59                  </thead>60                  <tbody>61          <c:forEach items="${list}" var="list">62          <tr>63                 <td>${list.id }</td>64                 <td>${list.name }</td>65                 <td>${list.password }</td>66                 <td>${list.birthday }</td> 67                 <td><c:if test="${list.sex==false }">男</c:if>68                 <c:if test="${list.sex==true }">女</c:if></td>69                  <td><a  href= "${url}/zhu/Servlet_TbUser?who=queryById&id=${list.id}"     style=&#39;text-decoration:none&#39;       >修改 </a> 70                     <a    href= "${url}/zhu/Servlet_TbUser?who=delete&id=${list.id}"   style=&#39;text-decoration:none&#39;     >删除</a>  </td> 71          </tr>72          </c:forEach>73                  </tbody>74             </table>75             <hr />76         </form>77     </div> 78 79      <div align="center"80         style="width: 400px; position: relative;left:450px"> 81             <h4>不用使用form标签提交表单,使用jQuery的post来提交表单</h4>82             <h5>新增用户</h5> 83             姓名: <input type="text" id="name"><br />84              密码: <input    type="text" id="password"><br /> 85              出生日期 : <input type="text" id="birthday"><br /> 86              性别: <select id="sex">87                 <option value="0">男</option>88                 <option value="1">女</option>89             </select><br /> 90             <input type="button" value="新增" onclick="funInsert()"/>91             <hr />92          93     </div> 94   </body>95 </html>
Copy after login

Servlet_TbUser2Complete
The code is as follows:

Use the

JSON* method to transfer data from the servlet to a jsp

JSON* is used as needed The jar package is

##

  1 package zhu.jdbc.servlet;  2   3 import java.io.IOException;  4 import java.sql.Date;  5    6 import java.text.SimpleDateFormat;  7 import java.util.List;  8   9 import javax.servlet.ServletException; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13  14 import net.sf.json.JSONObject; 15  16   17  18 import zhu.jdbc.domain.Tb_User; 19 import zhu.jdbc.service.ITb_UserService; 20 import zhu.jdbc.service.imp.ITb_UserServiceImpI; 21 import zhu.jdbc.unit.WebUtils; 22  23 public class Servlet_TbUser2 extends HttpServlet { 24     /** 25      * 
 26      */ 27     private static final long serialVersionUID = 1L; 28     ITb_UserService myITb_UserService = new ITb_UserServiceImpI(); 29  30     @Override 31     protected void doGet(HttpServletRequest req, HttpServletResponse resp) 32             throws ServletException, IOException { 33         doPost(req, resp); 34     } 35  36     @Override 37     protected void doPost(HttpServletRequest request, 38             HttpServletResponse response) throws ServletException, IOException { 39         request.setCharacterEncoding("UTF-8");// 解决乱码 40         String type = request.getParameter("who"); 41         // 新增 42         if ("Insert".equals(type)) { 43             Insert(request, response); 44         } 45         //查询所有数据 46         else if("queryAll".equals(type)){ 47             queryAll(request, response); 48         } 
 49         //使用jquery提交表单新增 50                 else if("jQueryInsert".equals(type)){ 51                     jQueryInsert(request, response); 52                 } 
 53     } 54  55     // 新增 56     public void Insert(HttpServletRequest request, HttpServletResponse response) 57             throws ServletException, IOException { 58         /*注册字符串到日期的转换器 
 59          * ConvertUtils.register(new DateLocaleConverter(), java.util.Date.class); 
 60          * */ 
 61                 //将jsp页面专递参数封装到 domain层的 Tb_User对象中 62                  Tb_User tb_User=WebUtils.request2Bean(request, Tb_User.class); 
 63                  System.out.println(tb_User.getName()); 
 64                 // 把获取到的这些值放到user里 65                 Tb_User user = new Tb_User(); 66                 try { 67                     // 下面两句是把 string 转换为 sql类型的 时间格式 68                     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 69                     String time=sdf.format(tb_User.getBirthday()); 70                      user.setBirthday(new Date(sdf.parse(time).getTime())); 71                     user.setEmail(tb_User.getEmail()); 72                     user.setName(tb_User.getName()); 73                     user.setPassword(tb_User.getPassword()); 
 74                     user.setSex(tb_User.isSex()); 75                     // 最后调用服务来添加 76                     String message = null; 77                     if (myITb_UserService.insertData(user) == true) { 78                         queryAll(request, response); 79                     } else { 80                         message = "新增失败!!!"; 81                         request.setAttribute("msg", message); 82                         request.getRequestDispatcher("/index.jsp").forward(request,    response); 83                     } 84                 } catch (Exception e1) { 85                     e1.printStackTrace(); 86                 } 87     } 88      //查询所有的数据 89      public void queryAll(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{ 90              List<Tb_User> lis=myITb_UserService.queryAllData(); 
 91              request.setAttribute("list", lis); 92                  request.getRequestDispatcher("/jsp/WebUtils_User.jsp").forward(request, response); 93         } 94       95       96     // 新增 97         public void jQueryInsert(HttpServletRequest request, HttpServletResponse response) 98                 throws ServletException, IOException { 99             100             /*注册字符串到日期的转换器 
101              * ConvertUtils.register(new DateLocaleConverter(), java.util.Date.class); 
102              * */ 
103                     //将jsp页面专递参数封装到 domain层的 Tb_User对象中104                      Tb_User tb_User=WebUtils.request2Bean(request, Tb_User.class); 
105                      System.out.println(tb_User.getName()); 
106                     // 把获取到的这些值放到user里107                     Tb_User user = new Tb_User();108                     try {109                         // 下面两句是把 string 转换为 sql类型的 时间格式110                         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");111                         String time=sdf.format(tb_User.getBirthday());112                          user.setBirthday(new Date(sdf.parse(time).getTime()));113                         user.setEmail(tb_User.getEmail());114                         user.setName(tb_User.getName());115                         user.setPassword(tb_User.getPassword()); 
116                         user.setSex(tb_User.isSex());117                         // 最后调用服务来添加 
118                         119                          JSONObject json=new JSONObject();120                         response.setCharacterEncoding("UTF-8");//解决乱码121                         if (myITb_UserService.insertData(user) == true) {122                             json.put("msg", "新增成功!");  
123                         } else { 
124                             json.put("msg", "新增失败!");  
125                         }126                         //使用了JSONObject就必须这句代码 
127                            response.getWriter().write(json.toString());128                     } catch (Exception e1) {129                         e1.printStackTrace();130                     }131                 132         }133       134 }
Copy after login

Effect :

Source code download address:

The above is the detailed content of The parameters of the form submitted in jsp are encapsulated into a method. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C++ function parameter type safety check C++ function parameter type safety check Apr 19, 2024 pm 12:00 PM

C++ parameter type safety checking ensures that functions only accept values ​​of expected types through compile-time checks, run-time checks, and static assertions, preventing unexpected behavior and program crashes: Compile-time type checking: The compiler checks type compatibility. Runtime type checking: Use dynamic_cast to check type compatibility, and throw an exception if there is no match. Static assertion: Assert type conditions at compile time.

i9-12900H parameter evaluation list i9-12900H parameter evaluation list Feb 23, 2024 am 09:25 AM

i9-12900H is a 14-core processor. The architecture and technology used are all new, and the threads are also very high. The overall work is excellent, and some parameters have been improved. It is particularly comprehensive and can bring users Excellent experience. i9-12900H parameter evaluation review: 1. i9-12900H is a 14-core processor, which adopts the q1 architecture and 24576kb process technology, and has been upgraded to 20 threads. 2. The maximum CPU frequency is 1.80! 5.00ghz, which mainly depends on the workload. 3. Compared with the price, it is very suitable. The price-performance ratio is very good, and it is very suitable for some partners who need normal use. i9-12900H parameter evaluation and performance running scores

MySQL transaction processing: the difference between automatic submission and manual submission MySQL transaction processing: the difference between automatic submission and manual submission Mar 16, 2024 am 11:33 AM

MySQL transaction processing: the difference between automatic submission and manual submission. In the MySQL database, a transaction is a set of SQL statements. Either all executions are successful or all executions fail, ensuring the consistency and integrity of the data. In MySQL, transactions can be divided into automatic submission and manual submission. The difference lies in the timing of transaction submission and the scope of control over the transaction. The following will introduce the difference between automatic submission and manual submission in detail, and give specific code examples to illustrate. 1. Automatically submit in MySQL, if it is not displayed

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The open source model wins GPT-4 for the first time! Arena's latest battle report has sparked heated debate, Karpathy: This is the only list I trust The open source model wins GPT-4 for the first time! Arena's latest battle report has sparked heated debate, Karpathy: This is the only list I trust Apr 10, 2024 pm 03:16 PM

An open source model that can beat GPT-4 has appeared! The latest battle report of the large model arena: the 104 billion parameter open source model CommandR+ climbed to 6th place, tying with GPT-4-0314 and surpassing GPT-4-0613. Image This is also the first open-weight model to beat GPT-4 in the large model arena. The large model arena is one of the only test benchmarks that the master Karpathy trusts. Image CommandR+ from AI unicorn Cohere. The co-founder and CEO of this large model startup is none other than Aidan Gomez, the youngest author of Transformer (referred to as the wheat harvester). As soon as this battle report came out, another wave of big model clubs started

Advanced usage of reference parameters and pointer parameters in C++ functions Advanced usage of reference parameters and pointer parameters in C++ functions Apr 21, 2024 am 09:39 AM

Reference parameters in C++ functions (essentially variable aliases, modifying the reference modifies the original variable) and pointer parameters (storing the memory address of the original variable, modifying the variable by dereferencing the pointer) have different usages when passing and modifying variables. Reference parameters are often used to modify original variables (especially large structures) to avoid copy overhead when passed to constructors or assignment operators. Pointer parameters are used to flexibly point to memory locations, implement dynamic data structures, or pass null pointers to represent optional parameters.

vivox200ultra parameters and price details vivox200ultra parameters and price details Jun 28, 2024 pm 01:23 PM

The latest official news of vivox200ultra has exposed the parameters and price details of vivox200ultra. It is reported that vivox200ultra will be equipped with a 10x periscope super telephoto lens, and the price starts at about 6999 yuan. It can be seen that it occupies an absolute advantage in photography performance. The following are the parameters and prices of vivox200ultra Come and see the details. 1. Parameter configuration details of vivox200ultra 1. Vivox200ultra rendering From the vivo X200 Ultra rendering, the front of the phone adopts a borderless full-screen design, and the visual effect of the entire front of the phone can be said to be very invincible. 2. vivox200ultra has Blackhawk frame

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles