This question already has answers here:
Servlet and path parameters like /xyz/{value}/test, how to map in web.xml?
(7 answers)
Closed 2 years ago.
I am trying to catch OData call in Java with WebServlet.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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("/someservice/UserSet")
public class UserSetServlet extends HttpServlet {
#Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
//some functionality
}
}
When I call simply "http://somdomain.com/someservice/UserSet", then I get to service, but when I call "http://somdomain.com/someservice/UserSet("SOME_ID")", then I receive 404, that service is not found
Does someone know how I can configure Servlet for catching entire OData Request?
Thanks a lot!
Thanks to all answers. Solution - nohow. I starting migration to Spring Framework.
Related
In my Spring boot project, I have made some some RESTful APIs. Now, for each request in my APIs, I want to set a specific header like below below-
If the Http request is called with that specific header name and header value, only then it will show response code ok(200) otherwise it will show some other response code.
I need one single configuration to fix that specific header for each request in my project. So, I need some suggestion about the procedure to follow to solve this issue.
I think in these kind of scenarios if you want to handle them in single point filters are good choices
I hope below code can give you the idea how to use filter to solve your problem:
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HeaderCheckerFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String header = request.getHeader("MyHeader");
if (header != null && header.equals("HeaderValue")) {
filterChain.doFilter(request, response);
} else {
response.getWriter().println("invalid request");
}
}
}
I am learning how to build a Java project in IntelliJ. But I can't make it build automatically, while running the Jetty:run command.
I already set the IDE to autobuild when saving and to build when idle for 10 secs, and set the compiler.automake.allow.when.app.running to 1. All of these methods worked doing in my mac, but in windows it doesn't work.
I have a servlet like so:
package br.com.alura.maven.lojaweb;
import java.io.IOException;
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={"/contato"})
public class ContatoServlet extends HttpServlet{
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.println("<html><h2>My message here!</h2></html>");
writer.close();
}
}
When I change the message and save, I hope to find it changed in the browser
I know that there were similar problems already, but non of the solutions worked for me. I checked the directories and I edited my `web.xml file a couple of times but it still does not work.
I am writing a simple servlet in Java running on Tomcat and I am getting the error:
HTTP Status 404 – Not Found
Type Status Report
Message /WorkshopForm/MainWorkshopForm
Description The origin server did not find a current representation
for the target resource or is not willing to disclose that one exists.
My servlet class is:
package workshop;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.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;
#WebServlet(description = "This registration form", urlPatterns = {
"/WorkshopForm" })
public class WorkshopForm {
public class MyServlet extends HttpServlet implements Servlet {
private static final long serialVersionUID = 13425L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String participantName = request.getParameter("participantName");
String participantSurname = request.getParameter("participantSurname");
String participantEmail = request.getParameter("participantEmail");
PrintWriter writer = response.getWriter();
writer.println("Welcome" + participantName + " " + participantSurname + " " + participantEmail);
}
}
}
My web.xml:
Tree in Eclipse:
Is it a problem with the web.xml file? I am thinking that maybe I have some mismatch with names or paths but I tried to solved it already and no idea why it is not working.
The URL pattern /WorkshopForm matches only the exact URL path /WorkshopForm. If you want the servlet to also handle longer paths like /WorkshopForm/MainWorkshopForm, you need to change the URL pattern to /WorkshopForm/*. Then you can call request.getPathInfo() in your servlet code to obtain the variable part of the path.
Another alternative is to use some JAX-RS framework to handle the mapping from URL paths to Java methods that handle individual paths.
After trying many different url paths I still am not able to map my jsp get request to my servlet. The request keeps returning a 404 resource not found. The jsp and servlet are located in the same /NOSESSION folder. Here is the call from the jsp
<form action="/webapps/xxxx-xxx-BBLEARN/NOSESSION/createLinkReturn_proc" method="get" name="the_form" onsubmit="validateForm();">
And my servlet looks like this
package com.xxxx;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.io.*;
import java.net.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
#WebServlet("/NOSESSION/createLinkReturn_proc")
public class createLinkReturn_proc extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
LoggingManager.appendToLogFile("Made it into the servlet");
}
I am using Servlet 3.0 with an updated web.xml config. I shouldn't have to put the servlet mappings in the web.xml file, but I have tried that and it still didn't work that way. I have tried lots of combinations of mappings from simple "/createLinkReturn_proc" to "${pageContext.request.servletPath}/createLinkReturn_proc" and nothing has worked so far.
I am trying to combine these two sample Java Spring apps together in order to be able to run my Mongo database on one server and serve JSON to a front end app on another server.
CORS tutorial:
http://spring.io/guides/gs/rest-service-cors/
MongoDB with REST
http://spring.io/guides/gs/accessing-mongodb-data-rest/
My current "MongoDB with REST" Spring.io sample application runs, but it currently still isn't supporting CORS even after adding the SimpleCORSFilter class as shown in the CORS sample (above).
I am thinking that I may simply need to configure this new SimpleCORSFilter class somewhere - in the annotation equivalent of the web.xml - so I am trying to use #WebFilter("/*") in the SimpleCORSFilter class.
According to the "MongoDB with REST" tutorial page, the "#Import(RepositoryRestMvcConfiguration.class) annotation imports a collection of Spring MVC controllers, JSON converters, and other beans needed to provide a RESTful front end. These components link up to the Spring Data MongoDB backend." This might indicate that I should also want to override something in RepositoryRestMvcConfiguration to configure the SimpleCORSFilter filter.
I tried adding #WebFilter("/") on the SimpleCORSFilter class itself, but I don't see Access-Control- headers in the response using curl --verbose. As a result, I don't think the filter is properly configured.
Has anyone had any luck with combining these two tutorial projects (or something similar?)?
For reference, the SimpleCORSFilter class I am trying to configure is here:
package foo.bar;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
#WebFilter("/*")
#Component
public class SimpleCORSFilter extends OncePerRequestFilter implements Filter {
/* Attempt #1 - based on original demo code from spring.io - could not get to work
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
*/
// Attempt #2 - based on https://stackoverflow.com/questions/20583814/angular-and-cors which advised use of addHeader() instead of setHeader() - still no luck
#Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS");
response.addHeader("Access-Control-Allow-Headers",
"origin, content-type, accept, x-requested-with, sid, mycustom, smuser");
filterChain.doFilter(request, response);
}
// unable to override this final method
//public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
...and the main Application class which currently seems to be performing the configuration is here:
package foo.bar;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
#Configuration
#EnableMongoRepositories
#Import(RepositoryRestMvcConfiguration.class)
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Note: I did find a somewhat similar post here: CORS with Spring not working, but that solution involves the use of JSONP, which I also read was sort of a hack, and in any case, that issue does not seem to be resolved either.
I was running into what I believe is a similar issue. Turning basic authentication off seems to have resolved it.