1

I'm learning JSP and Servlets and trying to transfer data from my servlet to JSP.But I get the transferred string as null in my JSP.

DemoServlet:

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.getSession().setAttribute("name", "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=(String)session.getAttribute("name");
    out.print("your name"+name);
        
        %>  
         
</body>
</html>

Error: https://i.stack.imgur.com/uDnKo.png I have tried doing the same without using session which give the nullPointerException

Harmless
  • 38
  • 5
  • yes because when you open your `index.jsp` for the first time value of `name` is still not set..it will be set when you go to servlet .That's the reason its showing null . – Swati Jul 11 '20 at 13:24
  • How should I change it so it calls the servlet first? – Harmless Jul 11 '20 at 13:26
  • 1
    this [post](https://stackoverflow.com/questions/32020447/set-servlet-as-default-home-page-in-web-xml) will help to do the same. – Swati Jul 11 '20 at 13:29
  • ok thanks I'll try this – Harmless Jul 11 '20 at 13:39
  • 1
    @Stefan - It's good that you have educated OP regarding the deprecation of JSP. It will be more helpful if you can suggest him/her the alternative to it. – Arvind Kumar Avinash Jul 11 '20 at 18:48
  • The usual alternative is JSF which means, not mixing Java code with HTML. But Freemarker is also a look worth. – Stefan Jul 13 '20 at 20:08

0 Answers0