caching images served by servlet

The default servlet serving static content in containers like Tomcat doesn’t set any cache control headers. You don’t need write a servlet just for that. Just create a filter like this, public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { long expiry = new Date().getTime() + cacheAge*1000; HttpServletResponse httpResponse = (HttpServletResponse)response; httpResponse.setDateHeader(“Expires”, … Read more

How to forward request from servlet to action of struts2?

In order to do this you may also need to set the filter to run on FORWARD (and INCLUDE as your code shows, although you state you want a FORWARD): <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> <!– If you want includes as well –> </filter-mapping>

Spring – Modifying headers for every request after processing (in postHandle)

It sounds like you’re on the right track with a servlet filter, what you probably need to do is wrap the servlet response object with one that detects when a 401 status code has been set and adds your custom header at that time: HttpServletResponse wrappedResponse = new HttpServletResponseWrapper(response) { public void setStatus(int code) { … Read more

Create and download CSV file in a Java servlet

I got the solution and I am posting it below. public void doGet(HttpServletRequest request, HttpServletResponse response) { response.setContentType(“text/csv”); response.setHeader(“Content-Disposition”, “attachment; filename=\”userDirectory.csv\””); try { OutputStream outputStream = response.getOutputStream(); String outputResult = “xxxx, yyyy, zzzz, aaaa, bbbb, ccccc, dddd, eeee, ffff, gggg\n”; outputStream.write(outputResult.getBytes()); outputStream.flush(); outputStream.close(); } catch(Exception e) { System.out.println(e.toString()); } } Here we don’t need to … Read more

Differences between ServletResponse and HttpServletResponseWrapper?

BalusC’s answer is good, but it might be a little overwhelming if you’re just starting out. Put simply: SerlvetResponse and its extension, HttpServletResponse, are interfaces telling you what methods are available to call to do the things you need. In the normal course of working with Filters, Servlets, et al., you’ll use HttpServletResponse often to … Read more

How to get and set a global object in Java servlet context

Yes, I would store the list in the ServletContext as an application-scoped attribute. Pulling the data from a database instead is probably less efficient, since you’re only updating the list every hour. Creating a ServletContextListener might be necessary in order to give the Quartz task a reference to the ServletContext object. The ServletContext can only … Read more