gpt4 book ai didi

java - 如何配置我的 servlet 来发送 Ajax 请求

转载 作者:行者123 更新时间:2023-12-01 06:14:19 29 4
gpt4 key购买 nike

我正在使用一个 servlet,其 URL 名称是通用的。我将一些表单参数发送到 servlet,然后用 Java 处理它们。但是如何配置我的 servlet 来发送 Ajax 请求,例如 getRecords.ajax 或 getAnother.ajax。也就是说,我想发送所有 *.ajax > 到我的 servlet。

然后我想在我的 servlet 中像这样处理;

public getAnother (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO
return JSONObject
}

不在doGet中。

我的 servlet 也像这样(一个示例 servlet):

package com.domain;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class General
*/
@WebServlet("/General")
public class General extends HttpServlet {
private static final long serialVersionUID = 1L;

private String message;
/**
* Default constructor.
*/
public General() {
// TODO Auto-generated constructor stub
}

/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
message = "Hello World";
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
String colorName=request.getParameter("color");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
out.println("<br><h2>"+colorName+"</h2>");
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

最佳答案

Servlet 映射可用于服务器特定 URL。这是通过 URL 模式完成的

@WebServlet(urlPatterns="/General/*.ajax")

现在您可以使用/General/getRecords.ajax/General/getAnother.ajax

Use the @WebServlet annotation to define a servlet component in a web application. This annotation is specified on a class and contains metadata about the servlet being declared. The annotated servlet must specify at least one URL pattern. This is done by using the urlPatterns or value attribute on the annotation. All other attributes are optional, with default settings. Use the value attribute when the only attribute on the annotation is the URL pattern; otherwise use the urlPatterns attribute when other attributes are also used.

关于java - 如何配置我的 servlet 来发送 Ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27971467/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com