{"id":3384,"date":"2020-05-27T19:22:28","date_gmt":"2020-05-27T13:52:28","guid":{"rendered":"https:\/\/www.h2kinfosys.com\/blog\/?p=3384"},"modified":"2025-12-19T05:43:28","modified_gmt":"2025-12-19T10:43:28","slug":"servlet-request-and-response-objects","status":"publish","type":"post","link":"https:\/\/www.h2kinfosys.com\/blog\/servlet-request-and-response-objects\/","title":{"rendered":"Servlet Request and Response objects"},"content":{"rendered":"\n<p>The servlet container of a web service is responsible for the creation of ServletRequest and Response objects. The servlet container wraps all data that came from a <a href=\"https:\/\/www.h2kinfosys.com\/blog\/installing-web-server-tomcat\/\">client to a web server<\/a> as a request. Also, the servlet container creates a corresponding Servlet Response object, that will be filled with data in a servlet.\u00a0<\/p>\n\n\n\n<p>The container passes the ServletRequest and the Servlet Response objects as an argument to the service() method of a corresponding servlet. The ServletRequest object contains header and body information of data that come with request.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Servlet Request and Response objects<\/strong><\/h2>\n\n\n\n<p>The ServletRequest object is from package javax.servlet.<\/p>\n\n\n\n<p>Probably, the most used method from the ServletRequest interface is the method to get parameters.&nbsp;<\/p>\n\n\n\n<p>Let&#8217;s assume the situation that we have a web page with fields. A user filled some of them and pressed a button to submit changes. This triggers the get request to the server. There is a dispatcher of the servlet that sends a request to the corresponding servlet. All data are wrapped to the ServletRequest. The parameters are contained in the query string or posted form data. To get each parameter that the user filled in the web page we will use methods to get parameters. They are:<\/p>\n\n\n\n<p><em>java.lang.String getParameter(java.lang.String name)<\/em> &#8211; returns the value of parameter by name. The result is null if the parameter does not exist. This method is used when you are sure the parameter has only one value. If the parameter can have more than one value there is another method for it.&nbsp; In the case of many values, the current method will return just the first value.<\/p>\n\n\n\n<p><em>java.lang.String[] getParameterValues(java.lang.String)<\/em> &#8211; returns an array of values of a parameter by name. It returns all of the values the given request parameter has. If the parameter does not exist, it will return null.<\/p>\n\n\n\n<p><em>java.util.Enumeration&lt;java.lang.String&gt; getParameterNames() <\/em>&#8211; returns an Enumeration of String objects containing the names of the parameters contained in this request. It returns an empty Enumeration, if no parameters in the request.<\/p>\n\n\n\n<p><em>java.util.Map&lt;java.lang.String,java.lang.String[]&gt; getParameterMap()<\/em> &#8211; returns the parameters of this request in the form of key-value pairs( java.util.Map).<\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"Java Servlets | Http body Class | Request and Response of HTTP body Class Online | Java Training\" width=\"800\" height=\"450\" src=\"https:\/\/www.youtube.com\/embed\/EGZm0H1pZ9c?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n\n\n\n<p><em>Here is simple example:<\/em><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;web-app&gt;\n&nbsp;&nbsp;&nbsp;&lt;servlet&gt;\n&nbsp;&nbsp; &lt;servlet-name&gt;myservlet&lt;\/servlet-name&gt;\n&nbsp;&nbsp; &lt;servlet-class&gt;edu.test.myservlets.ServletExample&lt;\/servlet-class&gt;\n&nbsp;&nbsp;&nbsp;&lt;\/servlet&gt;\n&nbsp;&nbsp;&nbsp;&lt;servlet-mapping&gt;\n&nbsp;&nbsp; &lt;servlet-name&gt;myservlet&lt;\/servlet-name&gt;\n&nbsp; &lt;url-pattern&gt;\/test\/myservlet&lt;\/url-pattern&gt;\n&nbsp;&nbsp;&nbsp;&lt;\/servlet-mapping&gt;\n&lt;\/web-app&gt;<\/pre>\n\n\n\n<p><em>Our servlet:<\/em><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>package<\/strong> edu.test.myservlets;\n\n<strong>import<\/strong> javax.servlet.http.*;&nbsp;\n<strong>import<\/strong> javax.servlet.*;&nbsp;\n<strong>import<\/strong> java.io.*;&nbsp;\n\n<strong>public<\/strong> <strong>class<\/strong> ServletExample <strong>extends<\/strong> HttpServlet{&nbsp;\n&nbsp;&nbsp;&nbsp;<strong>public<\/strong> <strong>void<\/strong> doGet(HttpServletRequest request, HttpServletResponse response)&nbsp;\n&nbsp;&nbsp;&nbsp;<strong>throws<\/strong> ServletException,IOException&nbsp;\n&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;response.setContentType(\"text\/html\");&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PrintWriter printwriter=response.getWriter();&nbsp;\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String name = request.getParameter(\"username\");\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;printwriter.println(\"Username: \" + name);&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;printwriter.close();&nbsp;\n&nbsp;&nbsp;}\n}<\/pre>\n\n\n<p>[box type=&#8221;shadow&#8221; align=&#8221;&#8221; class=&#8221;&#8221; width=&#8221;&#8221;]<\/p>\n<p><span style=\"font-weight: 400;\">To call our servlet and to pass parameters we can use URL:<br \/><\/span><span style=\"font-weight: 400;\">http:\/\/&lt;host&gt;:&lt;port&gt;\/&lt;mywebapp&gt;\/test\/myservlet?username=TestUser<\/span><\/p>\n<p><span style=\"font-weight: 400;\">We will get the output:<br \/><\/span><i><span style=\"font-weight: 400;\">Username: TestUser<\/span><\/i><\/p>\n<p>[\/box]<\/p>\n\n\n<p><strong><em>To get all parameters we can use this method doGet:<\/em><\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>public<\/strong> <strong>void<\/strong> doGet(HttpServletRequest request, HttpServletResponse response) <strong>throws<\/strong> ServletException, IOException {\nPrintWriter output = response.getWriter();\nresponse.setContentType(\"text\/html\");\nEnumeration en = request.getParameterNames();\n<strong>while<\/strong> (en.hasMoreElements()) {\nObject obj = en.nextElement();\nString param = (String) obj;\nString paramvalue = request.getParameter(param);\noutput.print(\"Parameter Name: \" + param + \" Parameter Value: \" + paramvalue);\n}\noutput.close();\n}<\/pre>\n\n\n\n<p>In our case, we have just one parameter, so the output will be the same as in the previous example.<\/p>\n\n\n\n<p>There are methods in the ServletRequest interface to get HTTP Request Headers. The header is used to pass the additional information about the client to the server. There are methods:<\/p>\n\n\n\n<p>&nbsp;java.lang.String getHeader(java.lang.String name) &#8211; returns single header value by key.<\/p>\n\n\n\n<p>&nbsp;java.util.Enumeration getHeaderNames() &#8211; returns an enumeration of header names.<\/p>\n\n\n\n<p>&nbsp;java.util.Enumeration getHeaders(java.lang.String name) &#8211; returns all the values for a specific header.&nbsp;<\/p>\n\n\n\n<p>As header information can be:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>acceptable media types in response;<\/li>\n\n\n\n<li>acceptable character sets in response;<\/li>\n\n\n\n<li>an acceptable set of languages<\/li>\n\n\n\n<li>authorization, when client is attempting to authenticate itself with a server<\/li>\n\n\n\n<li>host, that indicates the internet host and port number of the resource being requested<\/li>\n\n\n\n<li>User-Agent, that contains the information about the client originating the request<\/li>\n<\/ul>\n\n\n\n<p>Here is the example of getting information about servlet headers:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>package<\/strong> edu.test.myservlets;\n\n<strong>import<\/strong> java.io.IOException;\n<strong>import<\/strong> java.io.PrintWriter;\n<strong>import<\/strong> java.util.Enumeration;\n<strong>import<\/strong> javax.servlet.ServletException;\n<strong>import<\/strong> javax.servlet.http.HttpServlet;\n<strong>import<\/strong> javax.servlet.http.HttpServletRequest;\n<strong>import<\/strong> javax.servlet.http.HttpServletResponse;\n\n<strong>public<\/strong> <strong>class<\/strong> HeaderDetailsServlet <strong>extends<\/strong> HttpServlet {\n\n&nbsp;&nbsp;<strong>public<\/strong> <strong>void<\/strong> doGet(HttpServletRequest request,\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;HttpServletResponse response)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>throws<\/strong> IOException, ServletException&nbsp;\n&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;response.setContentType(\"text\/html\");\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PrintWriter printWriter = response.getWriter();\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;printWriter.println(\"Here is the Header Information:\");\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Enumeration en = request.getHeaderNames();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>while<\/strong> (en.hasMoreElements()) {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String headerName = (String) en.nextElement();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String headerValue = request.getHeader(headerName);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;printWriter.println(headerName + \" \" + headerValue);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;}\n}\n<\/pre>\n\n\n\n<p><strong><em>There is our web.xml:<\/em><\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;web-app&gt;\n&nbsp;&nbsp;&nbsp;&lt;servlet&gt;\n&nbsp;&nbsp; &lt;servlet-name&gt;headerservlet&lt;\/servlet-name&gt;\n&nbsp;&nbsp; &lt;servlet-class&gt;edu.test.myservlets.HeaderDetailsServlet&lt;\/servlet-class&gt;\n&nbsp;&nbsp;&nbsp;&lt;\/servlet&gt;\n&nbsp;&nbsp;&nbsp;&lt;servlet-mapping&gt;\n&nbsp;&nbsp; &lt;servlet-name&gt;headerservlet&lt;\/servlet-name&gt;\n&nbsp; &lt;url-pattern&gt;\/test\/myservlet&lt;\/url-pattern&gt;\n&nbsp;&nbsp;&nbsp;&lt;\/servlet-mapping&gt;\n&lt;\/web-app&gt;<\/pre>\n\n\n\n<p><strong><em>Let&#8217;s look at more methods of ServletRequest:<\/em><\/strong><\/p>\n\n\n\n<p><em>java.lang.String getCharacterEncoding() <\/em>&#8211; returns the name of the character encoding used in the body of this request.<\/p>\n\n\n\n<p><em>java.lang.String getContentType() <\/em>&#8211; returns the MIME type of the request body, or null if the type is not known.<\/p>\n\n\n\n<p><em>java.lang.String getLocalAddr()<\/em>&#8211; returns the IP address of the interface where the request was received.<\/p>\n\n\n\n<p><em>java.util.Locale getLocale()<\/em> &#8211; returns the preferred Locale that the client will accept content in. It is based on the Accept-Language header.<\/p>\n\n\n\n<p><em>java.lang.String getProtocol()<\/em> &#8211; returns the name and version of the protocol the request uses. For example, HTTP\/1.1.<\/p>\n\n\n\n<p><em>java.lang.String getScheme() <\/em>&#8211; returns the name of the scheme used to make this request. E.g: http, https, ftp.<\/p>\n\n\n\n<p><em>boolean isSecure()<\/em> &#8211; returns true if this request was made using a secure channel. For example, HTTPS.<\/p>\n\n\n\n<p><em>ServletInputStream getInputStream()<\/em> &#8211; gets the request body as binary data using a ServletInputStream.<\/p>\n\n\n\n<p><em>Cookie[] getCookies() <\/em>&#8211; returns an array of all the Cookies that were sent by a client with this request.<em>java.lang.String getAuthType()<\/em> &#8211; returns the name of the <a href=\"https:\/\/www.h2kinfosys.com\/blog\/servlet-configuration-and-context\/\">servlet authentication type<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>ServletResponse interface<\/strong><\/h2>\n\n\n\n<p>ServletResponse object assists a servlet in sending a response to the client. The servlet container is responsible for the creation of a ServletResponse object. After creation, it passes ServletResponse object as an argument to the service method of the servlet.<\/p>\n\n\n\n<p>If we need to send binary data in a MIME body response, better to use the ServletOutputStream returned by getOutputStream(). In the case of sending character data, it is better to use the PrintWriter object returned by getWriter(). If we need to send a mix of binary and text data, it is good to use a ServletOutputStream and work on the character sections manually.<\/p>\n\n\n\n<p>You can specify charset for the MIME body response explicitly, by using the <a href=\"https:\/\/chrome.google.com\/webstore\/detail\/set-character-encoding\/bpojelgakakmcfmjfilgdlmhefphglae?hl=en\" rel=\"nofollow noopener\" target=\"_blank\">setCharacterEncoding<\/a>(java.lang.String) and setContentType(java.lang.String) methods. Also, we can do this implicitly by using the setLocale(java.util.Locale) method. The ISO-8859-1 is used as default charset. The setCharacterEncoding, setContentType, setLocale method must be called before getWriter and before committing the response for the character encoding to be used.<\/p>\n\n\n\n<p><strong>Let&#8217;s look at the example where we will utilize the two most used methods setContentType and getWriter:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>package<\/strong> edu.myservlets.example;\n\n<strong>import<\/strong> java.io.*;\n<strong>import<\/strong> javax.servlet.*;\n<strong>import<\/strong> javax.servlet.http.*;\n\n\/\/ we are extending HttpServlet class\n<strong>public<\/strong> <strong>class<\/strong> ServletResponseExample <strong>extends<\/strong> HttpServlet {\n\n<strong>public<\/strong> <strong>void<\/strong> doGet(HttpServletRequest request, HttpServletResponse response) <strong>throws<\/strong> ServletException, IOException {\n\n\/\/ Set response content type\nresponse.setContentType(\"text\/html\");\n\nPrintWriter out = response.getWriter();\nout.print(\"&lt;html&gt;&lt;body&gt;&lt;h1&gt;\");\nout.print(\"This is our HTML response\");\nout.print(\"&lt;\/h1&gt;&lt;\/body&gt;&lt;\/html&gt;\");\nout.close();\n}\n}\n\nLet's look at one more example that will open our response in Excel:\n\n<strong>package<\/strong> edu.myservlets.example;\n\n<strong>import<\/strong> java.io.*;\n\n<strong>import<\/strong> javax.servlet.*;\n<strong>import<\/strong> javax.servlet.http.*;\n\n\/\/ we are extending HttpServlet class\n<strong>public<\/strong> <strong>class<\/strong> ServletResponseExcelExample <strong>extends<\/strong> HttpServlet {\n\n<strong>public<\/strong> <strong>void<\/strong> doGet(HttpServletRequest request, HttpServletResponse response) <strong>throws<\/strong> ServletException, IOException {\n\n\/\/ Set response content type\nresponse.setContentType(\"application\/vnd.ms-excel\");\n\nPrintWriter out = response.getWriter();\nout.println(\"Name\\t Surname\\t Age\");\nout.println(\"Mickey\\t Mouse\\t 6\");&nbsp;&nbsp;\nout.println(\"Minnie\\t Mouse\\t 6\");\nout.close();\n}\n}\n<\/pre>\n\n\n\n<p><strong>Here are more methods of the ServletResponse interface:<\/strong><\/p>\n\n\n\n<p><em>String getCharacterEncoding()<\/em> &#8211; returns the character encoding (MIME charset) used for the response body. For example, UTF-8.<\/p>\n\n\n\n<p><em>String getContentType()<\/em> &#8211; returns a String specifying the content type. For example, text\/html; charset=UTF-8. If content type was not specified, this method returns null.<\/p>\n\n\n\n<p><em>ServletOutputStream getOutputStream()<\/em> &#8211; returns ServletOutputStream object, that is suitable for writing binary data in the response. We need to call flush() on the ServletOutputStream to commit the response.<\/p>\n\n\n\n<p><em>void setCharacterEncoding(String charset)<\/em> &#8211; sets the character encoding of the response being sent to the client. This method overrides the character encoding that was set by different methods(<em>setContentType(java.lang.String)<\/em> or <em>setLocale(java.util.Locale)<\/em>).<\/p>\n\n\n\n<p><em>void setContentLength(int length)<\/em> &#8211; sets the content body length in the response for HTTP servlet. This method sets the <a href=\"https:\/\/en.wikipedia.org\/wiki\/HTTP\" rel=\"nofollow noopener\" target=\"_blank\">HTTP<\/a> Content-Length header. The integer value is used as input. There is the method that does the same, but get long as input data <em>void setContentLengthLong(long length).<\/em><\/p>\n\n\n\n<p><em>void setContentType(String type) &#8211; <\/em>the method sets the type of the response content being sent to the client. This method can be called several times. But, the method has no effect if called after the response has been committed. Servlet Containers need to know the content type and the character encoding of the servlet response and communicate them with the client.&nbsp;<\/p>\n\n\n\n<p><em>void setBufferSize(int size)<\/em> &#8211; sets the buffer size for the response body.&nbsp;<\/p>\n\n\n\n<p>A larger buffer allows more content before anything is actually sent at once. But, a smaller buffer allows the client to start receiving data more quickly. Also, it decreases the server memory load.<\/p>\n\n\n\n<p><em>int getBufferSize()<\/em> &#8211; method to get buffer size of the response body.<\/p>\n\n\n\n<p><em>void flushBuffer()<\/em> &#8211; forces any content in the buffer to be sent to the client. It automatically commits the response with the status code and headers will be written.<\/p>\n\n\n\n<p><em>void reset() <\/em>&#8211; clears all data that exists in the buffer. The status code, headers will be also cleared. The state of calling getWriter() or getOutputStream() is also cleared.&nbsp;<em>boolean isCommitted()<\/em> &#8211; returns true if the response has been commited<\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The servlet container of a web service is responsible for the creation of ServletRequest and Response objects. The servlet container wraps all data that came from a client to a web server as a request. Also, the servlet container creates a corresponding Servlet Response object, that will be filled with data in a servlet.\u00a0 The [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":3388,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[42],"tags":[831,832,830,828,829],"class_list":["post-3384","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java-tutorials","tag-http-servlet","tag-servlet-container","tag-servlet-headers","tag-servlet-request","tag-servlet-response"],"_links":{"self":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/3384","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/comments?post=3384"}],"version-history":[{"count":1,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/3384\/revisions"}],"predecessor-version":[{"id":33154,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/3384\/revisions\/33154"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media\/3388"}],"wp:attachment":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media?parent=3384"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/categories?post=3384"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/tags?post=3384"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}