Enable caching in Tomcat 6? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 8 years ago.
Improve this question
I need to increase the page load speed. In google page speed I have this issue:
The following cacheable resources have a short freshness lifetime. Specify an expiration at least one week in the future for the following resources.
So I should add expiration date to header to force browser to cache static content in the page. Is there any solution for this?
I use tomcat 6.0.26.

One Solution using spring framework
You need to write a filter something similar to this one:
#WebFilter(dispatcherTypes = { YourDispatcherTypes }, urlPatterns = { "*.jsp","/yourresourcename/*", "oranyother"})
public class CacheHandlingFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain)
throws ServletException, IOException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpResp = (HttpServletResponse) response;
if(httpReq.getRequestURI().contains("/yourresourcename/")) {
httpResp.setDateHeader("Expires", ProvideTimeForCacheHere);
httpResp.setHeader("Cache-Control", "public, max-age=" + ProvideTimeForCacheHere);
}
filterChain.doFilter(request, response);
}
}

If you want something to apply cache headers globally across your servlets you could use a Filter.
Tomcat 7 has an ExpiresFilter built in; for Tomcat 6 you could write your own, or use a third-party library, to perform the same task.

Related

How to set a variable for Controller from HttpInterceptor? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
I am building a Spring Boot application.
I like to set a variable for the Spring Boot application. This variable should be set in an HTTP interceptor. The reason I do this, this variable will store some ID, and this ID will be used in methods in every controller.
How can I achieve this?
You SET the variable in an HTTP interceptor?
So it's not a unique global variable, it's an ID that is different for every request? That's what request attributes are for:
#Component
public class MyInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
if(request.getMethod().matches(RequestMethod.OPTIONS.name())) {
return true;
}
request.setAttribute("MY_ID", generateId(...));
return true;
}
}
#Controller
public class SampleController {
#RequestMapping(...)
public String something(HttpServletRequest req, HttpServletResponse res){
System.out.println( req.getAttribute("MY_ID"));
}
}
Pass it as JVM args and use it using System.getProperty.
Use -Dspring-boot.run.arguments=--interceptor.enabled=true and keep a backup config in application.properties or using -Drun.arguments and access the property key directly in your interceptor

more servlets vs more objects [duplicate]

This question already has answers here:
Design Patterns web based applications [closed]
(5 answers)
Closed 6 years ago.
I want to understand, If request has to be processed through multiple functions-
is it good to forward through multiple Servlets OR
implement as object methods
Example
req.getRequestDispatcher("LoadSession").forward(req, resp);
req.getRequestDispatcher("AuthoriseRoles").forward(req, resp);
req.getRequestDispatcher("Boot").forward(req, resp);
OR
sessionLoader.loadSession(req,res);
authoriseService.authoriseRoles(req,res);
bootService.boot(req, res);
I assume you are at the phase of designing an API. According to REST design principles, the url should reflect the resource that is handled or requested and the HTTP method should reflect what action is required to be taken on the resource.
So, instead of /LoadSession and having the session id as query param in the Http request, it should be GET /session/{id} for example GET /session/e841092fa2194340bc40 (I am assuming LoadSession is a request to return an existing session)
You might ask yourself what is the advantage of following this design. It is that there are several libraries and frameworks that are able to parse incoming HTTP requests and take care of the routing for you (for example, Jersey is the reference JAX-RS implementation, JAX-RS being JavaEE's REST standard) . So instead of writing a servlet as you mentioned, you write the class that represents the resource and methods that are fired according to the HTTP method. you tie it all together with annotations:
#Path("/session")
import javax.ws.rs.*;
import javax.ws.rs.core.*;
#Produces({MediaType.APPLICATION_JSON})
public class SessionHandler
{
#Context
private HttpServletRequest httpRequest;
#Context
private HttpServletResponse httpResponse;
#GET
#Path("{id}")
public Session load(#PathParam("id") String id) {
...

REST make sure transport is HTTPS? [duplicate]

This question already has answers here:
How can I know if the request to the servlet was executed using HTTP or HTTPS?
(3 answers)
Closed 6 years ago.
I have a Restful Web Service written in Java:
Example:
#GET
#PATH("/foo")
public Response getFoo(){
...
}
and a filter
public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) {
....
}
How can i make sure that incoming requests and sent responses from my REST API are transported by HTTPS?
If you have access to ServletRequest, you can use ServletRequest.isSecure to determine whether it was HTTPS or not.
Be careful, if your application gets deployed behind some frontend servers that extract HTTPS for you, you have to do something different. Usually check some headers or similar.

Spring Framework Abstraction [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have a legacy application that uses a singleton pattern for all the services and accesses all the services via ServiceName.getInstance() inside services that use other services and in the web tier. I'm converting the project to use Spring and was thinking of creating a singleton utility class ServiceProvider with methods getServiceA, getServiceB..etc and have it get the bean from a Spring application context. I will use the ServiceProvider in the web tier only since I can't convert to it to use Spring just yet and autowire all the services that use other services. Is this a good solution?
I have a very simple web tier and maybe someone can recommend how to springify it with minimal changes. I have a map of url to controllers loaded on start up. The RequestDispatcher parses the request url, looks up the controller by class and executes a template method (there are various subclasses of the base controller but it doesn't complicate the problem).
RequestDispatcher:
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
int slashIndex = req.getRequestURL().lastIndexOf("/");
String path = req.getRequestURL().substring(slashIndex, req.getRequestURL().length());
ServiceURL url = urlMap.get(path);
ServiceProvider.getLog().info("Requested page: " + path);
if (url != null) {
try {
Utils.authenticate(req, resp);
grantAccess(req, url);
BaseServlet servlet = (BaseServlet)url.getClass().getClassLoader().loadClass(url.getClassName()).newInstance();
servlet.service(req, resp);
}
catch (AuthorizationException e) {
resp.getWriter().write(new ErrorModel("You are not authorized to perform the requested action.").getContent());
ServiceProvider.getAuthLog().info("auth", e);
}catch (SystemException e) {
I'm thinking of annotating my servlets as components, having the packages auto scanned. Can the ApplicationContext get the bean by full class name?
Looks like your services are stateless.
I would annotate them with #Service(make them spring beans) and just #Autowire them anywhere you need. Let Spring act as a service provider.
Your getInstance() solution sounds like the objects are not unnder Spring's control.
If you need to access the services as JNDI lookups you should configure them as such in Spring.
If it's under Spring's control it should not be instantiated in your code. If it's instantiated in your code, it's not under Spring's control.

HTTP 303 redirect in Spring MVC *without tacking on JSESSIONID* and without touching any spring config [duplicate]

This question already has answers here:
Closed 11 years ago.
When using spring's RedirectView, it calls encodeRedirectURL which sneaks the JSESSIONID into the URL. I'd like to redirect without that happening.
Right now, I have:
#RequestMapping(value = "/MyProfile")
public ModelAndView gotoMyProfile(HttpSession session) {
return new ModelAndView(new RedirectView("/profile?id="+userid));
}
This works fine to redirect users to "/profile?id=4256", but it sticks ";JSESSIONID=F3D5AE8AED0F" in there, so I end up with "/profile;JSESSIONID=F3D5AE8AED0F?id=4256".
I'd like to have the code below, but I don't think HttpServletResponse is a valid return type for a RequestMapping:
#RequestMapping(value = "/MyProfile")
public HttpServletResponse gotoMyProfile(HttpSession session, HttpServletResponse response) {
response.setStatus(303);
response.setHeader("Location", "/profile?id=" + userid);
return response;
}
EDIT: Thanks for your answer, but I don't have access to the Spring security configuration. That's why I was trying the code above. I'm asking for a solution that can be done strictly in java.
You could set disable-url-rewriting="true" in the <http>.
But clients must use cookies if this attribute is set to true.

Categories