一尘不染

HttpServlet和JSP集成

jsp

我想知道是否可以将自定义servlet逻辑与.jsp模板视图集成。例如,我有以下servlet:

public class MyServlet extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
      String name = "Mark";        
  }
}

而且我想像这样将name变量放在jsp文件(new.jsp)内:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>New</title>
    </head>
    <body>
         <%= name %>

    </body>
</html>

我的web.xml:

<servlet>
    <servlet-name>MyServlet</servlet-name>
    <jsp-file>/new.jsp</jsp-file>
</servlet>
<servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/new</url-pattern>
</servlet-mapping>

我不想提出name要求。

有什么帮助吗?


更新

非常感谢,但我仍然遇到麻烦。首先,我更新了我的servlet:

public class MyServlet extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
      String name = "Mark";
      request.setAttribute("name", name);
      request.getRequestDispatcher("/WEB-INF/new.jsp").forward(request, response);       
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
      String name = "Mark";
      request.setAttribute("name", name);
      request.getRequestDispatcher("/WEB-INF/new.jsp").forward(request, response);       
  }
}

我也改变了看法:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>New</title>
    </head>
    <body>
         ${name}

    </body>
</html>

但是当我使用时${name},没有任何显示。我以为我应该导入任何jstl,但是不幸的是,如果使用,<%= request.getAttribute("name") %>我会得到null


更新2终于解决了!是我的错,我忘了

<servlet>
   <servlet-name>MyServlet</servlet-name>
   <servlet-class>com.example.MyServlet</servlet-class>
</servlet>

阅读 218

收藏
2020-06-10

共1个答案

一尘不染

您需要改为实现该doGet()方法。普通的HTTP请求(单击链接,书签或直接在浏览器地址栏中输入URL)默认为GETmethod。

为了使对象在预处理Servlet中的JSP中可用,您需要将其设置为请求,会话或应用程序范围内的属性。最后,您需要将请求/响应转发到JSP,以便可以显示它。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String name = "Mark";
    request.setAttribute("name", name);
    request.getRequestDispatcher("/WEB-INF/new.jsp").forward(request, response);
}

如果您按照以下方式修复servlet映射

<servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>com.example.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/new</url-pattern>
</servlet-mapping>

那么您可以通过http:// localhost:8080 / contextname /
new
调用servlet 。在转发的JSP中,您可以访问namejust
by EL

${name}

请注意,将JSP放置在/WEB-INF文件夹中是为了避免直接访问,而无需通过在浏览器地址栏中输入JSP URL来调用预处理servlet。

2020-06-10