I have servlet which calls a jsp page. While calling it should set a object which jsp should get hold and manipulate it. If possible please send a code snippet also.

kevin smith

One way is to use the JSP/servlet forwarding functionality to achieve this. An object can be put into a HttpSession and then retrieved from the session in the JSP using the "jsp:useBean" tag. Any changes made to the bean in the JSP will be available to all other servlets/JSPs that have access to the session object. Here is some code to demonstrate this concept:

ControllerServlet.java
======================
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class ControllerServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException {
try {
String ssn = req.getParameter("ssn");

HttpSession session = req.getSession(true);

Person bean = new Person();
if (ssn.equals("123456")) {
bean.setFirstName("Kermit");
bean.setLastName("TheFrog");
}
else {
bean.setFirstName("Bugsy");
bean.setLastName("Malone");
}

session.setAttribute("personBean", bean);

getServletContext().getRequestDispatcher("/view.jsp").forward(req, res);
}
catch (IOException e) {
e.printStackTrace();
}
}
}

Person.java
===========
public class Person {
private String firstName;
private String lastName;

public Person() {
firstName = null;
lastName = null;
}

public void setFirstName(String name) {
firstName = name;
}

public void setLastName(String name) {
lastName = name;
}

public String getFirstName() {
return firstName;
}

public String getLastName() {
return lastName;
}
}

view.jsp
========
<jsp:useBean id="personBean" scope="session" type="Person"/>
<html>
<head>
<title>MVC Demo - View</title>
</head>
<body>
First Name: <%=personBean.getFirstName()%>
Last Name: <%=personBean.getLastName()%>
</body>
</html>


Of course you can call the "set..." methods on the bean in the JSP and then call another servlet/JSP that can retrieve the bean from the session and make use of the changed state.

Well, hope this helps!

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact