JSP Impilicit Objects - request, response and out


JSP request -

request is an object of HttpServletRequest passed to the service() method by web container. We can directly use it in JSP files.
For Example -
<% String param_Value = request.getParameter("param_Name"); %>        

JSP response -

response is an object of HttpServletResponse passed to service() method by web container. We can directly use it in JSP files.
For Example -
<% response.setContentType("text/html"); %>        

JSP out -

out is an object of JspWriter that is used to write on web pages. We can directly use it in JSP files.
For Example -
<% out.println("Just a Demo"); %>        
Difference between PrintWriter and JspWriter - In servlets out is an object of PrintWriter, but in JSP out belongs to JspWriter. Both are nearly same with the following differences -
JspWriter is a PrintWriter with some buffering capabilities added into it. It uses some functionalities from both java.io.BufferedReader and java.io.PrintWriter.
JspWriter print() method through java.io.IOException, whereas PrintWriter print() method does not.

Example -

This simple example will show you how to use request, response and out implicit objects in JSP.

1- index.html or index.jsp - This will be our default page.
Make the following changes in index page -
<!DOCTYPE html>
<html>
    <head>
        <title>JSP Demo</title>
    </head>
    <body>
        <form method="post" action="LoginChek.jsp">
            <table border="1px">
                <tr>
                    <td>Name - </td>
                    <td><input type="text" name="t1"></td>
                </tr>
                <tr>
                    <td>Password - </td>
                    <td><input type="password" name="t2"></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Login"></td>
                    <td><input type="reset" value="Reset"></td>
                </tr>
            </table>
        </form>
    </body>
</html>

2- Create a JSP file named LoginChek.jsp as follows -
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <title>JSP Page</title>
    </head>
    <body>

        <%
        
        String name = request.getParameter("t1");  // request is implicit object in JSP.
        String pass = request.getParameter("t2");
        if(name.equals("admin") && pass.equals("123"))
        {
            out.println("Welcome "+ name);  // out is implicit object in JSP.
        }
        else
        {
            response.sendRedirect("index.html");  // response is implicit object in JSP.
        }
        
        %>
        
    </body>
</html>   

3- Now run the project. If you enter valid username and password, you will get a Welcome message otherwise redirected to Login From again.





Download this example (NetBeans implementation) - Click Here