Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaAttributes in Servlets | Java

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.




<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>


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




// 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();
    }
}


Output :
Error

Error1

HTML Code 2

If no error occurs, successful message is printed




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


Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments