0

So I'm learning Servlet and JSP and I'm trying to send a String name to my jsp using RequestDispatcher but I'm getting 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

Harmless
  • 38
  • 5

1 Answers1

0

Use setAttribute (and getAttribute) when you need to pass objects around across many servlets (or other components) handling the same request.

Can you please try using setAttribute in your servlet and fetch the parameter using getParameter in the jsp

request.setAttribute("name", "Harmless");

above code in servlet.

and try to fetch in jsp as below
<%
  request.getParamter("name");
%>