встроенная пристань для перехода от сервлета к jsp

Я пытаюсь заставить свой встроенный сервлет причала выполнить некоторую обработку, а затем передать управление JSP, который сгенерирует страницу результатов.

Сервлет отображается и вызывается правильно, однако ему не удается найти JSP. Поскольку я использую встроенный причал, у меня нет ни файла web.xml, ни войны. Может быть, это означает, что причал не знает, где искать мой JSP или что-то в этом роде. Если это так, как я могу сказать eclipse / jetty, где это найти, или что-то мне не хватает в том, как я вызываю форвард.

N.B. Я использую обычный проект maven, поэтому мне пришлось самому создать папку WEB-INF. Может быть, это ключ к разгадке !?

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.core.io.ClassPathResource;

public class RunHelloServlet {

public static void main(String[] args) throws Exception {
    Server server = new Server(8080);

    ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);

    contextHandler.setContextPath(".");
    server.setHandler(contextHandler);

    contextHandler.addServlet(new ServletHolder(new HelloServlet()), "/hello");

    server.start();
    server.join();
}

public static class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public HelloServlet() {
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String par1 = request.getParameter("par1");
        request.setAttribute("key", par1);

        // logic

        try {
            RequestDispatcher r = request.getRequestDispatcher("/result.jsp");
            request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);
        }
        catch (ServletException e1) {
            e1.printStackTrace();
        }

    }
}

}

Мой помпон выглядит следующим образом ...

<project xmlns="http://maven.apache.org/POM/4.0.0"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0     http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.hp.it.kmcs.search</groupId>
  <artifactId>JettyTest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>JettyTest</name>
  <url>http://maven.apache.org</url>

 <properties>
    <jettyVersion>7.2.0.v20101020</jettyVersion>
  </properties>

  <dependencies>
    <dependency>
        <groupId>org.eclipse.jetty.aggregate</groupId>
        <artifactId>jetty-all-server</artifactId>
        <version>7.6.0.RC1</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.1.0.RELEASE</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
  </dependencies>

  <build>
<plugins>
  <plugin>
    <!-- This plugin is needed for the servlet example -->
    <groupId>org.mortbay.jetty</groupId>
    <artifactId>jetty-maven-plugin</artifactId>
    <version>${jettyVersion}</version>
  </plugin>
  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.1</version>
    <executions>
      <execution><goals><goal>java</goal></goals></execution>
    </executions>
    <configuration>
      <mainClass>com.hp.it.kmcs.JettyTest.RunHelloServlet</mainClass>
    </configuration>
  </plugin>
</plugins>


person Rob McFeely    schedule 21.12.2011    source источник


Ответы (2)


Итак, я заставил это работать, используя setWar и правильные jar-файлы. Используя этот код, можно как напрямую обращаться к jsp (localhost: 8080 / result.jsp), так и, что более важно, перенаправлять на jsp с помощью сервлетов (localhost: 8080 / hello) .forward. Это позволит мне обслуживать динамический контент с помощью моего файла jsp.

Код следующим образом ... (NB: Embedded Jetty => web.xml не требуется)

import java.io.File;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;

public class RunHelloServlet {

public static void main(String[] args) throws Exception {

    System.setProperty("DEBUG", "true");
    Server server = new Server(8080);

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath("/");

    File warPath = new File("C:/dev/workspace/JettyTest", "src/main/webapp");
    webappcontext.setWar(warPath.getAbsolutePath());
    HandlerList handlers = new HandlerList();
    webappcontext.addServlet(new ServletHolder(new HelloServlet()), "/hello");

    handlers.setHandlers(new Handler[] { webappcontext, new DefaultHandler() });
    server.setHandler(handlers);
    server.start();
}

public static class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public HelloServlet() {
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // logic

        try {
            request.getRequestDispatcher("/result.jsp").forward(request, response);
        }
        catch (Throwable e1) {
            e1.printStackTrace();
        }

    }
}
}

POM.xml ...

<project xmlns="http://maven.apache.org/POM/4.0.0"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0     http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.hp.it.kmcs.search</groupId>
  <artifactId>JettyTest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>JettyTest</name>
  <url>http://maven.apache.org</url>

<properties>
    <jettyVersion>7.2.0.v20101020</jettyVersion>
</properties>
<dependencies>

    <dependency>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-server</artifactId>
    <version>7.6.0.RC1</version>
    <type>jar</type>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-util</artifactId>
    <version>7.6.0.RC1</version>
    <type>jar</type>
    <classifier>config</classifier>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>org.mortbay.jetty</groupId>
    <artifactId>jsp-2.1-glassfish</artifactId>
    <version>2.1.v20100127</version>
    <type>jar</type>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.eclipse.jdt.core.compiler</groupId>
    <artifactId>ecj</artifactId>
    <version>3.5.1</version>
    <type>jar</type>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>org.mortbay.jetty</groupId>
    <artifactId>servlet-api-2.5</artifactId>
    <version>6.1.14</version>
    <type>jar</type>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-webapp</artifactId>
    <version>7.6.0.RC0</version>
    <type>jar</type>
    <scope>compile</scope>
    </dependency>
</dependencies>

  <build>
    <plugins>
      <plugin>
        <!-- This plugin is needed for the servlet example -->
        <groupId>org.mortbay.jetty</groupId>
       <artifactId>jetty-maven-plugin</artifactId>
        <version>${jettyVersion}</version>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.1</version>
        <executions>
          <execution><goals><goal>java</goal></goals></execution>
        </executions>
        <configuration>
          <mainClass>com.hp.it.kmcs.JettyTest.RunHelloServlet</mainClass>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
person Rob McFeely    schedule 04.01.2012
comment
Спасибо - это помогло мне найти ответ на связанную проблему. Для меня переключение с общего ServletContextHandler на WebAppContext решило эту проблему (встроенная пристань с инъекцией сервлета guice). Я устанавливаю ResourceBase на путь к веб-приложению. - person Lars Grammel; 19.06.2012

Отображает ли ваша встраиваемая консоль приложения такую ​​ИНФОРМАЦИЮ:

INFO:oejw.StandardDescriptorProcessor:NO JSP Support for /servletpath, did not find org.apache.jasper.servlet.JspServlet

Embedded Jetty по умолчанию не поддерживает JSP. Подробнее см. здесь. HTH.

person user981    schedule 22.12.2011
comment
Никакой консольный вывод на это не жалуется. Я что-то сломал в своем рабочем пространстве прямо сейчас, пока возился с этим :), но я скоро дам вам точный вывод консоли - person Rob McFeely; 22.12.2011
comment
о, эта статья о поддержке JSP, мягко говоря, сбивает с толку. однако в конце он говорит, что вы можете использовать банку с заполнителем на пристани, которая уже использует - person Rob McFeely; 22.12.2011
comment
консоль говорит ...... 2011-12-22 14: 12: 17.262: ИНФОРМАЦИЯ: oejs.Server: jetty-7.6.0.RC1 2011-12-22 14: 12: 17.370: ИНФОРМАЦИЯ: oejsh.ContextHandler: start oejsServletContextHandler {/, файл: / C: / dev / workspace / JettyTest /} 2011-12-22 14: 12: 17.425: ИНФОРМАЦИЯ: oejs.AbstractConnector: запущено [email protected]: 8080 ЗАПУСК - person Rob McFeely; 22.12.2011
comment
Хорошо, тогда вроде все в порядке, просто спрашиваю, потому что именно с этим я и столкнулся. - person user981; 24.12.2011