views:

203

answers:

1

How to use bean in JSP with only <jsp:useBean>, not MVC?

Assume you have a grade.txt file which contains following data:

Tom 90
Jerry 70
Katy 80
John 60

It asks you to create a bean named grade.java, a JSP page named graderesult.jsp, and a html page named gradecheck.html.

gradecheck.html provides a input textbox and a button submit, once you submit the name of the student, the graderesult.jsp will communicates with bean to show the name and the score corresponding to the person.

+2  A: 

You can make use of <jsp:setProperty name="beanname" property="*" /> to "automatically" set all request parameters as bean properties matching the property name. As this is a typical homework question, I won't give complete code examples, but only hints:

  1. Create a bean Grade with a property name.
  2. Add a constructor which loads the data from the text file into a Map<String, Integer> property representing name-score pairs. Learn more about Java IO here and about Java Maps here.
  3. Add a "special" getter getScore() which returns the score from the Map using the name as key.
  4. Create a form with <input type="text" name="name"> in the gradecheck.html. Let the form submit to graderesult.jsp. The request method doesn't matter, I would prefer POST though.
  5. In the graderesult.jsp use <jsp:useBean> to declare and instantiate the bean in request scope and use <jsp:setProperty> to "automatically" set all input values in the bean.
  6. Use EL to show the name by ${grade.name} and the associated score by ${grade.score}.

Good luck.

BalusC