Java类调用Web服务返回至JSP?温度转换工具开发及代码验证求助
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
POSTmethod (safer for data submission than GET) - Name attributes (
temperature,conversionType) should match the parameter names your Java class will read - Include validation (like
requiredandtype="number") to ensure valid input - The
actionpoints 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:
- Run
wsimport -keep http://your-service-url?wsdlin your terminal—this creates Java classes for the service. - 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
nameattributes must exactly match the parameter names your Java class reads withrequest.getParameter() - The data types must align: if the Web service expects a
doublefor temperature, parse the form string todouble(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
optionvalues to match exactly
内容的提问来源于stack exchange,提问作者Luiz Wynne

