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
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
Improve this question
I have a problem I want to inject a service in the successfulAuthentication function of Spring Secuirty.
I had an error at #Autowired: the annotation #Autowired is disallowed for this location.
JwtAuthentificationFilter.java:
I tried to put it outside the function protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult), but when I execute and do the /login I get an error:
java.lang.NullPointerException: Cannot invoke
"org.sid.secservice.sec.service.EmailService.sendVerificationCode(String,
String)" because "this.emailService" is null
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 7 years ago.
Improve this question
I call method1 of servlet1 from service() of servlet2. I want to throw sendError(5xx) from servlet1. But it needs the response object of servlet2 which I am not passing. Any other method to throw the HTTP status codes?
public class servlet2 extends servlet1{
public void service(HttpServletRequest request, HttpServletResponse response){
}
}
public abstract class servlet1 extends HTTPServlet{
public void init(ServletConfig config) throws ServletException {
}
public boolean method1()
{
return true;
}
}
If you invoke a custom method1 of servlet1, from servlet2, then the servlet1 don't act as a real Servlet, but as a normal object. In that case, the servlet1 don't have any HttpServletResponse to wich send an error.
The normal way to dispatch the control from one servlet to another, is using a RequestDispatcher. For example, execute this sentence from servlet2:
getServletContext().getNamedDispatcher("servlet1").forward(request, response);
In servlet1, you receive the request in the service method, with receive as a parameter an HttpServletResponse, which you can use to send the error.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
The title pretty much says it all, I have written a REST webservice in Java using JAX-RS and Jersey, and I would like to extract the I.P. address of the client that hits it in my code. If I have a class like this:
#Path("/service")
public class Service {
#GET
public void doAction () {
// ...
}
}
What do I do from there?
P.s. I'm not asking for debugging help, I'm asking how I can retrieve the IP address of the client that connects to my web service. #ANyarThar provided a good answer.
How #Context HttpServletRequest as argument in your method,
#GET
public void doAction (#Context HttpServletRequest req) {
//then get ip address
String ipAddress = req.getRemoteHost();
}
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.
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.