Servlet doFilter setAttributes not available in Servlet - servlets

I'm trying to add an Attribute to the request via doFilter before passing it to the Servlet, so that a value in JSTL will be set. I simply do req.setAttribute("b", "blah") in the filter, but it doesn't seem to get set in the JSTL file. How would I do this?

It's hard to pinpoint the root cause without seeing the code. There are several possible causes.
You're sending a redirect after setting the attribute instead of continuing with the same request.
You're accessing the attribute with the wrong name (case sensitive!).
You're accessing the attribute the wrong way.
The attribute is been overridden somewhere further down in the request processing.
There's a page scoped attribute with the same name which has no value.
You're misinterpreting the results.
Etc.
By the way, there's no such thing as a "JSTL file". Perhaps you meant "JSP file".

The problem is that the doFilter method uses ServletRequest instead of HttpServletRequest which is the one that has the setAttribute method. Most of my filters are something like this:
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
// do what you must...
chain.doFilter(servletRequest, servletResponse);
}

Related

Sending response after chain.doFilter in filters

I am new to Servlets. In the book i am reading now it is written, that we need wrappers, because it is late to do anything with response after finishing chain.doFilter() method as response is sent already.
I wrote the following Servlet and Filter:
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
PrintWriter writer = response.getWriter();
writer.println("In Servlet");
}
}
public class MyFilter implements Filter{
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException{
PrintWriter writer = response.getWriter();
chain.doFilter(request, response);
writer.println("After chain");
}
}
And i see both strings in the browser.
My question is: Why do we need wrappers? I still can write to response even after chain.doFilter and i still see result?
Is it because response is sent in two pieces(first in the end of chain.doFilter and second in the end of Filter.doFilter)? So if i had to compress response it would work incorrectly(because first uncompressed part would be sent)?
The book is talking about response headers.
You misunderstood it as response body.
Here are some real world use cases of response wrappers so you can see why we may need them:
How to add response headers based on Content-type; getting Content-type before the response is committed
How do delete a HTTP response header?
How to read and copy the HTTP servlet response output stream content for logging
How to insert JSF page rendering time and response size into the page itself, at least partially?
How to configure Tomcat to not encode the session id into the URL when HttpServletResponse.encodeURL() is invoked
For more examples, see this search.

doPost super causing - HTTP Status 405

Till now I believed it was a common practice to call a super.doPost(req, resp) from your servlet's doPost(req, resp){}
But here's the issue I faced -
I have a very simple servlet having a doPost(req, resp) and since it was auto generated method from eclipse it was having super.doPost(req, resp) which is fine as it is calling its parent's doPost() but I was getting
HTTP Status 405 - HTTP method GET is not supported by this URL
whenever the servlet was hit.
I went through a lot of post and this post
had been talking about the same issue and one of the solution suggested was remove the super.doGet().
I did the same with my Post method and to my surprise it worked!!!!
I cannot find a logical reason for this. Can someone please explain what was happening?
Why was
405
flashing due to call of super.doPost().
Thanks,
Saurabh.
The default implementation of HttpServlet.doPost returns a 405 error (method not allowed). You have to implement the doPost method if you want to support the POST method in your servlet.
This is the code of HttpServlet.doPost:
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_post_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}

How HttpServletRequest works

i'm trying to understand how HttpServletRequest works:
in a demo application I have this code in a .class file:
HttpServletRequest req = (HttpServletRequest)
FacesContext.getCurrentInstance().getExternalContext().getRequest();
String parameter = req.getHeader("PARAMETER");
is this a JSF implementation? Does it read a parameter from the session right?
How can I retrieve the same parameter without using JSF?
Yes, this snippet is part of a JSF application.
No it doesn't read a parameter from the session, since it calls getHeader() on a HttpServletRequest object. So it reads a request header (as the javadoc of HttpServletRequest.getHeader() explains).
To retrieve the same header in a simple servlet-based application, you would use the HttpServletRequest argument passed to every servlet method:
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
String header = request.getHeader("PARAMETER");
...
}
It looks like you're not familiar at all with servlets. Read an introductory tutorial to grasp the basics before dving into code.

Setting character encodiing using ServletRequest and ServletResponse

I have seen a web application which deals with file processing (reciving applications from
a third party application and storing them in database for further usage).
That particular web application is also having a servlet filter configured whose only basic purpose is to set the character encoding to UTF-8.
For example :
public class ResponseFilterExample implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain) throws IOException, ServletException {
filterchain.doFilter(request, response);
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
}
}
Now my question is, what is the difference between
request.setCharacterEncoding("UTF-8");
and
response.setCharacterEncoding("UTF-8");
?
Well, the difference is that one sets the encoding on the request, the other sets the encoding on the response.
The above doc links explain in more detail.
ServletRequest.setCharacterEncoding():
Overrides the name of the character encoding used in the body of this request. This method must be called prior to reading request parameters or reading input using getReader(). Otherwise, it has no effect.
ServletResponse.setCharacterEncoding():
Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.

How to get a Servlet Request attribute in Struts 2.2.1?

I'm reading some tutorial where before invocating any action there is a filter that sets an attribute in the ServletRequest as Connection.
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
Connection connection = new ConnectionFactory().getConnection();
request.setAttribute("connection", connection);
chain.doFilter(request, response);
connection.close();
}
However I still didn't find a way to get the attribute in my Action. How can I get it?
Map parameters = ActionContext.getContext().getParameters();
Another option is that your action class implements ServletRequestAware. In the implementation of the method you simply assign the request to an instance field.

Resources