首页 >Java >java教程 >在jsp提交表单的参数封装到一个方法里

在jsp提交表单的参数封装到一个方法里

巴扎黑
巴扎黑原创
2017-06-23 15:54:052176浏览

建议去看一下孤傲苍狼写的Servlet+JSP+JavaBean开发模式(),

最好把他JavaWeb学习总结全部看完会有很大的收获哦! 而把jsp专递的参数封装到一个方法里面也是从他那里学到的.

我觉得特别有用,尤其是在做项目的时候能省很多的代码

  一: 需要的包

根据上一篇JDBC+Servlet+jsp()的内容为基础,增加新功能代码.

如下所示: 

一:代码的编写 

 1. zhu.jdbc.unit 

 在zhu.jdbc.unit包下创建一个WebUtils.java的类(用来存放参数定义的类) 

  

WebUtils代码如下:

 

 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 }

 为了更明了点,我再建一个servlet和jsp

 2. zhu.jdbc.servlet 

 在zhu.jdbc.servlet包下创建一个Servlet_TbUser2.java的类(用来存放参数定义的类) 

  

 主要的差别是: 在没有调用WebUtils类的方法request2Bean时,专递参数是这样的

调用了之后是这样的:

 

Servlet_TbUser2代码如下:

 

 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 }

 

3.jsp

 创建一个WebUtils_User.jsp

 

 

  WebUtils_User.jsp的代码如下: 

 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>

 效果如下

 

 

 

 

二:使用jQuery提价表单

应用jquery-2.1.4.min.js的文件

  在刚刚的WebUtils_User.jsp中应用jQuery-2.1.4.min.js的文件即可应用jQuery的了

   WebUtils_User.jsp的完整代码如下:

  

 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>

 

   Servlet_TbUser2完整代码如下:

    使用JSON*方法来把数据从servlet专递个jsp中

    JSON*需要的用用到的jar包是

 

  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 }

 

 效果:

 

 

源码下载地址: 

 

 

以上是在jsp提交表单的参数封装到一个方法里的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
上一篇:读取XML文件下一篇:Java 8——Optional