Passing Data to Java User Controls

In this article, I'll explain various methods for passing data, such as an encoded record number (recno) and a stored procedure name (sp), to User Controls in Java-based web applications. It covers key techniques, including URL parameters (QueryString), session attributes, request attributes, and JavaScript data attributes. Each method is accompanied by practical examples and scenarios to help you choose the best approach for your application's architecture, data flow, and security requirements.

Theory

In web development, it's common to pass data between different components or layers of an application. In Java-based web applications, especially those using JSP, Servlets, or MVC frameworks like Spring, you may need to pass data from one part of your application to a User Control or a similar reusable component.

There are multiple ways to achieve this,

To pass values like recno and sp to a Java-based User Control, you can follow similar approaches as in C#, but with Java-specific mechanisms. Below are methods to pass these values in a Java-based web application, such as one using JSP, Servlets, or a Java MVC framework like Spring.

URL Parameters (QueryString)

This method involves appending data as parameters in the URL. It is straightforward and easy to implement but exposes the data in the URL, making it less secure for sensitive information.

You can append the values as query string parameters in the URL when invoking a servlet or JSP page that includes the User Control.

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/ExampleServlet")
public class ExampleServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int recno = Integer.parseInt(request.getParameter("recno"));
        String sp = request.getParameter("sp");

        response.setContentType("text/html");
        response.getWriter().println("<h2>URL Parameters</h2>");
        response.getWriter().println("<p>RecNo: " + recno + "</p>");
        response.getWriter().println("<p>SP: " + sp + "</p>");
    }
}

In the servlet or JSP, retrieve the values.

<% 
int recno = 123; // Sample value
String sp = "sp_Inv"; 
String url = "ExampleServlet?recno=" + recno + "&sp=" + sp;
%>
<a href="<%= url %>">Click to Pass via URL</a>

Output for the above code

When you click the link on index.jsp.

<a href="ExampleServlet?recno=123&amp;sp=sp_Inv">Click to Pass via URL</a>

Output on the ExampleServlet page

<h2>URL Parameters</h2>
<p>RecNo: 123</p>
<p>SP: sp_Inv</p>

ExampleServlet page

Using Session Attributes

This approach stores data in the session, allowing it to persist across multiple requests from the same user. It is secure and doesn't expose data in the URL, but it requires careful management to avoid unnecessary memory usage.

Store the values in the session before invoking the servlet or JSP page.

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/ExampleSessionServlet")
public class ExampleSessionServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        int recno = (int) session.getAttribute("recno");
        String sp = (String) session.getAttribute("sp");

        response.setContentType("text/html");
        response.getWriter().println("<h2>Session Attributes</h2>");
        response.getWriter().println("<p>RecNo: " + recno + "</p>");
        response.getWriter().println("<p>SP: " + sp + "</p>");
    }
}

In the servlet or JSP, retrieve the session attributes.

<% 
int recno = 123; // Sample value
String sp = "sp_Inv"; 
session.setAttribute("recno", recno);
session.setAttribute("sp", sp);
%>
<a href="ExampleSessionServlet">Click to Pass via Session</a>

Output for the above code

When you click the link on index.jsp.

<a href="ExampleServlet?recno=123&sp=sp_Inv">
  Click to Pass via Session
</a>

Output on the ExampleServlet page

<h2>Session Attributes</h2>
<p>RecNo: 123</p>
<p>SP: sp_Inv</p>

JSP page

Passing Values as Request Attributes

Request attributes are useful for passing data within the same request, such as forwarding from a servlet to a JSP. They are secure and do not persist beyond the current request, making them ideal for short-lived data.

Set these values as request attributes and forward them to the User Control.

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/ExampleRequestServlet")
public class ExampleRequestServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int recno = 123; // Sample value
        String sp = "sp_Inv";
        
        request.setAttribute("recno", recno);
        request.setAttribute("sp", sp);
        request.getRequestDispatcher("display.jsp").forward(request, response);
    }
}

In the JSP, you can retrieve these values.

<%
    int recno = (Integer) request.getAttribute("recno");
    String sp = (String) request.getAttribute("sp");
%>
<h2>Request Attributes</h2>
<p>RecNo: <%= recno %></p>
<p>SP: <%= sp %></p>

Output for the above code

When you click the link on index.jsp.

<a href="ExampleServlet?recno=123&sp=sp_Inv">
    Click to Pass via Request
</a>

Output on the ExampleServlet page

<h2>Request Attributes</h2>
<p>RecNo: 123</p>
<p>SP: sp_Inv</p>

Passing Values

JavaScript (For Client-Side Handling)

These attributes allow you to store data in HTML elements and manipulate it on the client side using JavaScript. This method is ideal for client-side processing and can be combined with AJAX to pass data back to the server.

If you want to handle this client-side using JavaScript, pass the values back to the server later.

out.println(
    "<a id='btnDel' class='list-icons-item text-danger-600' " + 
    deleteAttributes + 
    " data-recno='" + recno + "' data-sp='" + sp + "'>" + 
    "<i class='icon-bin mr-1'></i></a>"
);

Then in JavaScript, handle the click event.

function BindData(element) {
    var recno = element.getAttribute("data-recno");
    var sp = element.getAttribute("data-sp");
    // Use recno and sp as needed
}

Later, we can pass these values back to the server via an AJAX request or form submission.

Output for the above code

When you click the link on index.jsp.

<a id="btnDel" 
   href="#" 
   data-recno="123" 
   data-sp="sp_Inv" 
   onclick="handleClick(this)">
   Click to Pass via JavaScript
</a>

Output on the ExampleServlet page

// JavaScript Data
const data = {
  RecNo: 123,
  SP: "sp_Inv"
};

AJAX request

Choosing the Right Method

  • URL Parameters (QueryString): Simple but exposes data in the URL.
  • Session Attributes: Secure and persistent during the session but shared across the user's session.
  • Request Attributes: Useful for passing data between servlets/JSPs without exposing the URL.
  • JavaScript Data Attributes: Useful for client-side manipulation before sending data back to the server.

Choosing the right method depends on the context in which the data is used, the sensitivity of the data, and the overall design of your application. This guide provides detailed explanations and examples to help you implement the most appropriate solution for your needs.


Similar Articles