Open In App
Related Articles

Attributes in Servlets | Java

Improve Article
Save Article
Like Article

An attribute in servlet is an object that can be set, get or removed by the following aspects

  1. Request Scope
  2. Application Scope
  3. Session Scope

To pass the value from servlet to html/jsp files, setAttribute() method is called by the request object. setAttribute() method takes an input as an object which sends the data from servlet to the requesting website

public void setAttribute(String name, Object obj)

Sets the specified object in the application scope.

At the user-end, html uses a syntax by which attributes can be fetched

${ var-name }

in which var-name is same as name in setAttribute() method

Let’s look at an example of website which validates the form in server side

HTML File 1 (Requesting Website)

The code will send the input data to the Servlet to process the validation, which in return get the error text if any validation occurs.

<p style="color: black;">* required field</p
<form method="post" action="./CommitServlet">
    <label>Username: *</label>
    <!-- Received response bundle data from the servlet as ${ var-name }  -->
    <input type="text" value="${after.inputName}" name="inputName"/>
    <span name="errorName">${errors.Name}</span>
    <label>Gender: *</label>
    <input type="radio" name="gender" value="male" />Male
    <input type="radio" name="gender" value="female" />Female
    <input type="radio" name="gender" value="other" />Other 
    <span name="errorGender">${errors.Gender}</span>
    <input type="submit"/>


HTML1 Output

Servlet Code

This Program process the requesting data and checks its validation, if any error encounter it will add the error text in the Bundle known as MAP class. This bundle is again sent to the requesting site for an error correction

// Servlet code
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CommitServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
        throws ServletException, IOException
        // Create a Bundle of errors in the form of Map
        Map<String, String> errors = new HashMap<String, String>();
        Map<String, String> after = new HashMap<String, String>();
        // Get the input values from the website
        String inputName = request.getParameter("inputName");
        String inputGender = request.getParameter("gender");
        // If error occur, previous entered data will be reflected
        after.put("inputName", inputName);
        // Check for Validation of Name and Gender
        if (!validateName(inputName))
            // If error occur, create a entry for
            // the bundle and write a alert message
            errors.put("Name", "Please enter a valid name");
        if (inputGender == null)
            // If Gender is not select, encounter an error
            errors.put("Gender", "Please select a Gender");
        if (errors.isEmpty())
            // If no error occur, redirect to the response website
        else {
            // Set this bundle into the request attribute
            // and pass the data to the requested website
            request.setAttribute("after", after);
            request.setAttribute("errors", errors);
            request.getRequestDispatcher("comment.jsp").forward(request, response);
    // Method to validate Proper Name, entered by the user
    public static boolean validateName(String txt)
        String regex = "^[a-zA-Z ]+$";
        Pattern pattern = Pattern.compile(regex,
        Matcher matcher = pattern.matcher(txt);
        return matcher.find();

Output :


HTML Code 2

If no error occurs, successful message is printed

        <h1>Comment Successfully Stored</h1>

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 13 Sep, 2018
Like Article
Save Article
Similar Reads
Complete Tutorials