Attributes in Servlets | Java

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<body>
<h1>Demo</h1>
<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>
    <br/><br>
      
    <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>
    <br><br>
    <input type="submit"/>
</form>
</body>

chevron_right


Output:

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Servlet code
import java.io.IOException;
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;
  
@WebServlet("/CommitServlet")
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
            response.sendRedirect("success.html");
  
        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,
                                          Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(txt);
        return matcher.find();
    }
}

chevron_right


Output :
Error

Error1

HTML Code 2

If no error occurs, successful message is printed

filter_none

edit
close

play_arrow

link
brightness_4
code

<body>
    <center>
        <h1>Comment Successfully Stored</h1>
    </center>
</body>

chevron_right




My Personal Notes arrow_drop_up

सर्वशक्तिशाली इकलौता

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.