first need to import jquery.js Baidu jquery into the official website download on the line note to be placed under the Web-inf
Front-end code:
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "
pageencoding= "UTF-8"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>insert title here</title>
<script src= "/ajax/js/jquery-1.11.0.min.js" ></script>
<script type= "Text/javascript" >
function Ajaxfun () {
$.ajax ({
Type: "POST",//The way data is transmitted
URL: "Testservlet",//servlet address
Data: $ (' #form '). Serialize () and//data passed in form
Success:function (Result) {///pass data after successful operation result is the data from the servlet. This function processes the result so that it appears in the input box
$ ("#result"). Val (result); Find the input box and pass in the value of result
}
});
}
</script>
<body>
<H1 align= "center" > Please enter two strings </H1>
<div align= "center" >
<form id= "Form" >
First:<input type= "text" name= "first" id= "First" >
Second:<input type= "text" name= "second" id= "second" >
<button type= "button" onclick= "Ajaxfun ()" >button</button>//Submit button
</form>
<input type= "text" id= "result" >//used to display result
</div>
</body>
servlet Code:
Package Ajax;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import java.io.*;
public class Testservlet extends httpservlet{
public void DoPost (HttpServletRequest request,httpservletresponse response) throws ioexception,servletexception{
Response.setcontenttype ("text/html");
Request.setcharacterencoding ("Utf-8");
Response.setcharacterencoding ("UTF-8");
PrintWriter out = Response.getwriter ();
String first = Request.getparameter ("First"); Get data first from the front
String second = Request.getparameter ("second");//Get data from the front end second
String Result=first+second;
SYSTEM.OUT.PRINTLN (result); Used for testing, to determine whether to obtain data successfully;
OUT.PRINTLN (result); Uploading data to the front end
}
public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
DoPost (request, response);
}
}