JSP Get Value of Property

Daniel picture Daniel · Jul 14, 2013 · Viewed 9.4k times · Source

I am very new to JSPs so I need your help. Google didn't give me what I was looking for, I might just entered the wrong search term. So please forgive me, but I think its a really dumb question, however nothing seems to be on the net about it.

I created a login screen (works fine) and the credentials are checked (works fine) and the main screen gets a DTO which should be evaluated.

As you can see, there is a jsp:getProperty tag, it works fine, if I try to access the paramter name using jsp:getProperty. I want to do some additional checks, therefor I tried to access the property within the <% %> section, in there however, it is null. Is there a way how to access the object within the <<% %> section, after you retrieved it with a jsp:useBean tag?

Here is the main jsp file:

 <?xml version="1.0" encoding="ISO-8859-1" ?>
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
 <%@ page import="de.daniel.docmanager.dto.User"  %>   
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
 </head>
 <body>
 <jsp:useBean id="user" class="de.daniel.docmanager.dto.User" scope="session">  
 </jsp:useBean>

<%
String name =  user.getName();
System.out.println("name: " + name);  //<= name is null
%>

Hello <jsp:getProperty property="name" name="user"/> //<= works fine
</body>
</html>

Thank you very much for your support. I really do appreciate it.

Answer

AllTooSir picture AllTooSir · Jul 14, 2013

It is a bad practice to use scriptlets in JSP . Read this nice SO Q&A : How to avoid Java Code in JSP-Files? on this subject .


Coming back to your problem. You are defining a bean using Standard Action as :

<jsp:useBean id="user" class="de.daniel.docmanager.dto.User" scope="session">  
</jsp:useBean>

The useBean tag will look for an instance of the "de.daniel.docmanager.dto.User" class in the session . If the instance is not already there, it will create a new instance of "de.daniel.docmanager.dto.User" , and put it in the session.

You have to retrieve the object from the session scope :

<%
 String name =  ((de.daniel.docmanager.dto.User)session
                                      .getAttribute("user")).getName();
 System.out.println("name: " + name);  
%>

I want to do some additional checks, therefor I tried to access the property within the <% %> section

You can use JSTL or some tag library for that purpose.