Содержание
- Httpservletresponse java send error
- HttpServletResponseWrapper
- addCookie
- containsHeader
- encodeURL
- encodeRedirectURL
- encodeUrl
- encodeRedirectUrl
- sendError
- sendError
- sendRedirect
- setDateHeader
- addDateHeader
- setHeader
- addHeader
- setIntHeader
- addIntHeader
- setStatus
- setStatus
- getStatus
- getHeader
- getHeaders
- getHeaderNames
- Httpservletresponse java send error
- HttpServletResponseWrapper
- addCookie
- containsHeader
- encodeURL
- encodeRedirectURL
- encodeUrl
- encodeRedirectUrl
- sendError
- sendError
- sendRedirect
- setDateHeader
- addDateHeader
- setHeader
- addHeader
- setIntHeader
- addIntHeader
- setStatus
- setStatus
- getStatus
- getHeader
- getHeaders
- getHeaderNames
Httpservletresponse java send error
Provides a convenient implementation of the HttpServletResponse interface that can be subclassed by developers wishing to adapt the response from a Servlet. This class implements the Wrapper or Decorator pattern. Methods default to calling through to the wrapped response object.
Since: Servlet 2.3 Author: Various See Also: HttpServletResponse
Field Summary |
---|
Fields inherited from interface javax.servlet.http.HttpServletResponse |
---|
SC_ACCEPTED, SC_BAD_GATEWAY, SC_BAD_REQUEST, SC_CONFLICT, SC_CONTINUE, SC_CREATED, SC_EXPECTATION_FAILED, SC_FORBIDDEN, SC_FOUND, SC_GATEWAY_TIMEOUT, SC_GONE, SC_HTTP_VERSION_NOT_SUPPORTED, SC_INTERNAL_SERVER_ERROR, SC_LENGTH_REQUIRED, SC_METHOD_NOT_ALLOWED, SC_MOVED_PERMANENTLY, SC_MOVED_TEMPORARILY, SC_MULTIPLE_CHOICES, SC_NO_CONTENT, SC_NON_AUTHORITATIVE_INFORMATION, SC_NOT_ACCEPTABLE, SC_NOT_FOUND, SC_NOT_IMPLEMENTED, SC_NOT_MODIFIED, SC_OK, SC_PARTIAL_CONTENT, SC_PAYMENT_REQUIRED, SC_PRECONDITION_FAILED, SC_PROXY_AUTHENTICATION_REQUIRED, SC_REQUEST_ENTITY_TOO_LARGE, SC_REQUEST_TIMEOUT, SC_REQUEST_URI_TOO_LONG, SC_REQUESTED_RANGE_NOT_SATISFIABLE, SC_RESET_CONTENT, SC_SEE_OTHER, SC_SERVICE_UNAVAILABLE, SC_SWITCHING_PROTOCOLS, SC_TEMPORARY_REDIRECT, SC_UNAUTHORIZED, SC_UNSUPPORTED_MEDIA_TYPE, SC_USE_PROXY |
Constructor Summary |
---|
HttpServletResponseWrapper (HttpServletResponse response) Constructs a response adaptor wrapping the given response. |
Method Summary | |
---|---|
void | addCookie (Cookie cookie) The default behavior of this method is to call addCookie(Cookie cookie) on the wrapped response object. |
void | addDateHeader (java.lang.String name, long date) The default behavior of this method is to call addDateHeader(String name, long date) on the wrapped response object. |
void | addHeader (java.lang.String name, java.lang.String value) The default behavior of this method is to return addHeader(String name, String value) on the wrapped response object. |
void | addIntHeader (java.lang.String name, int value) The default behavior of this method is to call addIntHeader(String name, int value) on the wrapped response object. |
boolean | containsHeader (java.lang.String name) The default behavior of this method is to call containsHeader(String name) on the wrapped response object. |
java.lang.String | encodeRedirectUrl (java.lang.String url) Deprecated. As of version 2.1, use encodeRedirectURL(String url) instead |
java.lang.String | encodeRedirectURL (java.lang.String url) The default behavior of this method is to return encodeRedirectURL(String url) on the wrapped response object. |
java.lang.String | encodeUrl (java.lang.String url) Deprecated. As of version 2.1, use encodeURL(String url) instead |
java.lang.String | encodeURL (java.lang.String url) The default behavior of this method is to call encodeURL(String url) on the wrapped response object. |
java.lang.String | getHeader (java.lang.String name) The default behaviour of this method is to call HttpServletResponse#getHeader on the wrapped response object. |
java.util.Collection | getHeaderNames () The default behaviour of this method is to call HttpServletResponse#getHeaderNames on the wrapped response object. |
java.util.Collection | getHeaders (java.lang.String name) The default behaviour of this method is to call HttpServletResponse#getHeaders on the wrapped response object. |
int | getStatus () The default behaviour of this method is to call HttpServletResponse#getStatus on the wrapped response object. |
void | sendError (int sc) The default behavior of this method is to call sendError(int sc) on the wrapped response object. |
void | sendError (int sc, java.lang.String msg) The default behavior of this method is to call sendError(int sc, String msg) on the wrapped response object. |
void | sendRedirect (java.lang.String location) The default behavior of this method is to return sendRedirect(String location) on the wrapped response object. |
void | setDateHeader (java.lang.String name, long date) The default behavior of this method is to call setDateHeader(String name, long date) on the wrapped response object. |
void | setHeader (java.lang.String name, java.lang.String value) The default behavior of this method is to return setHeader(String name, String value) on the wrapped response object. |
void | setIntHeader (java.lang.String name, int value) The default behavior of this method is to call setIntHeader(String name, int value) on the wrapped response object. |
void | setStatus (int sc) The default behavior of this method is to call setStatus(int sc) on the wrapped response object. |
void | setStatus (int sc, java.lang.String sm) Deprecated. As of version 2.1, due to ambiguous meaning of the message parameter. To set a status code use setStatus(int) , to send an error with a description use sendError(int, String) |
Methods inherited from class javax.servlet.ServletResponseWrapper |
---|
flushBuffer, getBufferSize, getCharacterEncoding, getContentType, getLocale, getOutputStream, getResponse, getWriter, isCommitted, isWrapperFor, isWrapperFor, reset, resetBuffer, setBufferSize, setCharacterEncoding, setContentLength, setContentType, setLocale, setResponse |
Methods inherited from class java.lang.Object |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Methods inherited from interface javax.servlet.ServletResponse |
---|
flushBuffer, getBufferSize, getCharacterEncoding, getContentType, getLocale, getOutputStream, getWriter, isCommitted, reset, resetBuffer, setBufferSize, setCharacterEncoding, setContentLength, setContentType, setLocale |
Constructor Detail |
---|
HttpServletResponseWrapper
Throws: java.lang.IllegalArgumentException — if the response is null
Method Detail |
---|
addCookie
Specified by: addCookie in interface HttpServletResponse Parameters: cookie — the Cookie to return to the client
Specified by: containsHeader in interface HttpServletResponse Parameters: name — the header name Returns: true if the named response header has already been set; false otherwise
encodeURL
Specified by: encodeURL in interface HttpServletResponse Parameters: url — the url to be encoded. Returns: the encoded URL if encoding is needed; the unchanged URL otherwise.
encodeRedirectURL
Specified by: encodeRedirectURL in interface HttpServletResponse Parameters: url — the url to be encoded. Returns: the encoded URL if encoding is needed; the unchanged URL otherwise. See Also: HttpServletResponse.sendRedirect(java.lang.String) , HttpServletResponse.encodeUrl(java.lang.String)
encodeUrl
The default behavior of this method is to call encodeUrl(String url) on the wrapped response object.
Specified by: encodeUrl in interface HttpServletResponse Parameters: url — the url to be encoded. Returns: the encoded URL if encoding is needed; the unchanged URL otherwise.
encodeRedirectUrl
The default behavior of this method is to return encodeRedirectUrl(String url) on the wrapped response object.
Specified by: encodeRedirectUrl in interface HttpServletResponse Parameters: url — the url to be encoded. Returns: the encoded URL if encoding is needed; the unchanged URL otherwise.
sendError
Specified by: sendError in interface HttpServletResponse Parameters: sc — the error status code msg — the descriptive message Throws: java.io.IOException — If an input or output exception occurs
sendError
Specified by: sendError in interface HttpServletResponse Parameters: sc — the error status code Throws: java.io.IOException — If an input or output exception occurs
sendRedirect
Specified by: sendRedirect in interface HttpServletResponse Parameters: location — the redirect location URL Throws: java.io.IOException — If an input or output exception occurs
Specified by: addDateHeader in interface HttpServletResponse Parameters: name — the name of the header to set date — the additional date value See Also: HttpServletResponse.setDateHeader(java.lang.String, long)
Specified by: setHeader in interface HttpServletResponse Parameters: name — the name of the header value — the header value If it contains octet string, it should be encoded according to RFC 2047 (http://www.ietf.org/rfc/rfc2047.txt) See Also: HttpServletResponse.containsHeader(java.lang.String) , HttpServletResponse.addHeader(java.lang.String, java.lang.String)
Specified by: addHeader in interface HttpServletResponse Parameters: name — the name of the header value — the additional header value If it contains octet string, it should be encoded according to RFC 2047 (http://www.ietf.org/rfc/rfc2047.txt) See Also: HttpServletResponse.setHeader(java.lang.String, java.lang.String)
Specified by: addIntHeader in interface HttpServletResponse Parameters: name — the name of the header value — the assigned integer value See Also: HttpServletResponse.setIntHeader(java.lang.String, int)
setStatus
setStatus
The default behavior of this method is to call setStatus(int sc, String sm) on the wrapped response object.
Specified by: setStatus in interface HttpServletResponse Parameters: sc — the status code sm — the status message
getStatus
Specified by: getStatus in interface HttpServletResponse Returns: the current status code of the wrapped response
Specified by: getHeader in interface HttpServletResponse Parameters: name — the name of the response header whose value to return Returns: the value of the response header with the given name, or null if no header with the given name has been set on the wrapped response Since: Servlet 3.0
Any changes to the returned Collection must not affect this HttpServletResponseWrapper .
Specified by: getHeaders in interface HttpServletResponse Parameters: name — the name of the response header whose values to return Returns: a (possibly empty) Collection of the values of the response header with the given name Since: Servlet 3.0
Any changes to the returned Collection must not affect this HttpServletResponseWrapper .
Specified by: getHeaderNames in interface HttpServletResponse Returns: a (possibly empty) Collection of the names of the response headers Since: Servlet 3.0
|
|||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
Submit a bug or feature
Copyright © 2009-2011, Oracle Corporation and/or its affiliates. All Rights Reserved. Use is subject to license terms.
Источник
Httpservletresponse java send error
Обеспечивает удобную реализацию интерфейса HttpServletResponse, который может быть разделен на подклассы разработчиками, желающими адаптировать ответ от Сервлета. Этот class реализует Обертку или Шаблон «декоратор». Значение по умолчанию методов к вызову через к обернутому объекту ответа.
С тех пор: Сервлет 2.3 Автор: Различный См. Также: HttpServletResponse
Полевая Сводка |
---|
Поля, наследованные от интерфейса javax.servlet.http. HttpServletResponse |
---|
SC_ACCEPTED, SC_BAD_GATEWAY, SC_BAD_REQUEST, SC_CONFLICT, SC_CONTINUE, SC_CREATED, SC_EXPECTATION_FAILED, SC_FORBIDDEN, SC_FOUND, SC_GATEWAY_TIMEOUT, SC_GONE, SC_HTTP_VERSION_NOT_SUPPORTED, SC_INTERNAL_SERVER_ERROR, SC_LENGTH_REQUIRED, SC_METHOD_NOT_ALLOWED, SC_MOVED_PERMANENTLY, SC_MOVED_TEMPORARILY, SC_MULTIPLE_CHOICES, SC_NO_CONTENT, SC_NON_AUTHORITATIVE_INFORMATION, SC_NOT_ACCEPTABLE, SC_NOT_FOUND, SC_NOT_IMPLEMENTED, SC_NOT_MODIFIED, SC_OK, SC_PARTIAL_CONTENT, SC_PAYMENT_REQUIRED, SC_PRECONDITION_FAILED, SC_PROXY_AUTHENTICATION_REQUIRED, SC_REQUEST_ENTITY_TOO_LARGE, SC_REQUEST_TIMEOUT, SC_REQUEST_URI_TOO_LONG, SC_REQUESTED_RANGE_NOT_SATISFIABLE, SC_RESET_CONTENT, SC_SEE_OTHER, SC_SERVICE_UNAVAILABLE, SC_SWITCHING_PROTOCOLS, SC_TEMPORARY_REDIRECT, SC_UNAUTHORIZED, SC_UNSUPPORTED_MEDIA_TYPE, SC_USE_PROXY |
Сводка конструктора |
---|
HttpServletResponseWrapper (HttpServletResponse response) Создает адаптер ответа, обертывающий данный ответ. |
Сводка метода | |
---|---|
void | addCookie (Cookie cookie) Поведение значения по умолчанию этого метода должно вызвать addCookie (cookie Cookie) на обернутом объекте ответа. |
void | addDateHeader (java.lang.String name, long date) Поведение значения по умолчанию этого метода должно вызвать addDateHeader (Имя строки, отдаленный срок) на обернутом объекте ответа. |
void | addHeader (java.lang.String name, java.lang.String value) Поведение значения по умолчанию этого метода должно возвратить addHeader (Имя строки, Строковое значение) на обернутом объекте ответа. |
void | addIntHeader (java.lang.String name, int value) Поведение значения по умолчанию этого метода должно вызвать addIntHeader (Имя строки, международное значение) на обернутом объекте ответа. |
boolean | containsHeader (java.lang.String name) Поведение значения по умолчанию этого метода должно вызвать containsHeader (Имя строки) на обернутом объекте ответа. |
java.lang.String | encodeRedirectUrl (java.lang.String url) Осуждаемый. С версии 2.1 использовать encodeRedirectURL(String url) вместо этого |
java.lang.String | encodeRedirectURL (java.lang.String url) Поведение значения по умолчанию этого метода должно возвратить encodeRedirectURL (Строковый url) на обернутом объекте ответа. |
java.lang.String | encodeUrl (java.lang.String url) Осуждаемый. С версии 2.1 использовать encodeURL(String url) вместо этого |
java.lang.String | encodeURL (java.lang.String url) Поведение значения по умолчанию этого метода должно вызвать encodeURL (Строковый url) на обернутом объекте ответа. |
java.lang.String | getHeader (java.lang.String name) Поведение значения по умолчанию этого метода состоит в том, чтобы вызвать HttpServletResponse#getHeader на обернутом объекте ответа. |
java.util.Collection | getHeaderNames () Поведение значения по умолчанию этого метода состоит в том, чтобы вызвать HttpServletResponse#getHeaderNames на обернутом объекте ответа. |
java.util.Collection | getHeaders (java.lang.String name) Поведение значения по умолчанию этого метода состоит в том, чтобы вызвать HttpServletResponse#getHeaders на обернутом объекте ответа. |
int | getStatus () Поведение значения по умолчанию этого метода состоит в том, чтобы вызвать HttpServletResponse#getStatus на обернутом объекте ответа. |
void | sendError (int sc) Поведение значения по умолчанию этого метода должно вызвать sendError (международный кв/см) на обернутом объекте ответа. |
void | sendError (int sc, java.lang.String msg) Поведение значения по умолчанию этого метода должно вызвать sendError (международный кв/см, Строковое сообщение) на обернутом объекте ответа. |
void | sendRedirect (java.lang.String location) Поведение значения по умолчанию этого метода должно возвратить sendRedirect (Строковое расположение) на обернутом объекте ответа. |
void | setDateHeader (java.lang.String name, long date) Поведение значения по умолчанию этого метода должно вызвать setDateHeader (Имя строки, отдаленный срок) на обернутом объекте ответа. |
void | setHeader (java.lang.String name, java.lang.String value) Поведение значения по умолчанию этого метода должно возвратить setHeader (Имя строки, Строковое значение) на обернутом объекте ответа. |
void | setIntHeader (java.lang.String name, int value) Поведение значения по умолчанию этого метода должно вызвать setIntHeader (Имя строки, международное значение) на обернутом объекте ответа. |
void | setStatus (int sc) Поведение значения по умолчанию этого метода должно вызвать setStatus (международный кв/см) на обернутом объекте ответа. |
void | setStatus (int sc, java.lang.String sm) Осуждаемый. С версии 2.1, из-за неоднозначного значения параметра сообщения. Установить использование кода состояния setStatus(int) , отправить ошибку с использованием описания sendError(int, String) |
Методы, наследованные от class javax.servlet. ServletResponseWrapper |
---|
flushBuffer, getBufferSize, getCharacterEncoding, getContentType, getLocale, getOutputStream, getResponse, getWriter, isCommitted, isWrapperFor, isWrapperFor, reset, resetBuffer, setBufferSize, setCharacterEncoding, setContentLength, setContentType, setLocale, setResponse |
Методы, наследованные от class java.lang. Объект |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Методы, наследованные от интерфейса javax.servlet. ServletResponse |
---|
flushBuffer, getBufferSize, getCharacterEncoding, getContentType, getLocale, getOutputStream, getWriter, isCommitted, reset, resetBuffer, setBufferSize, setCharacterEncoding, setContentLength, setContentType, setLocale |
Деталь конструктора |
---|
HttpServletResponseWrapper
Броски: java.lang.IllegalArgumentException — если ответ является нулем
Деталь метода |
---|
addCookie
Определенный: addCookie в интерфейсе HttpServletResponse Параметры: cookie — Cookie, чтобы возвратиться к клиенту
Определенный: containsHeader в интерфейсе HttpServletResponse Параметры: name — имя заголовка Возвраты: true если именованный заголовок ответа был уже установлен; false иначе
encodeURL
Определенный: encodeURL в интерфейсе HttpServletResponse Параметры: url — url, который будет закодирован. Возвраты: закодированный URL, если кодирование необходимо; неизменный URL иначе.
encodeRedirectURL
Определенный: encodeRedirectURL в интерфейсе HttpServletResponse Параметры: url — url, который будет закодирован. Возвраты: закодированный URL, если кодирование необходимо; неизменный URL иначе. См. Также: HttpServletResponse.sendRedirect(java.lang.String) , HttpServletResponse.encodeUrl(java.lang.String)
encodeUrl
Поведение значения по умолчанию этого метода должно вызвать encodeUrl (Строковый url) на обернутом объекте ответа.
Определенный: encodeUrl в интерфейсе HttpServletResponse Параметры: url — url, который будет закодирован. Возвраты: закодированный URL, если кодирование необходимо; неизменный URL иначе.
encodeRedirectUrl
Поведение значения по умолчанию этого метода должно возвратить encodeRedirectUrl (Строковый url) на обернутом объекте ответа.
Определенный: encodeRedirectUrl в интерфейсе HttpServletResponse Параметры: url — url, который будет закодирован. Возвраты: закодированный URL, если кодирование необходимо; неизменный URL иначе.
sendError
Определенный: sendError в интерфейсе HttpServletResponse Параметры: sc — код ошибки msg — дескриптивное сообщение Броски: java.io.IOException — Если исключение ввода или вывода происходит
sendError
Определенный: sendError в интерфейсе HttpServletResponse Параметры: sc — код ошибки Броски: java.io.IOException — Если исключение ввода или вывода происходит
sendRedirect
Определенный: sendRedirect в интерфейсе HttpServletResponse Параметры: location — расположение перенаправления URL Броски: java.io.IOException — Если исключение ввода или вывода происходит
Определенный: addDateHeader в интерфейсе HttpServletResponse Параметры: name — имя заголовка, чтобы установить date — дополнительное значение даты См. Также: HttpServletResponse.setDateHeader(java.lang.String, long)
Определенный: setHeader в интерфейсе HttpServletResponse Параметры: name — имя заголовка value — значение заголовка, Если это содержит строку октета, это должно быть закодировано согласно RFC 2047 (http://www.ietf.org/rfc/rfc2047.txt) См. Также: HttpServletResponse.containsHeader(java.lang.String) , HttpServletResponse.addHeader(java.lang.String, java.lang.String)
Определенный: addHeader в интерфейсе HttpServletResponse Параметры: name — имя заголовка value — дополнительный заголовок оценивает, Если он содержит строку октета, он должен быть закодирован согласно RFC 2047 (http://www.ietf.org/rfc/rfc2047.txt) См. Также: HttpServletResponse.setHeader(java.lang.String, java.lang.String)
Определенный: addIntHeader в интерфейсе HttpServletResponse Параметры: name — имя заголовка value — присвоенное целочисленное значение См. Также: HttpServletResponse.setIntHeader(java.lang.String, int)
setStatus
setStatus
Поведение значения по умолчанию этого метода должно вызвать setStatus (международный кв/см, Строковый см) на обернутом объекте ответа.
Определенный: setStatus в интерфейсе HttpServletResponse Параметры: sc — код состояния sm — сообщение о состоянии
getStatus
Определенный: getStatus в интерфейсе HttpServletResponse Возвраты: код текущего статуса обернутого ответа
Определенный: getHeader в интерфейсе HttpServletResponse Параметры: name — имя заголовка ответа, чье значение, чтобы возвратиться Возвраты: значение заголовка ответа с именем, или null, если никакой заголовок с именем не был установлен на обернутом ответе С тех пор: Сервлет 3.0
Любые изменения к возвращенному Collection не должен влиять на это HttpServletResponseWrapper .
Определенный: getHeaders в интерфейсе HttpServletResponse Параметры: name — имя заголовка ответа, чьи значения, чтобы возвратиться Возвраты: (возможно пустой) Collection из значений заголовка ответа с именем С тех пор: Сервлет 3.0
Любые изменения к возвращенному Collection не должен влиять на это HttpServletResponseWrapper .
Определенный: getHeaderNames в интерфейсе HttpServletResponse Возвраты: (возможно пустой) Collection из имен заголовков ответа С тех пор: Сервлет 3.0
|
|||||||
ПРЕДЫДУЩИЙ КЛАСС СЛЕДУЮЩИЙ КЛАСС | ФРЕЙМЫ НИКАКИЕ ФРЕЙМЫ | ||||||
СВОДКА: ВЛОЖЕННЫЙ | ПОЛЕ | CONSTR | МЕТОД | ДЕТАЛЬ: ПОЛЕ | CONSTR | МЕТОД |
Представьте ошибку или функцию
Авторское право © 2009-2011, Oracle Corporation и/или его филиалы. Все права защищены. Использование подвергается срокам действия лицензии.
Сгенерированный на 10-February-2011 12:41
Источник
I’m working on a RESTful web service in Java. I need a good way to send error messages to the client if something’s wrong.
According to the Javadoc, HttpServletResponse.setStatus(int status, String message)
is deprecated «due to ambiguous meaning of the message parameter.»
Is there a preferred way to set the status message or «reason phrase» of the response? The sendError(int, String)
method doesn’t do it.
Edit: To clarify, I want to modify the HTTP status line, i.e. "HTTP/1.1 404 Not Found"
, not the body content. Specifically, I’d like to send responses like "HTTP/1.1 400 Missing customerNumber parameter"
.
Or I want to modify the HTTP status line to say something like 227 IM Used
— in other words: an HTTP Status Description different from what the web-server would know to send.
Ian Boyd
242k247 gold badges857 silver badges1188 bronze badges
asked Jul 8, 2009 at 22:26
3
I don’t think any RESTful client would expect to look at the reason phrase to figure out what went wrong; most RESTful services I’ve seen/used will send the standard status info and an expanded message in the body of the response. sendError(int, String)
is ideal for that situation.
answered Jul 8, 2009 at 23:38
Hank GayHank Gay
69.3k36 gold badges157 silver badges219 bronze badges
2
If you’re using Tomcat, see the setting org.apache.coyote.USE_CUSTOM_STATUS_MSG_IN_HEADER:
http://tomcat.apache.org/tomcat-5.5-doc/config/systemprops.html
- If this is true custom HTTP status messages will be used within HTTP headers. Users must ensure that any such message is ISO-8859-1 encoded, particularly if user provided input is included in the message, to prevent a possible XSS vulnerability. If not specified the default value of false will be used.
See this page for some detail on the original vulnerability:
http://www.securityfocus.com/archive/1/archive/1/495021/100/0/threaded
Nicktar
5,4981 gold badge27 silver badges43 bronze badges
answered Jul 9, 2009 at 0:58
arsars
118k23 gold badges144 silver badges134 bronze badges
1
After your clarification, I tried this in Tomcat. Executing
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "message goes here");
returns
HTTP/1.1 400 message goes here
as the first line in the response.
There must be a problem with the servlet container you are using.
answered Jul 8, 2009 at 23:12
lazlaz
28.2k5 gold badges53 silver badges50 bronze badges
3
I’m not quite familiar with the ‘best practices’ around REST. But I know the concept is based on HTTP and how it is supposed to work out naturally. So how about using a mime type and simple text inside the body for an application error, like ‘application/myapp-exception’ and some ‘Bla bla’? You can provide a client library for that.
I would not use HTTP response codes for application errors. Because I like to know what’s failing: whether it is my application or my HTTP server.
(I hope, I’ll see some best practice advices here, too.)
answered Jul 8, 2009 at 22:45
cafebabecafebabe
1,3908 silver badges9 bronze badges
2
It’s not really clear what you are trying to accomplish. My first thought was the sendError but you say that does not do what you want… have you looked at creating a set of «error responses», meaning specific xml or JSON content (or whatever you are using as a transfer language) that contains the error message or code and any other useful information?
I did something like that for Spring-mvc based RESTful services a while back and it worked well but you have to pretty much catch and handle every exception to keep the client from getting a generic 500 message or something. The Spring Exception Resolvers worked well for that.
Hope this helps… if not, maybe a little more clarity on what you are trying to accomplish. Sorry if I am being dense and missing something obvious.
answered Jul 8, 2009 at 22:37
cjstehnocjstehno
13.1k4 gold badges42 silver badges56 bronze badges
I think the sendError
should do it, but your application server may be failing… IBM WebSphere 3.5 failed on me a long time ago while Tomcat would propagate the message just fine; see JavaServer Pages (JSP) and JSTL — Error page: preserve header «HTTP/1.x 400 My message»? on the Sun forums.
Eventually I used the following workaround, but this is kind of JSP specific, and may in fact be old:
<%@ page isErrorPage="true" %>
<%
// This attribute is NOT set when calling HttpResponse#setStatus and then
// explicitely incuding this error page using RequestDispatcher#include()
// So: only set by HttpResponse#sendError()
Integer origStatus =
(Integer)request.getAttribute("javax.servlet.error.status_code");
if(origStatus != null) {
String origMessage =
(String)request.getAttribute("javax.servlet.error.message");
if(origMessage != null) {
response.reset();
response.setContentType("text/html");
// deprecated, but works:
response.setStatus(origStatus.intValue(), origMessage);
// would yield recursive error:
// response.sendError(origStatus, origMessage);
}
}
%>
And if you happen to test with Internet Explorer: disable «Show friendly HTTP error messages». (When not disabling that, IE has some odd requirement of some minimum length of the HTML content which, if not met, would —or will— make IE show its own error message instead. See also the registry key HKEY_LOCAL_MACHINESoftwareMicrosoftInternet ExplorerMainErrorThresholds
at Microsoft’s Description of Hypertext Transport Protocol Error Messages.)
answered Jul 8, 2009 at 23:08
ArjanArjan
22.3k11 gold badges60 silver badges71 bronze badges
In Spring powered web application, running on Tomcat I use following bean:
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.springframework.beans.factory.InitializingBean;
public class SystemPropertiesInitializingBean implements InitializingBean {
private Map<String, String> systemProperties;
@Override
public void afterPropertiesSet() throws Exception {
if (null == systemProperties || systemProperties.isEmpty()) {
return;
}
final Set<Entry<String, String>> entrySet = systemProperties.entrySet();
for (final Entry<String, String> entry : entrySet) {
final String key = entry.getKey();
final String value = entry.getValue();
System.setProperty(key, value);
}
}
public void setSystemProperties(final Map<String, String> systemProperties) {
this.systemProperties = systemProperties;
}
}
And in applicationContext.xml:
<bean class="....SystemPropertiesInitializingBean">
<property name="systemProperties">
<map>
<entry key="org.apache.coyote.USE_CUSTOM_STATUS_MSG_IN_HEADER" value="true"/>
</map>
</property>
</bean>
sth
218k53 gold badges277 silver badges364 bronze badges
answered Apr 27, 2010 at 11:46
The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client. The response object encapsulates all information to be returned from the server to the client. In the HTTP protocol, this information is transmitted from the server to the client either by HTTP headers or the message body of the request.
Check out: Servlet + JSP + JDBC + MySQL Examples
- Servlet + JSP + JDBC + MySQL Example
- Registration Form using JSP + Servlet + JDBC + Mysql Example
- Login Form using JSP + Servlet + JDBC + MySQL Example
The HttpServletResponse interface extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies.
The servlet container creates an HttpServletResponse object and passes it as an argument to the servlet’s service methods (doGet, doPost, etc). For instance, here is the signature of the HttpServlet.doGet() method:
protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }
HttpServletResponse Interface Class Diagram
Below class diagram shows a HttpServletResponse interface extends the ServletResponse interface to provide HTTP-specific functionality in sending a response:
HttpServletResponse Interface Example
In this example, we will demonstrate the usage of important HttpServletResponse interface methods:
package net.javaguides.servlet.tutorial.httpservlet; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; 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(urlPatterns = "/httpservletresponse") public class HttpServletResponseExample extends HttpServlet { private static final long serialVersionUID = 1 L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Writing HTML PrintWriter printWriter = response.getWriter(); // Headers response.setHeader("Header-Name", "Header Value"); // Content-Type response.setContentType("text/html"); // Content-Length response.setHeader("Content-Length", "31642"); // Writing Binary Data OutputStream outputStream = response.getOutputStream(); outputStream.write(123); //Redirecting to a Different URL response.sendRedirect("https://javaguides.net"); printWriter.print("<html>"); printWriter.print("<body>"); printWriter.print("<h1>Hello World HttpServlet Class Example</h1>"); printWriter.print("<a href="http://www.javaguides.net">Java Guides</a>"); printWriter.print("</body>"); printWriter.print("</html>"); printWriter.close(); } }
Reference
Servlet 4.0 Basic Examples
- Servlet Life Cycle
- Servlet Interface Example
- GenericServlet Class Example
- HttpServlet Class Example Tutorial
- HttpServlet doGet() Method Example
- HttpServlet doPost() Method Example
- ServletConfig Interface Example
- @WebServlet Annotation Example
- @WebInitParam Annotation Example
- @WebListener Annotation Example
- @WebFilter Annotation Example
- @MultipartConfig Annotation Example
package org.kodejava.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "ResponseStatusServlet", urlPatterns = "/response-status")
public class ResponseStatus extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// All response status is defined in the HttpServletResponse class. We
// can then use these constants value to return process status to the
// browser.
response.setContentType("text/html");
// Let say this servlet only handle request for page name inputForm. So
// when user request for other page name error page not found 404 will
// be returned, otherwise it will be 200 which mean OK.
String page = request.getParameter("page");
if (page != null && page.equals("inputForm")) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
final String message = "The requested page [" + page + "] not found.";
response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
}
}
}
Here is a list of all available status code that are defined in the HttpServletResponse class.
STATUS CODE | DESCRIPTION |
---|---|
SC_ACCEPTED | Status code (202) indicating that a request was accepted for processing, but was not completed |
SC_BAD_GATEWAY | Status code (502) indicating that the HTTP server received an invalid response from a server it consulted when acting as a proxy or gateway |
SC_BAD_REQUEST | Status code (400) indicating the request sent by the client was syntactically incorrect |
SC_CONFLICT | Status code (409) indicating that the request could not be completed due to a conflict with the current state of the resource |
SC_CONTINUE | Status code (100) indicating the client can continue |
SC_CREATED | Status code (201) indicating the request succeeded and created a new resource on the server |
SC_EXPECTATION_FAILED | Status code (417) indicating that the server could not meet the expectation given in the Expect request header |
SC_FORBIDDEN | Status code (403) indicating the server understood the request but refused to fulfill it |
SC_FOUND | Status code (302) indicating that the resource reside temporarily under a different URI |
SC_GATEWAY_TIMEOUT | Status code (504) indicating that the server did not receive a timely response from the upstream server while acting as a gateway or proxy |
SC_GONE | Status code (410) indicating that the resource is no longer available at the server and no forwarding address is known |
SC_HTTP_VERSION_NOT_SUPPORTED | Status code (505) indicating that the server does not support or refuses to support the HTTP protocol version that was used in the request message |
SC_INTERNAL_SERVER_ERROR | Status code (500) indicating an error inside the HTTP server which prevented it from fulfilling the request |
SC_LENGTH_REQUIRED | Status code (411) indicating that the request cannot be handled without a defined Content-Length |
SC_METHOD_NOT_ALLOWED | Status code (405) indicating that the method specified in the Request-Line is not allowed for the resource identified by the Request-URI |
SC_MOVED_PERMANENTLY | Status code (301) indicating that the resource has permanently moved to a new location, and that future references should use a new URI with their requests |
SC_MOVED_TEMPORARILY | Status code (302) indicating that the resource has temporarily moved to another location, but that future references should still use the original URI to access the resource |
SC_MULTIPLE_CHOICES | Status code (300) indicating that the requested resource corresponds to any one of a set of representations, each with its own specific location |
SC_NO_CONTENT | Status code (204) indicating that the request succeeded but that there was no new information to return |
SC_NON_AUTHORITATIVE_INFORMATION | Status code (203) indicating that the meta information presented by the client did not originate from the server |
SC_NOT_ACCEPTABLE | Status code (406) indicating that the resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request |
SC_NOT_FOUND | Status code (404) indicating that the requested resource is not available |
SC_NOT_IMPLEMENTED | Status code (501) indicating the HTTP server does not support the functionality needed to fulfill the request |
SC_NOT_MODIFIED | Status code (304) indicating that a conditional GET operation found that the resource was available and not modified |
SC_OK | Status code (200) indicating the request succeeded normally |
SC_PARTIAL_CONTENT | Status code (206) indicating that the server has fulfilled the partial GET request for the resource |
SC_PAYMENT_REQUIRED | Status code (402) reserved for future use |
SC_PRECONDITION_FAILED | Status code (412) indicating that the precondition given in one or more of the request-header fields evaluated to false when it was tested on the server |
SC_PROXY_AUTHENTICATION_REQUIRED | Status code (407) indicating that the client MUST first authenticate itself with the proxy |
SC_REQUEST_ENTITY_TOO_LARGE | Status code (413) indicating that the server is refusing to process the request because the request entity is larger than the server is willing or able to process |
SC_REQUEST_TIMEOUT | Status code (408) indicating that the client did not produce a request within the time that the server was prepared to wait |
SC_REQUEST_URI_TOO_LONG | Status code (414) indicating that the server is refusing to service the request because the Request-URI is longer than the server is willing to interpret |
SC_REQUESTED_RANGE_NOT_SATISFIABLE | Status code (416) indicating that the server cannot serve the requested byte range |
SC_RESET_CONTENT | Status code (205) indicating that the agent SHOULD reset the document view which caused the request to be sent |
SC_SEE_OTHER | Status code (303) indicating that the response to the request can be found under a different URI |
SC_SERVICE_UNAVAILABLE | Status code (503) indicating that the HTTP server is temporarily overloaded, and unable to handle the request |
SC_SWITCHING_PROTOCOLS | Status code (101) indicating the server is switching protocols according to Upgrade header |
SC_TEMPORARY_REDIRECT | Status code (307) indicating that the requested resource resides temporarily under a different URI |
SC_UNAUTHORIZED | Status code (401) indicating that the request requires HTTP authentication |
SC_UNSUPPORTED_MEDIA_TYPE | Status code (415) indicating that the server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method |
SC_USE_PROXY | Status code (305) indicating that the requested resource MUST be accessed through the proxy given by the Location field |
Maven dependencies
<!--https://search.maven.org/remotecontent?filepath=javax/servlet/javax.servlet-api/4.0.1/javax.servlet-api-4.0.1.jar-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
- Author
- Recent Posts
A programmer, runner, recreational diver, live in the island of Bali, Indonesia. Programming in Java, Spring, Hibernate / JPA. You can support me working on this project, buy me a cup of coffee ☕, every little bit helps, thank you 🙏
Views: 44,264
The HttpServlet class request processing methods take two parameters.
- javax.servlet.http.HttpRequest
- javax.servlet.http.HttpResponse
The HttpServletResponse object generates a response to return to the requesting client. Its methods allow you to set the response header and the response body.
The first line of the Response header (response.setContentType(“text/html”);) identifies the MIME type of the response. The following three lines are often placed in servlet code to prevent Web browsers and proxy servers from caching dynamically-generated Web pages. If you want your dynamic Web page to be cached, remove these three lines of code.
The response object also has the getWriter() method to return a PrintWriter object. The print() and println() methods of the PrintWriter object write the servlet response back to the client.
For instance, here is the signature of the HttpServlet.doGet() method:
protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }
Popular Tutorials
- Spring Tutorial
- Spring MVC Web Tutorial
- Spring Boot Tutorial
- Spring Security Tutorial
- Spring AOP Tutorial
- Spring JDBC Tutorial
- Spring HATEOAS
- Microservices with Spring Boot
- REST Webservice
- Core Java
- Hibernate Tutorial
- Spring Batch
In this text I will look at the HttpResponse object.
The purpose of the HttpResponse object is to represent the HTTP response your web application sends back to the browser, in response to the HTTP request the browser send to your web application.
Methods to Set HTTP Response Header:
There are following methods which can be used to set HTTP response header in your servlet program. These methods are available with HttpServletResponse object.
1 String encodeRedirectURL(String url)
Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged.
2 String encodeURL(String url)
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged.
3 boolean containsHeader(String name)
Returns a boolean indicating whether the named response header has already been set.
4 boolean isCommitted()
Returns a boolean indicating if the response has been committed.
5 void addCookie(Cookie cookie)
Adds the specified cookie to the response.
6 void addDateHeader(String name, long date)
Adds a response header with the given name and date-value.
7 void addHeader(String name, String value)
Adds a response header with the given name and value.
8 void addIntHeader(String name, int value)
Adds a response header with the given name and integer value.
9 void flushBuffer()
Forces any content in the buffer to be written to the client.
10 void reset()
Clears any data that exists in the buffer as well as the status code and headers.
11 void resetBuffer()
Clears the content of the underlying buffer in the response without clearing headers or status code.
12 void sendError(int sc)
Sends an error response to the client using the specified status code and clearing the buffer.
13 void sendError(int sc, String msg)
Sends an error response to the client using the specified status.
14 void sendRedirect(String location)
Sends a temporary redirect response to the client using the specified redirect location URL.
15 void setBufferSize(int size)
Sets the preferred buffer size for the body of the response.
16 void setCharacterEncoding(String charset)
Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.
17 void setContentLength(int len)
Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.
18 void setContentType(String type)
Sets the content type of the response being sent to the client, if the response has not been committed yet.
19 void setDateHeader(String name, long date)
Sets a response header with the given name and date-value.
20 void setHeader(String name, String value)
Sets a response header with the given name and value.
21 void setIntHeader(String name, int value)
Sets a response header with the given name and integer value.
22 void setLocale(Locale loc)
Sets the locale of the response, if the response has not been committed yet.
23 void setStatus(int sc)
Sets the status code for this response.
The HttpResponse object has a lot of methods, so I will just cover the most commonly used here. The rest you can read about in the JavaDoc, if you are interested. The parts I will cover are:
- Writing HTML
- Headers
- Content-Type
- Writing Text
- Content-Length
- Writing Binary Data
- Redirecting to a Different URL
- Writing HTML
To send HTML back to the browser, you have to obtain the a PrintWriter from the HttpResponse object. Here is how:
PrintWriter writer = response.getWriter();
writer.write("<html><body>GET/POST response</body></html>");
Headers
Just like the request object, the HttpRequest can contain HTTP headers. Headers must be set before any data is written to the response. You set a header on the response object like this:
response.setHeader("Header-Name", "Header Value");
As you can see, a response header is a name, value pair.
Content-Type
The Content-Type header is a response header that tells the browser the type of the content you are sending back to it. For instance, the content type for HTML is text/html. Similarly, if what you send back to the browser is plain text, you use the content type text/plain.
Here is how you set the Content-Type header on the HttpResponse object:
response.setHeader("Content-Type", "text/html");
Writing Text
You can write text back to the browser instead of HTML, like this:
response.setHeader("Content-Type", "text/plain"); PrintWriter writer = response.getWriter(); writer.write("This is just plain text");
First the Content-Type header is set to text/plain. Then a plain text string is written to the writer obtained from the response object.
Content-Length
The Content-Length header tells the browser how many bytes your servlet is sending back. If you are sending binary data back you need to set the content length header. Here is how:
response.setHeader("Content-Length", "31642");
Writing Binary Data
You can also write binary data back to the browser instead of text. For instance, you can send an image back, a PDF file or a Flash file or something like that.
Again, you will first have to set the Content-Type header to the type matching the data you are sending back. For instance, the content type for a PNG image is image/png.
You can search for “mime types” in your favourite search engine to find a list of mime types (content types), so you can find the mime type for the content you are sending back.
In order to write binary data back to the browser you cannot use the Writer obtained from response.getWriter(). Afterall, Writer’s are intended for text.
Instead you have to use the OutputStream obtained from the response.getOutputStream() method. Here is how:
OutputStream outputStream = response.getOutputStream(); outputStream.write(...);
Redirecting to a Different URL
You can redirect the browser to a different URL from your servlet. You cannot send any data back to the browser when redirecting. Here is how you redirect:
response.sendRedirect("https://www.dineshonjava.com");
Create the HTTP response
After the servlet request code, add the response code:
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletSample extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Enumeration keys; String key; String myName = ""; keys = request.getParameterNames(); while (keys.hasMoreElements()) { key = (String) keys.nextElement(); if (key.equalsIgnoreCase("myName")) myName = request.getParameter(key); } System.out.println("Name = "); if (myName == "") myName = "Hello"; response.setContentType("text/html"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>Just a basic servlet</title></head>"); out.println("<body>"); out.println("<h1>Just a basic servlet</h1>"); out.println ("<p>" + myName + ", this is a very basic servlet."); out.println("</body></html>"); out.flush(); } }
As discussed in the previous chapter, when a Web server responds to an HTTP request, the response typically consists of a status line, some response headers, a blank line, and the document. A typical response looks like this −
HTTP/1.1 200 OK Content-Type: text/html Header2: ... ... HeaderN: ... (Blank Line) <!doctype ...> <html> <head>...</head> <body> ... </body> </html>
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the example), and a very short message corresponding to the status code (OK in the example).
Following is a summary of the most useful HTTP 1.1 response headers which go back to the browser from web server side and you would use them very frequently in web programming −
Sr.No. | Header & Description |
---|---|
1 |
Allow This header specifies the request methods (GET, POST, etc.) that the server supports. |
2 |
Cache-Control This header specifies the circumstances in which the response document can safely be cached. It can have values public, private or no-cache etc. Public means document is cacheable, Private means document is for a single user and can only be stored in private (non-shared) caches and nocache means document should never be cached. |
3 |
Connection This header instructs the browser whether to use persistent in HTTP connections or not. A value of close instructs the browser not to use persistent HTTP connections and keepalive means using persistent connections. |
4 |
Content-Disposition This header lets you request that the browser ask the user to save the response to disk in a file of the given name. |
5 |
Content-Encoding This header specifies the way in which the page was encoded during transmission. |
6 |
Content-Language This header signifies the language in which the document is written. For example en, en-us, ru, etc |
7 |
Content-Length This header indicates the number of bytes in the response. This information is needed only if the browser is using a persistent (keep-alive) HTTP connection. |
8 |
Content-Type This header gives the MIME (Multipurpose Internet Mail Extension) type of the response document. |
9 |
Expires This header specifies the time at which the content should be considered out-of-date and thus no longer be cached. |
10 |
Last-Modified This header indicates when the document was last changed. The client can then cache the document and supply a date by an If-Modified-Since request header in later requests. |
11 |
Location This header should be included with all responses that have a status code in the 300s. This notifies the browser of the document address. The browser automatically reconnects to this location and retrieves the new document. |
12 |
Refresh This header specifies how soon the browser should ask for an updated page. You can specify time in number of seconds after which a page would be refreshed. |
13 |
Retry-After This header can be used in conjunction with a 503 (Service Unavailable) response to tell the client how soon it can repeat its request. |
14 |
Set-Cookie This header specifies a cookie associated with the page. |
Methods to Set HTTP Response Header
There are following methods which can be used to set HTTP response header in your servlet program. These methods are available with HttpServletResponse object.
Sr.No. | Method & Description |
---|---|
1 |
String encodeRedirectURL(String url) Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. |
2 |
String encodeURL(String url) Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. |
3 |
boolean containsHeader(String name) Returns a Boolean indicating whether the named response header has already been set. |
4 |
boolean isCommitted() Returns a Boolean indicating if the response has been committed. |
5 |
void addCookie(Cookie cookie) Adds the specified cookie to the response. |
6 |
void addDateHeader(String name, long date) Adds a response header with the given name and date-value. |
7 |
void addHeader(String name, String value) Adds a response header with the given name and value. |
8 |
void addIntHeader(String name, int value) Adds a response header with the given name and integer value. |
9 |
void flushBuffer() Forces any content in the buffer to be written to the client. |
10 |
void reset() Clears any data that exists in the buffer as well as the status code and headers. |
11 |
void resetBuffer() Clears the content of the underlying buffer in the response without clearing headers or status code. |
12 |
void sendError(int sc) Sends an error response to the client using the specified status code and clearing the buffer. |
13 |
void sendError(int sc, String msg) Sends an error response to the client using the specified status. |
14 |
void sendRedirect(String location) Sends a temporary redirect response to the client using the specified redirect location URL. |
15 |
void setBufferSize(int size) Sets the preferred buffer size for the body of the response. |
16 |
void setCharacterEncoding(String charset) Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8. |
17 |
void setContentLength(int len) Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header. |
18 |
void setContentType(String type) Sets the content type of the response being sent to the client, if the response has not been committed yet. |
19 |
void setDateHeader(String name, long date) Sets a response header with the given name and date-value. |
20 |
void setHeader(String name, String value) Sets a response header with the given name and value. |
21 |
void setIntHeader(String name, int value) Sets a response header with the given name and integer value |
22 |
void setLocale(Locale loc) Sets the locale of the response, if the response has not been committed yet. |
23 |
void setStatus(int sc) Sets the status code for this response |
HTTP Header Response Example
You already have seen setContentType() method working in previous examples and following example would also use same method, additionally we would use setIntHeader() method to set Refresh header.
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class Refresh extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set refresh, autoload time as 5 seconds response.setIntHeader("Refresh", 5); // Set response content type response.setContentType("text/html"); // Get current time Calendar calendar = new GregorianCalendar(); String am_pm; int hour = calendar.get(Calendar.HOUR); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); if(calendar.get(Calendar.AM_PM) == 0) am_pm = "AM"; else am_pm = "PM"; String CT = hour+":"+ minute +":"+ second +" "+ am_pm; PrintWriter out = response.getWriter(); String title = "Auto Refresh Header Setting"; String docType = "<!doctype html public "-//w3c//dtd html 4.0 " + "transitional//en">n"; out.println(docType + "<html>n" + "<head><title>" + title + "</title></head>n"+ "<body bgcolor = "#f0f0f0">n" + "<h1 align = "center">" + title + "</h1>n" + "<p>Current Time is: " + CT + "</p>n" ); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Now calling the above servlet would display current system time after every 5 seconds as follows. Just run the servlet and wait to see the result −
Auto Refresh Header Setting
Current Time is: 9:44:50 PM