【问题标题】:getAttribute resulting in java.lang.NullPointerException [duplicate]getAttribute 导致 java.lang.NullPointerException [重复]
【发布时间】:2020-07-11 08:38:29
【问题描述】:

所以我正在学习 Servlet 和 JSP,我正在尝试使用 RequestDispatcher 向我的 jsp 发送一个字符串名称,但我得到了 java.lang.NullPointerException

DemoServlet.java

package com.shubhankar;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/DemoServlet")
public class DemoServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
    {
        String name ="Harmless";
        request.setAttribute("label", "Harmless");
        RequestDispatcher rd= request.getRequestDispatcher("index.jsp");
        rd.forward(request, response);
        
    }   
}


index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%

        String name=request.getAttribute("label").toString();
        out.println(name);
%>
</body>
</html>

Error

【问题讨论】:

    标签: java jsp servlets


    【解决方案1】:

    当您需要在处理相同请求的多个 servlet(或其他组件)之间传递对象时,请使用 setAttribute(和 getAttribute)。

    您能否尝试在您的 servlet 中使用 setAttribute 并在 jsp 中使用 getParameter 获取参数

    request.setAttribute("name", "Harmless");
    
    above code in servlet.
    
    and try to fetch in jsp as below
    <%
      request.getParamter("name");
    %> 
    
    

    【讨论】:

    • 嘿,当我在 Servlet 中添加 request.setParameter("name", "Harmless");时,我收到此错误 The method setParameter(String, String) is undefined for the type HttpServletRequest
    • 在 servlet 中尝试 request.setAttribute("name","Harmless")
    • 它显示与 servlet 相同的错误,即不能将 getParameter 与请求一起使用
    • ``` request.getSession().setAttribute("name", "Harmless");上面的代码在 servlet 中。并尝试在jsp中获取如下 ```
    • 我的 jsp 页面上的名称为空