JQuery добавляет имя сервлета дважды в URL - PullRequest
0 голосов
/ 21 апреля 2009

Я пытаюсь завершить урок на http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=438

Похоже, что сервлет пытается отправить данные в http://localhost:8080/WeatherServlet/WeatherServlet ... (WeatherServlet - это имя сервлета - дух).

У меня есть следующая страница index.jsp (которая отображается нормально)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript">
   $(document).ready(function() {
          $("#getWeatherReport").click(function(){
            $cityName = document.getElementById("cityName").value;
            $.post("WeatherServlet", {cityName:$cityName}, function(xml) {
           $("#weatherReport").html(
             $("report", xml).text()
           );         
            });
        });

    });
</script>
</head>
<body>
<form name="form1" type="get" method="post">
Enter City :
    <input type="text" name="cityName" id="cityName" size="30" />
    <input type="button" name="getWeatherReport" id="getWeatherReport"
    value="Get Weather" />
</form>
<div id="weatherReport" class="outputTextArea">
</div>
</body>
</html>

Следующая страница WeatherReport.java

package org.ajax.tutorial;

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;

/**
* Servlet implementation class WeatherReport
*/
public class WeatherReport extends HttpServlet {
    private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public WeatherReport() {
    super();
    // TODO Auto-generated constructor stub
}

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

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String city = request.getParameter("cityName");
    String report = getWeather(city);
    response.setContentType("text/xml");
    PrintWriter out = response.getWriter();
    out.println("<weather><report>" + report + "</report></weather>");
    out.flush();
    out.close();
}

private String getWeather(String city) {
    String report;

    if (city.toLowerCase().equals("trivandrum"))
        report = "Currently it is not raining in Trivandrum. Average temperature is 20";
    else if (city.toLowerCase().equals("chennai"))
        report = "It’s a rainy season in Chennai now. Better get a umbrella before going out.";
    else if (city.toLowerCase().equals("bangalore"))
        report = "It’s mostly cloudy in Bangalore. Good weather for a cricket match.";
    else
        report = "The City you have entered is not present in our system. May be it has been destroyed "
                + "in last World War or not yet built by the mankind";
    return report;
}

}

Следующая страница web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
     xmlns="http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
 <servlet>
    <description>Weather Data provider</description>
    <display-name>Weather Data provider</display-name>
    <servlet-name>WeatherServlet</servlet-name>
<servlet-class>ajaxify.WeatherServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>WeatherServlet</servlet-name>
    <url-pattern>/WeatherServlet</url-pattern>
  </servlet-mapping>

</web-app>

Я создаю WAR-архив и внедряю его с помощью встроенных инструментов Eclipse (не ant - сомневаюсь, что это важно).

Ответы [ 2 ]

3 голосов
/ 21 апреля 2009

Вы публикуете «WeatherServlet» в jQuery, который является относительным URL-адресом, а исходный URL-адрес равен http://server.com/WeatherServlet/index.jsp,, поэтому неудивительно, что созданный им URL-адрес равен http://server.com/WeatherServlet/WeatherServlet

.

Изменить

$.post("WeatherServlet", {cityName:$cityName}, function(xml) {

до

$.post("index.jsp", {cityName:$cityName}, function(xml) {

или любой другой jsp, на который вы хотите отправить сообщение.

2 голосов
/ 21 апреля 2009

Я думаю, что проблема в том, что вы заходите на страницу в

http://localhost:8080/WeatherServelet/

и затем вы отправляете сообщение: $ .post ("WeatherServlet", ...

, который является относительным путем, поэтому вы в конечном итоге отправляете на

http://localhost:8080/WeatherServelet/WeatherServelet

Вы должны попытаться отправить по абсолютному пути:

$.post("/WeatherServlet", ...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...