You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java类调用Web服务返回至JSP?温度转换工具开发及代码验证求助

Troubleshooting Your Temperature Conversion Service Integration

Hey there! Let's break this down step by step to get your JSP-to-Java Web Service integration working smoothly. I'll cover form validation, proper service invocation, and parameter matching so you can connect the dots easily.

1. Validating Your JSP Form

First, let's make sure your JSP form is set up to pass the right data to your Java class. A solid form should capture the temperature value and the conversion direction (e.g., Fahrenheit → Celsius or vice versa). Here's a tested example:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>Temperature Converter</title>
</head>
<body>
    <h1>Temperature Conversion</h1>
    <form method="POST" action="TemperatureConverterServlet">
        <label for="temperature">Enter Temperature:</label>
        <input type="number" step="0.1" id="temperature" name="temperature" required>
        
        <label for="conversionType">Convert To:</label>
        <select id="conversionType" name="conversionType" required>
            <option value="F_TO_C">Fahrenheit to Celsius</option>
            <option value="C_TO_F">Celsius to Fahrenheit</option>
        </select>
        
        <button type="submit">Convert</button>
    </form>
</body>
</html>

Key checks for your form:

  • Use POST method (safer for data submission than GET)
  • Name attributes (temperature, conversionType) should match the parameter names your Java class will read
  • Include validation (like required and type="number") to ensure valid input
  • The action points to your Java servlet/handler class (adjust the name to match your project setup)

2. Correctly Calling the Web Service from Java

The approach depends on whether your temperature service is SOAP or REST. Let's cover both common scenarios:

Case 1: SOAP Web Service

If your service uses WSDL (common for enterprise services), use JAX-WS to generate client code first:

  1. Run wsimport -keep http://your-service-url?wsdl in your terminal—this creates Java classes for the service.
  2. In your handler class, use the generated code to invoke the service:
import com.your.temperature.service.TemperatureService;
import com.your.temperature.service.TemperatureConverter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class TemperatureConverterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // Get form parameters
        double inputTemp = Double.parseDouble(request.getParameter("temperature"));
        String conversionType = request.getParameter("conversionType");
        
        // Initialize SOAP service client
        TemperatureService service = new TemperatureService();
        TemperatureConverter port = service.getTemperatureConverterPort();
        
        // Call the service method (adjust method name/params to match your service)
        double result;
        if ("F_TO_C".equals(conversionType)) {
            result = port.fahrenheitToCelsius(inputTemp);
        } else {
            result = port.celsiusToFahrenheit(inputTemp);
        }
        
        // Pass result back to JSP
        request.setAttribute("result", result);
        try {
            request.getRequestDispatcher("result.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Case 2: REST Web Service

For a REST-based service (using JSON/XML), use HttpURLConnection to send a request:

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class TemperatureConverterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        double inputTemp = Double.parseDouble(request.getParameter("temperature"));
        String conversionType = request.getParameter("conversionType");
        
        // Build service URL (adjust to your service's endpoint)
        String serviceUrl = "http://your-rest-service-url/convert?";
        if ("F_TO_C".equals(conversionType)) {
            serviceUrl += "temp=" + inputTemp + "&unit=F";
        } else {
            serviceUrl += "temp=" + inputTemp + "&unit=C";
        }
        
        // Send request and parse response
        URL url = new URL(serviceUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String resultStr = in.readLine();
        double result = Double.parseDouble(resultStr);
        
        // Forward result to JSP
        request.setAttribute("result", result);
        try {
            request.getRequestDispatcher("result.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3. Ensuring Parameter Matching

Double-check these critical points to avoid mismatches:

  • Your JSP form's name attributes must exactly match the parameter names your Java class reads with request.getParameter()
  • The data types must align: if the Web service expects a double for temperature, parse the form string to double (don't pass raw text)
  • If the service expects specific values for conversion type (e.g., "F" instead of "F_TO_C"), adjust your form's option values to match exactly

内容的提问来源于stack exchange,提问作者Luiz Wynne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:39:14