Reputation: 3020
I have a jsp page where i am using a bean as request scope bean. I have an input text whose value is the attribute of the bean. On the form submit my action is someServlet. Now in that someServlet i want to access the bean that i used in my jsp page. here is sample code i am using.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="userBean" scope="request" class="com.iceman.bean.UserBean">
<jsp:setProperty property="*" name="userBean"/></jsp:useBean>
<form action="action.do" method="post">
Type Your Name:<input type="text" name="userName"/><br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Servler
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
UserBean userBean = (UserBean)request.getAttribute("userBean");
response.getWriter().print(userBean.getUserName());
}
When i run this i get a null pointer exception on servlet line where i call bean getter method.
Where am i doing wrong?
Upvotes: 0
Views: 1340
Reputation: 149155
It is simply because the render request and the post request are different requests:
The only ways to have information to persist between requests are:
Upvotes: 2
Reputation: 10142
For clarity , you need to take your bean declaration <jsp:useBean id="userBean" scope="request" class="com.iceman.bean.UserBean"></jsp:useBean>
outside form
element , and change definition to
<jsp:useBean id="userBean" scope="request" class="com.iceman.bean.UserBean">
<jsp:setProperty name="userBean" property="*" />
</jsp:useBean>
Star ( * ) means that all bean properties with names that match request parameters sent to the page are set automatically. ( As per O`Reilly book )
then you need to change line <input type="text" value="${userBean.userName}"/>
to <input type="text" name="one of field names as per your UserBean class "/>
You have not shared details of UserBean class but I guess field name is userName
Regarding bean being NULL
in request
, please refer answer by Jan Zyka for question jsp useBean is NULL by getAttribute by servlet
Hope it helps !!
Upvotes: 0