JuniorDev
JuniorDev

Reputation: 1200

Passing arguments between two JSP pages

I'm new to web programming, and I stuck on designing a simple flow.

Let's say I have a simple object like,

public class Object1
{
  private int ID;
  private String text;

  { getters and setters etc}
}

I get a bunch(depends on the record number in DB) of these from my DAO as List<Object1>, and print them in a loop on a page, lets call it jspPage1. And I have another page, jspPage2, that does something with Object1.ID

What I want is:

Create some kind of connection, such that, when user clicks or selects an object, selected object's ID (on jspPage1) will be sent to jspPage2.

What I've thought so far;

So to repeat my question; Is there a way of doing things like this in a neater way ?

or

Is my way of approaching to this problem is fundamentally wrong and I should consider a different design. (If so any tips on that)

Upvotes: 1

Views: 576

Answers (2)

Andy
Andy

Reputation: 6568

One way I can think of is to use the MVC approach. Once the user clicks on the URL, you can have a servlet verify that the object id is valid. In other words, the servlet will contain all your logic. So, in jspPage1

<c:forEach items="${objects}" var="object1">
    <tr>
        <td><a href="
               <c:url value='/checkId' > 
                   <c:param name='id'value ='${object1.ID}' /> 
               </c:url>
               ">${object1.text}</a>
    </tr>
</c:forEach>

Then you register a servlet called CheckIdServlet in web.xml

<servlet>
    <servlet-name>checkId</servlet-name>
    <servlet-class>CheckIdServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>checkId</servlet-name>
    <url-pattern>/checkId</url-pattern>
</servlet-mapping>

Since you are passing the parameters in the url all you need to do is override the doGet(...) method

public class CheckIdServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException { 
    //do your id checking to make sure it's a number or if id value is actually in the database 
    //if either condition not met, you could redirect back to jsppage 1 or however you want to do 
    //handle 
    response.sendRedirect("/jsppage1.jsp"); 

    //or if id is valid
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsppage2.jsp"); 
    dispatcher.forward(request, response);

    //Keep in mind this is pseudocode so make sure to add your if conditions above

}

Finally, in jsppage2 you simply display your object id

<h1>${param.id}</h1>

Upvotes: 1

PSR
PSR

Reputation: 40318

You can store those values into session and then you can use in the second jsp page

otherwise you can use request.setAttribute("name",value );

Upvotes: 0

Related Questions