> Java > java지도 시간 > jsp에 제출된 양식의 매개변수는 메소드로 캡슐화됩니다.

jsp에 제출된 양식의 매개변수는 메소드로 캡슐화됩니다.

巴扎黑
풀어 주다: 2017-06-23 15:54:05
원래의
2171명이 탐색했습니다.

Lone Ao Canglang이 작성한 Servlet+JSP+JavaBean 개발 모델()을 살펴보는 것이 좋습니다.

그의 JavaWeb 학습 요약을 모두 읽는 것이 가장 좋습니다. JSP 전달의 매개 변수도 그에게서 배웠습니다

매우 유용하다고 생각합니다. 특히 프로젝트를 할 때 코드를 많이 절약할 수 있습니다

One: 필수 패키지

이전 글 JDBC+Servlet+jsp() 내용을 토대로 새로운 함수 코드를 추가합니다.

1: 코드 작성

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 }
로그인 후 복사

좀 더 명확히 하기 위해 다른 서블릿과 jsp

를 빌드하겠습니다. 2. zhu.jdbc.servlet

zhu.jdbc.servlet 패키지 아래에 Servlet_TbUser2.java 클래스를 만듭니다(매개변수 정의를 저장하는 데 사용되는 클래스)

주요 차이점은 WebUtils 클래스의 request2Bean 메소드가 호출되지 않을 때 특수 전달 매개변수는 다음과 같습니다.

호출 후 다음과 같습니다.

코드는 다음과 같습니다.

 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 파일 적용

jQuery-2.1을 적용합니다. 방금 WebUtils_User.jsp에 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* 메소드를 사용하여 데이터를 넣습니다. 서블릿에서 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿