菜单

AJAX+Servlet实现的数额处理显示效果示例

2018年11月15日 - Ajax

本文实例讲述了AJAX+Servlet实现之数据处理显示力量。分享给大家供大家参考,具体如下:

以下内容引用自http://wiki.jikexueyuan.com/project/servlet/form-data.html:

兑现效益:在输入框中输入字符,用AJAX传到后台Servlet处理后增长自由数,并回到到前台显示。

当得从浏览器到Web服务器传递一些信并最终传回到后台程序时,一定遇到了很多状。浏览器采用简单种植方式为Web服务器传递信息。这些方式是GET方法和POST方法。

一、写前台jsp页面index.jsp

一、GET方法

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <title>My JSP 'index.jsp' starting page</title>
  <script type="text/javascript">
  /*
    ajax 的几个步骤:
    1、建立XmlHttpRequest对象
    2、设置回调函数
    3、使用Open方法建立与服务器的连接
    4、向服务器发送数据
    5、在回调函数中针对不同响应状态进行处理
  */
    var xmlHttp;
    function createXMLHttpRequest(){  //1建立XmlHttpRequest对象
      if(window.ActiveXObject){
        try{
          xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
        }catch(e){
          alert("Error!!!");
        }
      }else{
        xmlHttp = new XMLHttpRequest();
      }
    }
    function showMes(){   //2设置回调函数
      if(xmlHttp.readyState==4){ //数据接收完成并可以使用
        if(xmlHttp.status==200){ //http状态OK
        //5、在回调函数中针对不同响应状态进行处理
          document.getElementById("sp").innerHTML = xmlHttp.responseText; //服务器的响应内容
        }else{
          alert("出错:"+xmlHttp.statusText); //HTTP状态码对应的文本
        }
      }
    }
    /**
    //这是GET方法传送
    function getMes(){
      createXMLHttpRequest();
      var txt = document.getElementById("txt").value;
      var url="servlet/AjaxServlet?txt="+txt;
      url = encodeURI(url); //转换码后再传输
      xmlHttp.open("GET",url,true); //3使用Open方法建立与服务器的连接
      xmlHttp.onreadystatechange=showMes;
      xmlHttp.send(null); //4向服务器发送数据
    }
    */
    /**
    *这是post方法
    */
    function postMes(){
      createXMLHttpRequest();
      var txt = document.getElementById("txt").value;
      var url = "servlet/AjaxServlet";
      var params = "username="+txt;
    // alert(params);
      xmlHttp.open("POST",url,true);
      xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
      xmlHttp.send(params);
      xmlHttp.onreadystatechange = showMes;
    }
  </script>
 </head>
 <body>
  <input type="text" id="txt"/>
  <input type="button" value="query" onclick="postMes()" />

 </body>
</html>

GET方法向页面请求发送已编码的用户信息。页面和早已编码的消息用?字符分隔,如下所示:

二、写后台Servlet加random随机数,关键代码如下:

http://www.test.com/hello?key1=value1&key2=value2
public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("utf-8"); //用utf-8转换获得传输过来的码
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String txt = request.getParameter("txt");
//   String tx = new String(txt.getBytes("iso-8859"),"utf-8");
    out.print("txt="+txt+Math.random());
    out.flush();
    out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String username = request.getParameter("username");
//   String txt = new String(username.getBytes("ISO-8859-1"),"UTF-8");
    String txt = new String(username);
    out.print("txt="+txt+":"+Math.random());
    out.flush();
    out.close();
}

GET方法是自浏览器为Web服务器传递信息的默认的措施,且其见面以浏览器的地点栏中发生一个雅丰富的字符串。如果往服务器传递密码要任何敏感信息,请不要采取GET方法。GET方法有大小限制:请求字符串中极度多只能发出1024单字符。

重复多关于ajax相关内容感兴趣的读者可查本站专题:《jquery中Ajax用法总结》、《JavaScript中ajax操作技巧总结》、《PHP+ajax技巧及下小结》及《asp.net
ajax技巧总结专题》

这些消息以QUERY_STRING头传递,并通过QUERY_STRING环境变量访问,Servlet使用doGet()方法处理这种类型的要。

盼望本文所述对大家ajax程序设计有着帮助。

二、POST方法

公或许感兴趣之章:

相似情形下,将信息传送给后台程序的平栽更保险的点子是POST方法。POST方法打包信息的主意及GET方法同样,但是POST方法无是将信作URL中?字符之后的文本字符串进行发送,而是将它们当作一个单独的消息发送。消息因规范输出的款型传播后台程序,可以于处理过程中分析并利用这些标准输出。Servlet使用doPost()方法处理这种类型的伸手。

老三、使用Servlet读博表单数据

Servlet以活动分析的方法处理表单数据,根据不同之图景采用如下不同的法子:

季、使用URL的GET方法实例

立是一个概括的URL,使用GET方法以少个价传递给HelloForm程序。

http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI

下是HelloForm.java
Servlet程序,处理由Web浏览器给定的输入。将以getParameter()方法,使访问传递的音信变换得非常容易:

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String title = "Using GET Method to Read Form Data";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n" +
                "<ul>\n" +
                "  <li><b>First Name</b>: "
                + request.getParameter("first_name") + "\n" +
                "  <li><b>Last Name</b>: "
                + request.getParameter("last_name") + "\n" +
                "</ul>\n" +
                "</body></html>");
  }
}

倘条件就是地设置,编译HelloForm.java,如下所示:

$ javac HelloForm.java

万一一切顺利,上述编译会产生HelloForm.class文件。接下来,需要将这近乎公事复制到<Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes中,并在<Tomcat-installation-directory>/webapps/ROOT/WEB-INF/倍受之web.xml文件被开创以下条目:

    <servlet>
        <servlet-name>HelloForm</servlet-name>
        <servlet-class>HelloForm</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloForm</servlet-name>
        <url-pattern>/HelloForm</url-pattern>
    </servlet-mapping>

留神:POM和Eclipse项目直入主体修改web.xml。

今于浏览器的地点栏中输入http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI,并以浏览器中触发上述命令之前,确保已经起步Tomcat服务器。这将时有发生如下所展示之结果:

图片 1

五、使用表单的GET方法实例

下面是一个粗略的实例,使用HTML表单和交由按钮传递两独价值。将采用同样之Servlet
HelloForm来拍卖这输入。

<html>
<body>
<form action="HelloForm" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

用是HTML保存到hello.htm文件被,并将其置身<Tomcat-installation-directory>/webapps/ROOT目录下。当访问http://localhost:8080/Hello.htm每每,下面是上述表单的其实出口。

图片 2

品味输入姓名,然后点击提交按钮来在tomcat运行的地方电脑达查看结果。基于提供的输入,它会发出及上述例子中貌似的结果。

图片 3

六、使用表单的POST方法实例

针对上述Servlet做一些改动,以便她好拍卖GET方法及POST方法。下面是HelloForm.java
Servlet程序,使用GET和POST方法处理由Web浏览器被来之输入。

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
  // Method to handle GET method request.
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String title = "Using GET Method to Read Form Data";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n" +
                "<ul>\n" +
                "  <li><b>First Name</b>: "
                + request.getParameter("first_name") + "\n" +
                "  <li><b>Last Name</b>: "
                + request.getParameter("last_name") + "\n" +
                "</ul>\n" +
                "</body></html>");
  }
  // Method to handle POST method request.
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     doGet(request, response);
  }
}

今天编译,部署上述Servlet,并应用含POST方法的Hello.htm测试其,如下所示:

<html>
<body>
<form action="HelloForm" method="POST">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

眼看是上述表单的其实出口,尝试输入人名,然后点击提交按钮,在 tomcat
运行的当地电脑达查看结果。

图片 4

冲提供的输入,它见面时有发生和上述例子中一般之结果。

图片 5

七、将复选框数据传递至Servlet程序

当要摘多独挑选时,就要用复选框。

及时是一个HTML代码实例,CheckBox.htm,一个表单带有两个复选框。

<html>
<body>
<form action="CheckBox" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics"  /> Physics
<input type="checkbox" name="chemistry" checked="checked" /> 
                                                Chemistry
<input type="submit" value="Select Subject" />
</form>
</body>
</html>

旋即段代码的结果是之类所著之表单:

图片 6

下面是CheckBox.java Servlet程序,来也复选框按钮处理Web浏览器给定的输入。

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class CheckBox extends HttpServlet {
  // Method to handle GET method request.
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String title = "Reading Checkbox Data";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n" +
                "<ul>\n" +
                "  <li><b>Maths Flag : </b>: "
                + request.getParameter("maths") + "\n" +
                "  <li><b>Physics Flag: </b>: "
                + request.getParameter("physics") + "\n" +
                "  <li><b>Chemistry Flag: </b>: "
                + request.getParameter("chemistry") + "\n" +
                "</ul>\n" +
                "</body></html>");
  }
  // Method to handle POST method request.
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     doGet(request, response);
  }
}

配置web.xml:

    <servlet>
        <servlet-name>CheckBox</servlet-name>
        <servlet-class>com.jsoft.testservletbasics.CheckBox</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CheckBox</servlet-name>
        <url-pattern>/CheckBox</url-pattern>
    </servlet-mapping>

点的实例将展示如下所示结果:

图片 7

八、读取所有的表单参数

以下是运HttpServletRequest的getParameterNames()方法的通用实例来读取所有可用的表单参数。该措施返回一个枚举,包含了未指定顺序的参数名称。

若得一个枚举,可以坐规范方法循环是枚举,使用hasMoreElements()方法来规定何时休循环,使用nextElement()方法来获取每个参数的称谓。

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
public class ReadParams extends HttpServlet {
  // Method to handle GET method request.
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String title = "Reading All Form Parameters";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
        "<html>\n" +
        "<head><title>" + title + "</title></head>\n" +
        "<body bgcolor=\"#f0f0f0\">\n" +
        "<h1 align=\"center\">" + title + "</h1>\n" +
        "<table width=\"100%\" border=\"1\" align=\"center\">\n" +
        "<tr bgcolor=\"#949494\">\n" +
        "<th>Param Name</th><th>Param Value(s)</th>\n"+
        "</tr>\n");
      Enumeration paramNames = request.getParameterNames();      
      while(paramNames.hasMoreElements()) {
         String paramName = (String)paramNames.nextElement();
         out.print("<tr><td>" + paramName + "</td>\n<td>");
         String[] paramValues =
                request.getParameterValues(paramName);
         // Read single valued data
         if (paramValues.length == 1) {
           String paramValue = paramValues[0];
           if (paramValue.length() == 0)
             out.println("<i>No Value</i>");
           else
             out.println(paramValue);
         } else {
             // Read multiple valued data
             out.println("<ul>");
             for(int i=0; i < paramValues.length; i++) {
                out.println("<li>" + paramValues[i]);
             }
             out.println("</ul>");
         }
      }
      out.println("</tr>\n</table>\n</body></html>");
  }
  // Method to handle POST method request.
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     doGet(request, response);
  }
}

配置web.xml:

    <servlet>
        <servlet-name>ReadParams</servlet-name>
        <servlet-class>com.jsoft.testservletbasics.ReadParams</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ReadParams</servlet-name>
        <url-pattern>/ReadParams</url-pattern>
    </servlet-mapping>

今天,用底的表单尝试上述Servlet:

<html>
<body>
<form action="ReadParams" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics"  /> Physics
<input type="checkbox" name="chemistry" checked="checked" /> Chem
<input type="submit" value="Select Subject" />
</form>
</body>
</html>

现行采取上述表单调用Servlet将发生如下所示结果:

图片 8

图片 9

 

测试工程:https://github.com/easonjim/5_java_example/tree/master/servletbasics/test2

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图