Huppo
Huppo

Reputation: 971

Passing a java bean from jsp to servlet

I found out plenty of solutions but none of them work for me.

This is the bean in jsp

<jsp:useBean id="customer" class="com.objects.Customer" scope="request" />
<form action="proceed" method="post">
    <% customer.setEmail("abc");%>
    <input type="submit" value="Proceed" />
</form>

This is the servlet

Customer customer = (Customer)request.getAttribute("customer");
System.out.println(customer.getEmail());

Then it just boom, the customer object is null. I tried to change to session and getsession but still didn't work at all.

Could anyone point my mistake.? Thanks

Upvotes: 0

Views: 7104

Answers (1)

dcernahoschi
dcernahoschi

Reputation: 15230

Request attributes don't work this way. The customer bean is instantiated on the request object corresponding to the previous request: the one that displays the form. When you submit the form to the servlet the request where you put the customer object is long gone.

But it should work with <jsp:useBean id="customer" class="com.objects.Customer" scope="session" /> and session.getAttribute("customer") because the session objects spans multiple requests assuming you have cookies enabled in the browser. If it's not working then you have another issue not visible in your provided code.

One more suggestion: use standard <jsp:setProperty name="customer" property="email" value="abc" /> to set bean values.

Upvotes: 3

Related Questions