杰瑞科技汇

Java6如何开发webservice?

Of course. Let's dive into Java 6 Web Services. This is a topic rooted in a specific era of Java EE, and understanding it requires looking at the two primary technologies available at the time.

The Big Picture: Java 6 Web Service Landscape

Java 6 (released in 2006) was a dominant force in enterprise computing. The Java EE 5 platform, which was the standard for Java 6, introduced significant simplifications for web services. There were two main, competing (and often complementary) specifications:

  1. JAX-WS (Java API for XML Web Services): This was the standard and recommended way to create SOAP-based web services in Java 6. It was a major evolution from the older JAX-RPC. JAX-WS used annotations heavily, making development much simpler than before.
  2. JAX-RS (Java API for RESTful Web Services): This was the newcomer and the official standard for REST services. It was first introduced in Java EE 6 (2009), but it was backported and very popular in the Java 6 ecosystem via projects like Jersey and RESTEasy.

For most "Java 6 Web Service" discussions, people are referring to JAX-WS for SOAP services. We will cover both.


JAX-WS (SOAP Web Services) - The Workhorse

JAX-WS was the go-to technology for building robust, contract-first, enterprise-grade web services that used the SOAP protocol. Its key features were:

  • Annotation-Driven: You could define a web service endpoint by simply adding annotations like @WebService, @WebMethod, and @WebParam to a plain Java class (a POJO).
  • Standardized: It was part of the Java EE 5/6 standard, so it was supported by all major application servers (WebLogic, WebSphere, JBoss) and servlet containers (Tomcat, with the right libraries).
  • Tooling Support: The wsimport command-line tool was essential. It could take a WSDL (Web Services Description Language) file and generate all the necessary Java client-side (and server-side) stubs and skeletons.

Key JAX-WS Annotations in Java 6

Annotation Used On Purpose
@WebService A class or interface Marks the class as a web service endpoint. You specify the serviceName and endpointInterface.
@WebMethod A method Marks a method as being part of the web service contract. You can exclude it with operationName or exclude=true.
@WebParam A method parameter Allows you to customize the name and other properties of the parameter in the WSDL.
@WebResult A method return value Allows you to customize the name and other properties of the return value in the WSDL.

Example: A Simple JAX-WS "Hello World" Service

Let's create a service that takes a name and returns a greeting.

Step 1: Create the Service Endpoint Interface (SEI)

This is a best practice. It defines the contract for your service.

// src/com/example/HelloWorld.java
package com.example;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
// The @WebService annotation signals this is a web service interface.
// style = SOAPBinding.Style.RPC is a common style for simple services.
@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface HelloWorld {
    // The @WebMethod annotation exposes this method as part of the web service.
    @WebMethod
    String sayHello(@WebParam(name = "name") String name);
}

Step 2: Create the Service Implementation Bean (SIB)

This is the actual Java class that implements the interface.

// src/com/example/HelloWorldImpl.java
package com.example;
import javax.jws.WebService;
// The endpointInterface links this implementation to the SEI.
@WebService(endpointInterface = "com.example.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
    @Override
    public String sayHello(String name) {
        return "Hello, " + name + "!";
    }
}

Step 3: Deploy the Service

In a Java 6 environment, you would typically deploy this inside a web application (a .war file). You'd need a web.xml file and a servlet to act as the "front end" for your service.

web.xml:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <servlet>
        <servlet-name>HelloWorld</servlet-name>
        <!-- This is the special JAX-WS servlet that routes requests -->
        <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    <!-- You also need to configure the service implementation -->
    <listener>
        <listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
    </listener>
    <context-param>
        <param-name>service</param-name>
        <param-value>com.example.HelloWorldImpl</param-value>
    </context-param>
</web-app>

After building this into a hello-service.war file and deploying it to a server like Tomcat (with the JAX-WS libraries like jaxws-rt.jar in its lib directory), you could access the WSDL at:

http://localhost:8080/hello-service/hello?wsdl


JAX-RS (REST Web Services) - The Modern Challenger

While JAX-WS was the established standard, the REST architectural style was gaining immense popularity. JAX-RS was created to provide a clean, annotation-driven API for building RESTful services.

In Java 6, you didn't get JAX-RS from the core JDK. You had to use an implementation. The two most popular were:

  • Jersey: The reference implementation from Oracle/Sun.
  • RESTEasy: The JBoss project's implementation.

Key JAX-RS Annotations in Java 6

Annotation Used On Purpose
@Path A class or method Defines the URI path for the resource or a sub-path for a method.
@GET, @POST, @PUT, @DELETE A method Specifies the HTTP method that the method should respond to.
@Produces A method Defines the MIME media types that the method can produce (e.g., application/json, text/xml).
@Consumes A method Defines the MIME media types that the method can consume.
@PathParam Method parameter Binds a method parameter to a URI path parameter.
@QueryParam Method parameter Binds a method parameter to an HTTP query parameter.

Example: A Simple JAX-RS (Jersey) "Hello World" Service

Step 1: Add Jersey Library

You need to include the Jersey libraries in your project. For a Maven project, this would be:

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-server</artifactId>
    <version>1.19.4</version> <!-- A common version for Java 6 -->
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-servlet</artifactId>
    <version>1.19.4</version>
</dependency>

Step 2: Create the Resource Class

// src/com/example/HelloResource.java
package com.example;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
// The @Path annotation defines the base URI for this resource.
@Path("/hello")
public class HelloResource {
    // The @GET annotation means this method responds to HTTP GET requests.
    // @Path("/{name}") defines a sub-path with a parameter.
    // @PathParam("name") injects the value from the URI into the 'name' variable.
    // @Produces defines that this method returns plain text.
    @GET
    @Path("/{name}")
    @Produces(MediaType.TEXT_PLAIN)
    public String sayHello(@PathParam("name") String name) {
        return "Hello, " + name + "!";
    }
}

Step 3: Configure in web.xml

You need to register the Jersey servlet and tell it where to find your resource classes.

<web-app ...>
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.example</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

After deploying, you could access this service at:

http://localhost:8080/hello-service/rest/hello/World

This would return the plain text: Hello, World!


Key Differences: JAX-WS vs. JAX-RS in Java 6

Feature JAX-WS (SOAP) JAX-RS (REST)
Style Service-Oriented Architecture (SOA) Representational State Transfer (REST)
Protocol SOAP (XML-based, over HTTP/SMTP/etc.) HTTP (GET, POST, PUT, DELETE)
Contract Strict WSDL contract-first or code-last Loosely defined, URI-based, often with OpenAPI/Swagger
Data Format Primarily XML, but also JSON possible Primarily JSON, XML, HTML, plain text
State Stateless (by design) Can be stateless or leverage state (e.g., cookies)
Use Cases Enterprise Integration, B2B transactions, WS-* Security Public APIs, Mobile backends, AJAX frontends

Why You Should Be Careful Today (The "But...")

While Java 6 was a great platform, it is ancient by modern standards and is no longer supported.

  1. End of Life (EOL): Oracle stopped public updates for Java 6 in 2025. This means no security patches. Running it in production is a massive security risk.
  2. No Modern Features: You miss out on a decade of Java improvements (lambdas, Streams, a vastly improved module system, etc.).
  3. Legacy Code: If you are maintaining a Java 6 web service, your goal should be to migrate it to a modern Java version (Java 11, 17, or 21).
  4. Deprecated Libraries: The libraries used (like the reference implementation for JAX-WS) are old and may have vulnerabilities or compatibility issues with modern systems.

How to Migrate from Java 6 Web Services

  1. Upgrade the JDK: The first step is to move to a supported LTS (Long-Term Support) version of Java, like Java 11 or 17. The code is largely portable.
  2. Re-evaluate the Architecture: This is the most important step.
    • If you have a SOAP service, ask: "Does it need to be SOAP?" If it's used for internal integration, it might be fine. If it's a public-facing API, migrating to a REST/JSON-based service is almost always a better choice today.
    • If you have a REST service, great! You're already on the right track.
  3. Update Dependencies:
    • For JAX-WS, the API is standard (jakarta.xml.ws.* or javax.xml.ws.*), but the implementation might need updating. The reference implementation is now part of Jakarta EE.
    • For JAX-RS, the API is now jakarta.ws.rs.*. You would migrate from Jersey 1.x to Jersey 2/3 or to a different modern implementation like RESTEasy or Quarkus.
  4. Modernize the Code: Refactor the code to use modern Java features. The annotations and core logic will likely remain very similar, but the surrounding code can be improved significantly.

Conclusion

In Java 6, you had two powerful tools for web services:

  • JAX-WS for robust, contract-first SOAP services.
  • JAX-RS (via Jersey/RESTEasy) for flexible, modern REST services.

Understanding these technologies is key to maintaining legacy systems. However, due to the severe security risks and lack of support for Java 6 itself, any new development or maintenance should focus on migrating to a modern Java version and re-evaluating the choice of web service architecture for the current technology landscape.

分享:
扫描分享到社交APP
上一篇
下一篇