The example interprets the way Ajax interacts with servlets

  • 2020-04-01 03:25:17
  • OfStack

This article dissects the interaction between Ajax and servlets in the form of an example, with detailed comments in the code to help you understand. The specific implementation method is as follows:

1. The JavaScript section


var req;
 
 var url;
 function getResult()
 { 
  var f=document.getElementById("form_pub");
  var key=f.s.options[f.s.selectedIndex].text; //Gets a reference to the select text
 if (window.XMLHttpRequest)
 {
  req = new XMLHttpRequest();
  url = "ajaxServlet?action="+key+"&bm=UTF-8";
 }else if (window.ActiveXObject)
 {
 
  req = new ActiveXObject("Microsoft.XMLHTTP");
  url = "ajaxServlet?action="+key+"&bm=gbk";
 }
 if(req)
 { 
  req.open("GET",url, true); 
  req.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
  //Here, if the header is not set, firfox will send data error, servlet received parameters are garbled, in IE normal
  req.onreadystatechange = complete; 
  req.send(null);
  //req.setRequestHeader("Content-Type", "text/xml; charset=UTF-8"); 
 }
 }
 
 function complete(){
 if (req.readyState == 4)
 {
  if (req.status == 200)
  {
   var items=document.getElementById("belong");
  //The following is the XML document returned by parsing
   var xmlDoc = req.responseXML;
   var Node=xmlDoc.getElementsByTagName("type_name");
   //var str=new Array();
    var str=null;
    //Empty the work
    items.innerHTML=""; //Deletes the entire contents of a select
 for(var i=0;i<Node.length;i++)
    { 
     str=Node[i];
     //alert(str.childNodes[0].nodeValue);
     var objectOption=document.createElement("option");
      items.options.add(objectOption);
     //Firfox does not support innerText but instead must use textContent
      if (window.ActiveXObject)
      {objectOption.innerText=str.childNodes[0].nodeValue;}
      else
      {objectOption.textContent=str.childNodes[0].nodeValue;}
    }
   }
  }
 }

2. The servlet end:


package ajax;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Data_GetConn.GetConn;//This package was written by itself to get a reference to mysql
import java.sql.*;//This bag must have!!


public class ajaxServlet extends HttpServlet{
 //private static final String CONTENT_TYPE = "text/xml; charset=UTF-8";// It's best to use it uniformly here UTF-8 coding 
 public void init() throws ServletException{}
 public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
 {
 response.setContentType("text/xml; charset=UTF-8");
 //The following two sentences are to cancel the local cache
 response.setHeader("Cache-Control", "no-cache");
  response.setHeader("Pragma", "no-cache");
 PrintWriter out = response.getWriter();
 String action = request.getParameter("action");
 String bm = request.getParameter("bm");
 
 if(("gbk").equals(bm))
 {
  action=new String(action.getBytes("ISO-8859-1"),"gbk");//The obtained data with GBK new code! (thanks to Mr. Dong wei)
 }
 else
 {
   action=new String(action.getBytes("ISO-8859-1"),"gbk");
 }
 try
  {
   GetConn wq=new GetConn();
   Connection   con=wq.getCon();
   Statement stmt=con.createStatement();
   ResultSet rs=stmt.executeQuery("select items from class where main='"+action+"'");
   StringBuffer sb = new StringBuffer();
    sb.append("<type>");
   while(rs.next())
   {
      
   sb.append("<type_name>"+rs.getString(1)+"</type_name>");
     
   }
    //sb.append("<type_name>"+action+"</type_name>");
    sb.append("</type>"); 
    out.write(sb.toString());//Notice the intercepting method in script for the stream output to the JSP
    out.close();
    stmt.close();
    con.close();
  }
  catch(Exception ex)
  {
     
  }
 
 }
}

Related articles: