Wednesday 13 August 2014

getReader() : Read Request body as character data

public BufferedReader getReader() throws IOException
Retrieves the body of the request as character data using a BufferedReader. You can use either getInputStream() or getReader() to read the request body, but not both.

<!DOCTYPE html>
<html>
    <head>
        <title>User Registration</title>
    </head>
    <body>
        <noscript>Java Script functionality disabled, Please enable it</noscript>
        <form action="/servlet/GetReader" method="post">
            <table id="registrationTable">
                <caption>Please fill the details to Register</caption>
                <tr>
                    <td>Mail Id:<span class="required1"><sup>*</sup></span></td>
                    <td><input type="text" name="mailID" id="mailID" required="required" /></td>
                </tr>
                <tr>
                    <td>Password:<span class="required1"><sup>*</sup></span></td>
                    <td><input type="password" name="passwd" id="passwd" required="required" /></td>
                </tr>
                <tr>
                    <td>Confirm Password<span class="required1"><sup>*</sup></span></td>
                    <td><input type="password" name="confPasswd" id="confPasswd" required="required" /></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Register" id="register" /></td>
                    <td><input type="reset" value="Clear Data" /></td>             
                </tr>
            </table>
        </form>
    </body>
</html>

import java.io.IOException;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet(urlPatterns = {"/GetReader"})
public class GetReader extends HttpServlet {
  @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException{
        try(BufferedReader br = req.getReader();
            PrintWriter out = res.getWriter()){
            StringBuilder body = new StringBuilder(" ");
            String str;
            
            while((str =br.readLine())!= null)
                body.append(str);
            
            out.println("<html><head><title>InputStreamEx</title></head>");
            out.println("<body><h1>body in the request is <br />");
            out.println(body +"</h1></body></html>");
        }
    }
}

Output



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment