代码之家  ›  专栏  ›  技术社区  ›  dp.carlo

使用HTTPServletRequest将参数从servlet传递到jsp返回null[重复]

  •  1
  • dp.carlo  · 技术社区  · 9 年前

    我试图使用HTTPServletRequest将参数从servlet传递到JSP,但没有成功。有人能解释我哪里错了?

    这里是servlet: HelloServlet

    package net.codejava;
    
    import java.io.IOException;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    /**
     * Servlet implementation class HelloServlet
     */
    public class HelloServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest request,
                             HttpServletResponse response)
                             throws ServletException, IOException {
    
            request.setAttribute("name", "name1");
            request.setAttribute("surname", "surname1");
            request.getRequestDispatcher("index.jsp").forward(request, response);
    
        }
    
    }
    

    这里是JSP: JSP(“HelloServlet/index.JSP”)

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>HelloWorld Index</title>
    </head>
    <body>
        Welcome <%= request.getAttribute("name") %>
    </body>
    </html>
    

    和web.xml: web.xml

    <web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
        <servlet>
            <servlet-name>helloservlet</servlet-name>
            <servlet-class>net.codejava.HelloServlet</servlet-class>
            <jsp-file>/HelloServlet/index.jsp</jsp-file>        
        </servlet>
        <servlet-mapping>
            <servlet-name>helloservlet</servlet-name>
            <url-pattern>/HelloServlet</url-pattern>
        </servlet-mapping>
    </web-app>
    

    结果

    Welcome null
    
    1 回复  |  直到 9 年前
        1
  •  0
  •   Nishad K Ahamed    9 年前

    事实上,你的行动永远不会被召唤。 请尝试更改代码中的以下部分。

    已更新 web.xml

    <web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
        <servlet>
            <servlet-name>helloservlet</servlet-name>
            <servlet-class>net.codejava.HelloServlet</servlet-class>
       </servlet>
        <servlet-mapping>
            <servlet-name>helloservlet</servlet-name>
            <url-pattern>*.htm</url-pattern>
        </servlet-mapping>
    </web-app>
    

    并通过

    http://localhost:8080/HelloServlet/index.htm