Servlet mapping not working correctly - java

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.

Related

Java Servlet. Catch full OData URL [duplicate]

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.

How to build automatically in IntelliJ-IDEA?

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

Spring boot oauth callback for google

I am sharing the complete code regards to my problem.
I am taking the social configuration file handled via social-cfg.xml it is in classpath.
social-cfg.xml
google.client.id=#####################################################################
google.client.secret=############################
google.scope=https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile
I have made java handler to handle this config file
socialConfig.java
package com.inno.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.UserIdSource;
import org.springframework.social.config.annotation.ConnectionFactoryConfigurer;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurer;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.ConnectionSignUp;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository;
import org.springframework.social.connect.web.ConnectController;
import org.springframework.social.google.connect.GoogleConnectionFactory;
import org.springframework.social.security.AuthenticationNameUserIdSource;
import com.inno.dao.AppUserDAO;
import com.inno.service.ConnectionSignUpImpl;
#Configuration
#EnableSocial
// Load to Environment.
#PropertySource("classpath:social-cfg.properties")
public class SocialConfig implements SocialConfigurer {
private boolean autoSignUp = false;
#Autowired
private DataSource dataSource;
#Autowired
private AppUserDAO appUserDAO;
#Override
public void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) {
try {
this.autoSignUp = Boolean.parseBoolean(env.getProperty("social.auto-signup"));
} catch (Exception e) {
this.autoSignUp = false;
}
// Google
GoogleConnectionFactory gfactory = new GoogleConnectionFactory(//
env.getProperty("google.client.id"), //
env.getProperty("google.client.secret"));
gfactory.setScope(env.getProperty("google.scope"));
cfConfig.addConnectionFactory(gfactory);
}
//............. more code regards to another functionality.
when i am hitting this href
<a th:href="#{/auth/google}">Google</a>
<br />
Then it's redirecting to google page with error as below
Error: redirect_uri_mismatch
The redirect URI in the request, http://localhost:8787/auth/google, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: https://console.developers.google.com/apis/credentials/oauthclient/#######?project=#######
when i visit https://console.developers.google.com/apis/credentials/oauthclient/#######?project=#######
there are two option's
Authorized JavaScript origins
Authorized redirect URIs
I have set both of them to validate with my webapp. I just don't where is the point which stuck out this issue. PLease help me out. Also ask for any other requirement if required.
redirect URI in the google developer console must exactly match where you are sending your request from. In your case the error message tells you exactly where you are sending your request form.
http://localhost:8787/auth/google
Which means that you need to have that exactly in the Google developer console under Authorized redirect URIs or the authentication sever will not accept your request.
Note Port must be included. Exactly means exactly with the exception of cased.

Servlet error HTTP Status 404 – Not Found Java Tomcat

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.

How to configure CORS with a Spring Java Mongo REST application?

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.

Categories

Resources