【问题标题】:REST service with Spring 3 on JDK6 HTTP Server在 JDK6 HTTP 服务器上使用 Spring 3 的 REST 服务
【发布时间】:2012-04-05 22:00:49
【问题描述】:

是否有可能在没有 servlet 容器的情况下使用 spring 3.0 创建 REST 服务?因为我不想使用应用服务器。 我尝试使用 SimpleHttpInvokerServiceExporter 和 Spring MVC 创建 REST 服务,但我得到了 java.lang.NoClassDefFoundError: javax/servlet/ServletException,因为我不使用 servlet 容器。我的代码如下所示:

<beans>
  ...
    <bean name="serviceFacadeExporter" 
       class="org.springframework.remoting.httpinvoker.SimpleHttpInvokerServiceExporter">
        <property name="service" ref="serviceFacade" />
        <property name="serviceInterface" value="facade.ServiceFacade" />
    </bean>
    <bean id="httpServer"
        class="org.springframework.remoting.support.SimpleHttpServerFactoryBean">
            <property name="contexts">
                <map>
                    <entry key="/api/" value-ref="serviceFacadeExporter" />
                </map>
            </property>
             <property name="port" value="8082" />
    </bean>
   ...
</beans>

服务看起来像这样

@Controller
public class ServiceFacadeImpl implements ServiceFacade {

  @Override
  @RequestMapping(value = "/protein/search/{searchString}")
  public long searchProtein(@PathVariable String searchString) {
    return 0;
  }
}

【问题讨论】:

  • 第一个 REST 意味着 HTTP。所以你需要 servlet 容器来服务你的 REST 请求。
  • 我想使用 Jdk6 Http 服务器。所以我有没有 servlet 容器的 http。
  • 为什么不想在 servlet 容器中运行?

标签: java spring rest spring-mvc simplehttpserver


【解决方案1】:

Spring MVC 需要 Servlet API

您可以通过以下方式使用 JSE 6 HTTP Server 创建 Simple Rest Service

你创建一个资源类

@Path("/helloworld")
public class MyResource {

    // The Java method will process HTTP GET requests
    @GET
    // The Java method will produce content identified by the MIME Media
    // type "text/plain"
    @Produces("text/plain")
    public String getClichedMessage() {
        // Return some cliched textual content
        return "Hello World";
    }
}

你创建一个 Rest 应用程序

public class MyApplication extends javax.ws.rs.core.Application{
    public Set<Class<?>> getClasses() {
        Set<Class<?>> s = new HashSet<Class<?>>();
        s.add(MyResource.class);
        return s;
    }
}

这就是你启动服务器的方式

HttpServer server = HttpServer.create(new InetSocketAddress(8080), 25);
HttpContext context = server.createContext("/resources");
HttpHandler handler = RuntimeDelegate.getInstance().createEndpoint
(new MyApplication(), HttpHandler.class);
context.setHandler(handler);
server.start(); 

就是这样。不需要 Spring MVC。

出于测试目的,这非常有效,对于许多请求的高效使用,我会使用像 Jetty 或 Tomcat 这样的 WebContainer。

可以找到关于如何使用标准 JSE 6 HttpServer 构建 RESTFul 的更详细说明 RESTFul Webservice mit JAX-RS(德语)

【讨论】:

  • 感谢这对我有很大帮助,但如果有办法通过 spring 远程处理解决这个问题会很有趣。
  • 是的...第二个,我也希望看到 Spring 和 Spring MVC 解决了这个问题。
  • Spring 确实需要 Servlet API,而且似乎不是为更简单的 REST 无状态服务而设计的。如果你确实希望它在一个简单的服务器上运行,你需要在没有框架的情况下开发它。
猜你喜欢
  • 2017-10-31
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
  • 2020-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-29
相关资源
最近更新 更多