1

In jsp I have written following code:

    <form action="./ssoServlet?from=amount" method="post">
    <%request.setAttribute("formName", "DayCareForm"); %>
    Amount  
     <input type="text" name="amount" id="amount" required >
     <button onclick="dayCarePdf()" type="submit"> Convert to PDF </button>
    </form>

Post method of servlet is:

@Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("DoPost method");
        resp.setContentType("text/html");

        if(req.getParameter("from").equals("amount"))
        {
            req.getParameter("amount");

            String form = (String) req.getAttribute("formName");
            System.out.println("Type of form " +req.getAttribute("formName"));
            RequestDispatcher dispature = getServletContext().getRequestDispatcher("/DayCare.jsp");
            dispature.forward(req, resp);
        }
}

However, The servlet is returning null value for type of form

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Radhika Kulkarni
  • 298
  • 1
  • 4
  • 19

2 Answers2

1

In the jsp You set a value in the request. So it works only for the life of the request.

The servlet is invoked before passing to the jsp. So when the attribute is retrieved from the request in the servlet it doesn't exist yet.

Put it in the session and it works.


When you reach the line:

String form = (String) request.getAttribute("formName");

a code

req.setAttribute("formName", something) 

has not been set for the current request.

The code

<%request.setAttribute("formName", "DayCareForm"); %>

is performed on the previous request. Each time you pass to the servlet the request attributes are reset.

But you can set an attribute and retrieve an attribute from the session. In this case it works because a session ends when the browser is closed or the session is invalidated.


To work with a session, instead of a request replace

<%request.setAttribute("formName", "DayCareForm"); %>

with

<%session.setAttribute("formName", "DayCareForm"); %>

and

String form = (String) request.getAttribute("formName");

with

String form = (String) request.getSession().getAttribute("formName");
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
0

Try below code:

<form action="./ssoServlet" method="post" id="myForm" name="DayCareForm">
Amount  
 <input type="text" name="amount" id="amount" required >
 <input type="hidden" name="formName" value="DayCareForm" />
<button onclick="dayCarePdf()" type="submit"> Convert to PDF </button>
</form>

JavaScript:

function dayCarePdf()
{
    document.getElementById("myForm").submit();

//Rest Code will come here


}

set a hidden field as form name and you can access form name by below code.

   String formName= request.getParameter ("formName");  // you will get DayCareForm as we set form name
KhAn SaAb
  • 5,248
  • 5
  • 31
  • 52