0
votes

I am brand new to all of this, I like servlets and java on a whole so far but I'm having some growing pains.

Servlet Question: Just starting to learn servlets and I'm having an issue with Attributes/Parameters, Sessions and jsp.

Basically, I have a very basic form. My servlet code states:

println("Hello, " + request.getParameter("name") + "!!!");  

..and my .jsp states:

<form action="SimpleServlet" method="POST">
<input type="text" name="name">
<input type="submit"/>
</form>

So now what I need to do is take the last name input into this servlet, save it in session and then send it to a different .jsp that states:

'Hello, '

For example, if I input JIM into the servlet and it returns 'Hello, Jim!!!' in my first .jsp I would then need to click on a link on that page that re-directs me to another .jsp that takes the 'Jim' input and also displays 'Hello, Jim!'.

So I created a 2nd .jsp and have tried many different combinations of code on both to try and get this to work and I keep on getting null or screwing up the output of the first part of the form.

Could someone guide me in the right direction, I would greatly appreciate it.

3
Can you please post the code of your servlet also. I'm suspecting that your problem is with how you handle the input. - JFPicard

3 Answers

0
votes

if you want to show your last name JIM in multiple jsp pages you can use session to store your last name add following code in your servlet.

 String name  = request.getParameter("name");
 HttpSession session=request.getSession();  
 session.setAttribute("name",name);

then in all your jsp you need to do is put following scriplet where you want to print your name.

<%
  String name = request.getSession().getAttribute("name");
  out.print(name);
%>
0
votes

You can do exactly what you want using a single .jsp page, you don't have to create a different one. Just create a link that will POST different parameters to the same .jsp
But as an advice/direction to you, I think the first thing you must understand well is how can you pass and receive parameters and attributes to deal with at server side. Understanding what a request can carry has a huge importance in server-side development.

0
votes

Just an addon to Mitul's answer I'd advice you to use EL. It is a simplified approach.

Instead of String name = request.getSession().getAttribute("name"); use ${sessionScope.name} It would give you the desired output.

The best part is that scope resolution is done automatically. So, here name could come from page, or request, or session, or application scopes in that order. If for a particular instance you need to override this because of a name collision you can explicitly specify the scope as