Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Servlet to process AJAX requests

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces in detail "how to use Servlet to handle AJAX requests". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to use Servlet to deal with AJAX requests" can help you solve your doubts.

AJAX is used to update local content of a page asynchronously.

Request data types commonly used in ajax

Text plain text string

Json json data

Use ajax to get the text sample

This method is often used in the front end to query an attribute (field) of the entity to the background, such as querying the total score.

Front-end page student number: name: query results

Click ("# btn") .click (function () {$.ajax ({url: "servlet/HandlerServlet", / / request address type: "get", / / request method data: {"no": $("# no"). Val (), "name": $("# name"). Val ()}, / / the data to be sent is equivalent to the data submitted by the form, in json form. DataType: "text", / / the data type expected to be returned can also be understood as the requested data type error:function () {/ / processing in case of error}, success:function (data) {/ / processing in case of success. Parameter represents the returned data $("# score") .text (data);}})})

The ajax method provided by jq is used here, so you want to include the library file of jq.

The key of json can only be a string. If you want to quote it in standard writing, you can actually not quote it, and it will be automatically converted to a string.

The value of json can be of multiple data types, and if it is a string, it needs to be quoted.

Background @ WebServlet ("/ servlet/HandlerServlet") public class HandlerServlet extends HttpServlet {protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request,response);} protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding ("utf-8"); response.setContentType ("text/html;charset=utf-8") / / get the parameters passed by ajax in the same way as String no=request.getParameter ("no"); String name=request.getParameter ("name"); / / omit the connection database query here and directly return the score PrintWriter writer = response.getWriter (); writer.write (name+ "classmate, your total score is: 600");}} description

The url requested by ajax should correspond to the urlPatterns configured by servlet, which is easy to make mistakes.

When servlet returns a response, no matter how many times write () is returned, only one response is returned.

PrintWriter writer = response.getWriter (); writer.write ("China"); writer.write ("Beijing"); PrintWriter writer = response.getWriter (); writer.write ("Beijing")

These two methods are completely equivalent, the browser receives "Beijing, China", and there is no space between "China" and "Beijing".

Use ajax to get a json object example

This method is often used in the background to send an entity to the front end | JavaBean (multiple fields of an entity), such as querying a student's information.

Front-end student number: query student information

("# btn") .click (function () {$.ajax ({url: "servlet/HandlerServlet", type: "post", data: {}, dataType: "json", error:function () {console.log ("ajax failed to request data!") ;}, success: function (data) {/ / the browser takes the received json data as a js object. Call attribute var info = "name:" + data.name + ", age:" + data.age + ", score:" + data.score; $("# show") .text (info); console.log (data);}})})

Backstage

@ WebServlet ("/ servlet/HandlerServlet") public class HandlerServlet extends HttpServlet {protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request,response);} protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding ("utf-8"); response.setContentType ("text/html;charset=utf-8") / / get the parameters passed by ajax, String no=request.getParameter ("no") in the same way as form data; / / now many persistence layer frameworks convert the records returned from the database into JavaBean processing / / omit the connection database query here, and get the Student class instance Student student = new Student (1, "Zhang San", 20,100). / / use fastjson to convert the java object to the json string String jsonStr = JSON.toJSONString (student); PrintWriter writer = response.getWriter (); writer.write (jsonStr);}}

JSON.toJSONString () uses Ali's fastjson.jar, and you need to download and add this jar yourself.

Use ajax to get the json array

This method is used to return multiple instances of the same entity class to the front end, such as querying the information of students whose total score is greater than 600. Multiple records may meet the requirements.

The front end queries the information of the first three students $("# btn") .click (function () {$.ajax ({url: "servlet/HandlerServlet", type: "post", data: {}, dataType: "json", error:function () {console.log ("ajax failed to request data!") ;}, success: function (data) {console.log (data); / / traversing the json array for (var iTuno

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report