CodeGym/Java Course/Module 3. Java Professional/Serving Requests in a Servlet

Serving Requests in a Servlet

Available

2.1 HttpServletRequest class

Most of the work your servlet has to do based on the information received from the request. The object is responsible for it HttpServletRequest, which the container will pass to your servlet (to the method serviceor methods doGet(), doPost()etc.)

This object has quite a few methods, since it simply stores the request data, and through it you can interact with the container.

Methods can be divided into 2 large groups:

  • Methods related to user authorization
  • Methods for working with request data

I will give the user authorization methods in the form of a table, but we will not analyze them. The fact is that they are very rarely used to authorize a user. All popular frameworks use their own, much more advanced approaches to authorization.

I should list them, but again, I haven't seen anyone use them.

Method Description
1 authenticate(HttpServletResponse) Performs response authentication
2 changeSessionId() Forcibly change the session ID
3 getAuthType() Returns the type of authentication that is used: ASIC_AUTH, FORM_AUTH, CLIENT_CERT_AUTH, DIGEST_AUTH
4 getRemoteUser() Returns user login
5 getRequestedSessionId() Returns the SessionID of the client
6 getSession() Returns an HttpSession object
7 getUserPrincipal() Returns a java.security.Principal object
8 login(username, password) Performs user login
9 logout() Logs out the user session

2.2 Request data

The second group of methods is much more interesting. What kind of data do we have in the request?

  • http method
  • URI
  • Options
  • Titles

Let's see what methods are available for working with them:

Method Description
1 getMethod() Returns HTTP method: GET, POST, DELETE, ...
2 getRequestURI() Returns the request URI: http://codegym.cc/my/data
3 getRequestURL() Returns the request URL: http://codegym.cc/my/data
4 getQueryString() Returns Query, i.e. everything after the ?
5 getParameterMap() Returns a list of query parameters
6 getParameter(String name) Returns the value of the parameter by its name
7 getContentType() Returns MimeType request body
8 getReader() Reader to read request body as text
9 getInputStream() InputStream to read request body as byte[]
10 getSession() Returns an HttpSession object
eleven getCookies() Returns an array of Cookie[] objects
12 getHeaderNames() Returns a list of titles, names only
13 getHeader(String name) Returns the header value by name
14 getServletPath() Returns the part of the URL that refers to the servlet
15 getContextPath() Returns the part of the URI that specifies the content of the request

And that's not even all the methods ...

Although after we have studied the HTTP protocol and learned how to work with HttpClient, everything is more or less familiar here, isn't it?

Let's write a servlet that can be passed text and a color to, and it will return an HTML page with that text written in the specified color. How do you like the idea?

Let's start by writing our servlet:

public class ColorTextServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
          //write your code here
    }
}

Now we need to get the text and color passed from the URI by the user:

public class ColorTextServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {

        // Getting the parameter “text” and “color” from request
        String text= request.getParameter("text");
        String color = request.getParameter("color");

    }
}

And finally, you need to output the text as HTML. We will cover this in the next lecture, but here I will give a little hint:

public class ColorTextServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {

        // Get the "text" and "color" parameters from the request
        String text = request.getParameter("text");
        String color = request.getParameter("color");


        // Print the HTML as a response to the browser
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out =  response.getWriter();
        try {
            out.println("<html>");
            out.println("<head> <title> ColorTextServlet </title> </head>");
            out.println("<body>");
            out.println("<h1 style="color:"+color+">"+text+"</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }
}
Comments (1)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
Thomas
Level 41 , Bayreuth, Germany
15 March, 12:36
not to forget getPart() when working with multipart form data