1

I have scenario like this.

After submission of JSP page request goes to servlet. In the servlet I have requirement like need to send the an object to same JSP page to fill the form text fields.

User will enter id value in the form and we need to fetch the data from database and need to fill the rest of the fields in the same page

I have used these lines in the process

   //In servlet

   //1 request.setAttribute("student",student);

  //2 request.getRequestDispatcher("/Student.jsp").forward(request, response);

  //In JSP
  used getAtttibute here

  input type="text" name="name" value=<%=name %>

I have done with coding and it is working fine but it looks very clumsy!!

Please do refer any other ways to do this task efficiently.

Just Suggest me how to proceed and I can work on it :)

TruePS
  • 493
  • 2
  • 12
  • 33
NareshSathu
  • 21
  • 1
  • 8

2 Answers2

1

While your approach is sort of right, you should avoid using scriptlets in your view at all. So, retrieve the data from your request attributes using Expression Language:

<input type="text" name="name" value="${student.name}" />

You can overcome null values by using ternary operator:

<input type="text" name="name" value="${empty student ? "" : student.name}" />
Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • It is showing null value in the text field when the first time page accessed. – NareshSathu Apr 22 '14 at 05:59
  • @user3500659 it will show a `null` value if there's no request attribute associated to this. You should not directly access to the page, instead access to the servlet through a GET request and fill an empty student. – Luiggi Mendoza Apr 22 '14 at 06:00
  • unfortunately it is my only JSP page in my small application.then how to get rid of the null value. – NareshSathu Apr 22 '14 at 06:11
0

you can replace the getAttribute with JSTL EL's (expression language) so basically

request.setAttribute('KEY')

in a JSP can be accessed via

  1. request.getAttribute('KEY') -> This is what you are doing
  2. ${KEY}

The efficiency in terms of code would be the same. Approach 2 is neater.

AdityaKeyal
  • 1,208
  • 8
  • 14
  • Yeah I have tried this. when the first time page loading it is showing NAN(null) how to over come this. – NareshSathu Apr 22 '14 at 05:58
  • you can use [JSTL](http://docs.oracle.com/cd/E17802_01/products/products/jsp/jstl/1.1/docs/tlddocs/c/tld-summary.html) c tags (`${KEY}`) which is the recommended approach. – AdityaKeyal Apr 22 '14 at 06:19