【问题标题】:Servlet with jsp is not working带有 jsp 的 Servlet 不起作用
【发布时间】:2015-11-18 23:25:46
【问题描述】:

我正在使用支持 JSP 和 JSTL 的嵌入式 Jetty 服务器,但这不重要。

这就是我想要做的:

  • 我要访问页面http:localhost:8080/admin/index.jsp
  • 当我访问这个页面时,一个 servlet“StatisticsServlet”必须创建并发送一个地图 到 index.jsp
  • index.jsp 必须循环遍历地图并显示键和值。

这是我目前所拥有的:

StatisticsServlet.java

public class StatisticsServlet extends HttpServlet {

    SingletonStatsContainer stats = SingletonStatsContainer.getInstance();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Map<String, Integer> requestListLenghts = stats.getItemsInUnprocessedRedisList();

        req.setAttribute("stats", requestListLenghts);
        RequestDispatcher reqDispatcher = req.getRequestDispatcher("/index.jsp"); //Is this correct?
        reqDispatcher.forward(req, resp);
    }

}

这是启动服务器的原因:

AdminWeb.java

public class AdminWeb implements Runnable {
    private static final ContextHandlerCollection webContext = new ContextHandlerCollection();
    private static final Logger logger = LoggerFactory.getLogger(AdminWeb.class);
    @Override
    public void run() {
        logger.info("Starting Jetty server . . .");
        WebAppContext webAppContext = new WebAppContext();
        webAppContext.setDescriptor(webAppContext + "/WEB-INF/web.xml");
        webAppContext.setResourceBase("src/com/company/web/");
        webAppContext.setContextPath("/admin");
        webAppContext.addServlet(StatisticsServlet.class, "/admin");
        webContext.setHandlers(new Handler[]{webAppContext});
        JettyServer server = new JettyServer();
        server.setHandler(webContext);
        try {
            server.start();
            logger.info("Server started! Admin page now accessible @ http://localhost:{}/admin", server.getRunningPort());
        } catch (Exception ex) {
            logger.error("Server not started : {}", ex.getMessage());
        }
    }
}

还有 index.jsp 本身:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page import="com.company.web.StatisticsServlet"%>
<!DOCTYPE html>
<html>
    <head>
    </head>

    <body>        
        <c:forEach items="${stats}" var="entry">
            ${entry.key}", ${entry.value}
        </c:forEach>
    </body>
</html>

感谢任何帮助! 注意:我没有使用任何 web.xml 配置。如果可能的话,也可以根据这个场景添加 web.xml 示例。

谢谢!

【问题讨论】:

    标签: java jsp servlets jetty


    【解决方案1】:

    我自己想出来的。如果有人遇到同样的问题,可以在这里找到示例:https://github.com/lkallas/embedded-jetty-jsp-jstl

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多