基本上我想在Tomcat的8个内置的运行一些休息的类。 我不确定如何将它们添加到我创建tomcat的嵌入式实例。 所以这是我做的。 这里只是泽西类:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import static javax.ws.rs.core.MediaType.*;
@Path("register")
public class RegisterRestAPI {
private MerchantRegistrationService merchantRegistrationService;
public RegisterRestAPI(MerchantRegistrationService merchantRegistrationService) {
this.merchantRegistrationService = merchantRegistrationService;
}
@GET
@Produces(TEXT_PLAIN)
public String register() {
return "Hello!!!!";
}
}
这里是我创建的Tomcat类:
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.init.JerseyServletContainerInitializer;
import javax.servlet.ServletException;
import java.io.File;
public class TomcatServer {
private MerchantRegistrationService merchantRegistrationService;
public TomcatServer(MerchantRegistrationService merchantRegistrationService)
{
this.merchantRegistrationService = merchantRegistrationService;
}
public void start() throws ServletException, LifecycleException {
String webappDirLocation = "restui/src/main/webapp/";
Tomcat tomcat = new Tomcat();
String webPort = System.getenv("PORT");
if(webPort == null || webPort.isEmpty()) {
webPort = "8080";
}
tomcat.setPort(Integer.valueOf(webPort));
Context context = tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
tomcat.addServlet(context,"jersey-container-servlet",resourceConfig());
context.addServletMapping("/register", "registration rest");
tomcat.start();
tomcat.getServer().await();
}
private ServletContainer resourceConfig() {
return new ServletContainer(new ResourceConfig().register(new
RegisterRestAPI(merchantRegistrationService)));
}
}
所以当你看到与问号是给我找麻烦创建零件。 此外,只有一个拉特的问题,这是我要补充这些类在服务器上运行正确的方法是什么?
更新我加入由米哈尔Gajdos建议行,但在启动时,我得到:
例外在线程“主” java.lang.IllegalArgumentException异常:servlet映射指定了在org.apache.catalina.core.StandardContext.addServletMapping(StandardContext.java:3160)在org.apache.catalina.core.StandardContext未知servlet名称注册其余.addServletMapping(StandardContext.java:3139)在com.crypto.restui.TomcatServer.start(TomcatServer.java:44)在com.crypto.assembler.Boot.main(Boot.java:22)在sun.reflect.NativeMethodAccessorImpl。 invoke0(本机方法)在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)在java.lang.reflect.Method.invoke(Method.java: 606)在com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
我应该如何调用servlet?