I'm building a web-app and have chosen Spring for my backend and React for my frontend. I'm using Spring Security to provide authentication and authorisation:
#Configuration
#EnableWebSecurity
public class SecurityConfiguration {
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeHttpRequests((authz) -> authz
.antMatchers("/").permitAll()
.antMatchers("/register/**").permitAll()
.antMatchers("/aUrl/**").hasRole(aRole)
.antMatchers("/anotherUrl/**").hasRole(anotherRole)
.anyRequest().authenticated()
)
.formLogin((formLogin) ->
formLogin.permitAll().defaultSuccessUrl("/login/success")
)
.logout((logout) ->
logout.deleteCookies("remove")
.invalidateHttpSession(false)
.logoutSuccessUrl("/login")
);
return http.build();
}
#Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
and I was trying to submit the POST request through the following component:
class LoginForm extends React.Component{
constructor() {
super();
this.state = {
username: "",
password: ""
}
}
handleSubmit = (e) => {
const formData = new FormData();
formData.append("username", this.state.username);
formData.append("password", this.state.password);
fetch('/login', {
method: 'POST',
body: formData
})
e.preventDefault();
}
handleFieldChange = (event) => {
this.setState({[event.target.id]: event.target.value});
}
render(){
return (
<form onSubmit = {this.handleSubmit}>
<Input type="text" placeholder="username" id="username" label="Username:" value={this.state.username} onChange={this.handleFieldChange}/>
<Input type="text" placeholder="password" id="password" label="Password:" value={this.state.password} onChange={this.handleFieldChange}/>
<SubmitButton text="Log in"/>
</form>
);
}
}
I am basically trying to mimic the POST request sent by the browser in the following scenario:
<form method="post" action="/login">
<label htmlFor="username" >Username</label>
<input type="text" id="username" name="username" placeholder="Username" required="" autoFocus="" />
<label htmlFor="password">Password</label>
<input type="password" id="password" name="password" placeholder="Password" required="" />
<button type="submit">Log in</button>
</form>
The problem is that the latter works, the former does not. Specifically, I get a CORS policy error message that does not show up in the latter case, despite both pages being on the same port (3000), which is separate from the one that hosts the backend (8080) (N.B: I have declared a proxy as per React's indications). I am guessing that the request is somehow built differently, but I cannot imagine there wouldn't be a way to integrate a programmatic POST with Spring Security: am I simply not supposed to use form-based authentication?
Thank you in advance!
EDIT:
Here is my Spring log:
2022-10-21 10:03:57.303 INFO 15260 --- [ main] edu.devs.SomeApplication : Starting SomeApplication using Java 17.0.2 on *** with PID 15260
2022-10-21 10:03:57.306 INFO 15260 --- [ main] edu.devs.SomeApplication : No active profile set, falling back to 1 default profile: "default"
2022-10-21 10:03:58.117 INFO 15260 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Neo4j repositories in DEFAULT mode.
2022-10-21 10:03:58.218 INFO 15260 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 85 ms. Found 4 Neo4j repository interfaces.
2022-10-21 10:03:59.397 INFO 15260 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-10-21 10:03:59.409 INFO 15260 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-10-21 10:03:59.410 INFO 15260 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.65]
2022-10-21 10:03:59.537 INFO 15260 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-10-21 10:03:59.538 INFO 15260 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2106 ms
2022-10-21 10:04:00.106 INFO 15260 --- [ main] org.neo4j.driver.internal.DriverFactory : Routing driver instance 1107789101 created for server address ***:7687
2022-10-21 10:04:00.803 INFO 15260 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [org.springframework.security.web.session.DisableEncodeUrlFilter#c9b5a99, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#70be89ec, org.springframework.security.web.context.SecurityContextPersistenceFilter#3e43f049, org.springframework.security.web.header.HeaderWriterFilter#2017f6e6, org.springframework.security.web.authentication.logout.LogoutFilter#d25e878, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#5384ce66, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#336f49a1, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter#2aee0704, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#755a7218, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#58a7dc4, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#19a5b637, org.springframework.security.web.session.SessionManagementFilter#79ca7bea, org.springframework.security.web.access.ExceptionTranslationFilter#5627cb29, org.springframework.security.web.access.intercept.AuthorizationFilter#125f16b2]
2022-10-21 10:04:01.409 INFO 15260 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-10-21 10:04:01.433 INFO 15260 --- [ main] edu.devs.SomeApplication : Started SomeApplication in 4.607 seconds (JVM running for 5.145)
2022-10-21 10:04:03.901 WARN 15260 --- [ main] o.s.d.n.c.m.DefaultNeo4jIsNewStrategy : Instances of class edu.devs.domain.Student with an assigned id will always be treated as new without version property!
2022-10-21 10:04:04.059 WARN 15260 --- [ main] o.s.d.n.c.m.DefaultNeo4jIsNewStrategy : Instances of class edu.devs.security.UserAuthority with an assigned id will always be treated as new without version property!
2022-10-21 10:04:04.441 WARN 15260 --- [ main] o.s.d.n.c.m.DefaultNeo4jIsNewStrategy : Instances of class edu.devs.domain.Admin with an assigned id will always be treated as new without version property!
2022-10-21 10:04:05.052 WARN 15260 --- [ main] o.s.d.n.c.m.DefaultNeo4jIsNewStrategy : Instances of class edu.devs.domain.School with an assigned id will always be treated as new without version property!
2022-10-21 10:04:05.264 WARN 15260 --- [ main] o.s.d.n.c.m.DefaultNeo4jIsNewStrategy : Instances of class edu.devs.domain.Classroom with an assigned id will always be treated as new without version property!
2022-10-21 10:04:29.586 INFO 15260 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-10-21 10:04:29.587 INFO 15260 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-10-21 10:04:29.588 INFO 15260 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
and here is my browser console log:
Access to fetch at 'http://localhost:8080/login/success' (redirected from 'http://localhost:3000/login') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
LoginForm.js:26 GET http://localhost:8080/login/success net::ERR_FAILED 302
all of which does not show up if I just use a declarative POST.
For good measure, I'm also including the request headers of both.
Here are those of the programmatically-sent request:
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7
Connection: keep-alive
Content-Length: 256
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryZva4mpEReAgtMlLA
Host: localhost:3000
Origin: http://localhost:3000
Referer: http://localhost:3000/login
sec-ch-ua: "Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36
and here are those of the one handled by the browser (the one that works no problem):
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br
Accept-Language: it-IT,it;q=0.9
Cache-Control: max-age=0
Connection: keep-alive
Content-Length: 43
Content-Type: application/x-www-form-urlencoded
Host: localhost:3000
Origin: http://localhost:3000
Referer: http://localhost:3000/login
sec-ch-ua: "Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: same-origin
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36
Obviously I can see that the issue with the former request is that the server redirects the browser to a resource located on a different port, thus triggering a CORS policy error. What I do not get is why this does not happen with the latter request, although I'm guessing it's got something to do with the request headers(?).
It's a spring project imported into Eclipse.
I created the WebConfig file, added the parameterized and parameterless constructors to the entity and PK classes. I changed the annotations, I don't know what else I need to do anymore. I have consulted the pages with the same error, my file lista_parlamentari_circoscrizione.jsp is present, it is not absent. Can anyone please help me? Thank you
Update: I changed the controller index url to "/ Parliament" in both the class and the Beans file, to prevent the controller from taking precedence over the resource manager.
Should I also map the classes in the hibernate.cfg.xml file?
p.s.: if a jsp page is the result of sending another jsp page, what path do you put in the web.xml file? in my case it is the Beans.xml file. i tried to debug, but it doesn't work for me, it tells me it can't find library files.
Parlamentare.java
#EmbeddedId
private PK pk;
PK.java
#Type( type = "string-array" )
#Column(
name = "circoscrizione",
columnDefinition = "text[]"
)
// private String[] circoscrizione;
private List<String> circoscrizione;
ParlamentareController.java
#GetMapping("cerca_parlamentare_dalla_circoscrizione")
public String getParlamentare4(#RequestParam("circoscrizione")
String circoscrizionee)
{
ModelAndView mv = new ModelAndView();
List<Parlamentare> parlamentari =
parlamRepo.findByCircoscrizione(circoscrizionee);
System.out.println(parlamRepo.
findByCircoscrizione(circoscrizionee));
mv.addObject(parlamentari);
mv.setViewName("lista_parlamentari_circoscrizione.jsp");
return "lista_parlamentari_circoscrizione";
//mv;
}
ParlamentareRepository.java
#Query("FROM Parlamentare P where P.pk.circoscrizione=
:circoscrizionee")
public List<Parlamentare>
findByCircoscrizione(#Param(value="circoscrizione") String
circoscrizionee);
cerca_parlamentare_dalla_circoscrizione.jsp
<body>
<!-- lista_parlamentari_circoscrizione -->
<h2>Ricerca parlamentare in base alla circoscrizione:</h2>
<form method="GET" action="/lista_parlamentari_circoscrizione"
modelAttribute="parlamentare">
<table>
<tr>
<td>Circoscrizione:</td>
<td> <input type="text" name="circoscrizione"><br></td>
</tr>
<tr>
<td> <td><input type="submit" value="invio"><br></td>
</tr>
</table>
</form>
lista_parlamentari_circoscrizione
<title>Lista parlamentari di quella circoscrizione</title>
</head>
<body>
<c:forEach items="${parlamentari}" var="parlamentare">
<td>Nome:</td>
<td><c:out value="${parlamentare.getPk().getNome()}"/></td>
<br>
</tr>
<tr>
<td>Partito:</td>
<td><c:out value="${pk.partito}"/></td><br>
</tr>
<tr>
<td>Circoscrizione:</td>
<c:forEach items="${pk.getCircoscrizione()}" var="CIRCOSCRIZIONE">
<td><c:out value="${CIRCOSCRIZIONE}"/></td> <br>
</c:forEach>
</tr>
<br>
<tr>
<td>Data di nascita:</td>
<td><c:out value="${parlamentare.data_nascita}"/><br></td>
</tr>
<tr>
<td>Luogo:</td>
<td><c:out value="${parlamentare.luogo}"/><br></td>
</tr>
<tr>
<td>Titolo di studi:</td>
<td><c:out value="${parlamentare.titolo_studi}"/><br></td>
</tr>
<tr>
<td>Mandati:</td><br>
<c:forEach items="${parlamentare.mandati}" var="mandato">
<table>
<tr>
<td>Mandato:</td>
<td><c:out value="${mandato}"/></td><br>
</tr>
</table>
</c:forEach>
</tr>
<tr>
<td>Commissioni:</td>
<c:forEach items="${parlamentare.commissioni}" var="commissione">
<table>
<tr>
<td>Commissione:</td>
<td><c:out value="${commissione}"/></td><br>
</tr>
</table>
</c:forEach>
</c:forEach>
<!-- ${parlamentari} -->
</body>
</html>
ParlamentareRepository.java
#Query("SELECT P.pk.nome FROM Parlamentare P where
P.pk.circoscrizione= :circoscrizionee")
public List<Parlamentare>
findByCircoscrizione(#Param(value="circoscrizione") List<String>
circoscrizionee);
STACKTRACE:
2022-10-17 15:21:30.136 INFO 6912 --- [ restartedMain]
o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using
JtaPlatform implementation:
[org.hibernate.engine.transaction.jta.platform.internal.
NoJtaPlatform]
2022-10-17 15:21:30.153 INFO 6912 --- [ restartedMain]
j.LocalContainerEntityManagerFactoryBean : Initialized JPA
EntityManagerFactory for persistence unit 'default'
2022-10-17 15:21:32.016 DEBUG 6912 --- [ restartedMain]
s.w.s.m.m.a.RequestMappingHandlerAdapter : ControllerAdvice
beans: 0 #ModelAttribute, 0 #InitBinder, 1 RequestBodyAdvice, 1
ResponseBodyAdvice
2022-10-17 15:21:32.248 DEBUG 6912 --- [ restartedMain]
s.w.s.m.m.a.RequestMappingHandlerMapping : 11 mappings in
'requestMappingHandlerMapping'
2022-10-17 15:21:32.305 DEBUG 6912 --- [ restartedMain]
o.s.w.s.handler.SimpleUrlHandlerMapping : Patterns
[/webjars/**, /webapp/] in 'resourceHandlerMapping'
2022-10-17 15:21:32.360 DEBUG 6912 --- [ restartedMain]
.m.m.a.ExceptionHandlerExceptionResolver : ControllerAdvice
beans: 0 #ExceptionHandler, 1 ResponseBodyAdvice
2022-10-17 15:21:33.740 INFO 6912 --- [ restartedMain]
o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is
running on port 35729
2022-10-17 15:21:33.839 INFO 6912 --- [ restartedMain]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on
port(s): 8080 (http) with context path ''
2022-10-17 15:21:33.878 INFO 6912 --- [ restartedMain]
com.giuggiola.ParlamentoApplication : Started
ParlamentoApplication in 13.563 seconds (JVM running for
14.809)
2022-10-17 15:21:55.256 INFO 6912 --- [nio-8080-exec-2]
o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring
DispatcherServlet 'dispatcherServlet'
2022-10-17 15:21:55.256 INFO 6912 --- [nio-8080-exec-2]
o.s.web.servlet.DispatcherServlet : Initializing Servlet
'dispatcherServlet'
2022-10-17 15:21:55.256 DEBUG 6912 --- [nio-8080-exec-2]
o.s.web.servlet.DispatcherServlet : Detected
StandardServletMultipartResolver
2022-10-17 15:21:55.256 DEBUG 6912 --- [nio-8080-exec-2]
o.s.web.servlet.DispatcherServlet : Detected
AcceptHeaderLocaleResolver
2022-10-17 15:21:55.256 DEBUG 6912 --- [nio-8080-exec-2]
o.s.web.servlet.DispatcherServlet : Detected
FixedThemeResolver
2022-10-17 15:21:55.257 DEBUG 6912 --- [nio-8080-exec-2]
o.s.web.servlet.DispatcherServlet : Detected
org.springframework.web.servlet.view.
DefaultRequestToViewNameTranslator#6bdadfb5
2022-10-17 15:21:55.258 DEBUG 6912 --- [nio-8080-exec-2]
o.s.web.servlet.DispatcherServlet : Detected
org.springframework.web.servlet.support.
SessionFlashMapManager#589ac705
2022-10-17 15:21:55.258 DEBUG 6912 --- [nio-8080-exec-2]
o.s.web.servlet.DispatcherServlet :
enableLoggingRequestDetails='false': request parameters and
headers will be masked to prevent unsafe logging of potentially
sensitive data
2022-10-17 15:21:55.258 INFO 6912 --- [nio-8080-exec-2]
o.s.web.servlet.DispatcherServlet : Completed
initialization in 2 ms
2022-10-17 15:21:55.317 DEBUG 6912 --- [nio-8080-exec-2]
o.s.web.servlet.DispatcherServlet : GET "/", parameters=
{}
2022-10-17 15:21:55.339 WARN 6912 --- [nio-8080-exec-2]
o.s.web.servlet.PageNotFound : No mapping for GET /
2022-10-17 15:21:55.340 DEBUG 6912 --- [nio-8080-exec-2]
o.s.web.servlet.DispatcherServlet : Completed 404
NOT_FOUND
2022-10-17 15:21:55.352 DEBUG 6912 --- [nio-8080-exec-2]
o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for
GET "/error", parameters={}
2022-10-17 15:21:55.367 DEBUG 6912 --- [nio-8080-exec-2]
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to
com.giuggiola.controller.IndexController#error()
2022-10-17 15:21:55.413 DEBUG 6912 --- [nio-8080-exec-2]
m.m.a.RequestResponseBodyMethodProcessor : Using 'text/html',
given [text/html, application/xhtml+xml, image/avif,
image/webp, image/apng, application/xml;q=0.9,
application/signed-exchange;v=b3;q=0.9, */*;q=0.8] and
supported [text/plain, */*, text/plain, */*, application/json,
application/*+json, application/json, application/*+json,
application/x-jackson-smile, application/cbor]
2022-10-17 15:21:55.416 DEBUG 6912 --- [nio-8080-exec-2]
m.m.a.RequestResponseBodyMethodProcessor : Writing ["Error
handling"]
2022-10-17 15:21:55.429 DEBUG 6912 --- [nio-8080-exec-2]
o.s.web.servlet.DispatcherServlet : Exiting from "ERROR"
dispatch, status 404
2022-10-17 15:22:05.265 DEBUG 6912 --- [nio-8080-exec-8]
o.s.web.servlet.DispatcherServlet : GET "/Parlamento/",
parameters={}
2022-10-17 15:22:05.272 DEBUG 6912 --- [nio-8080-exec-8]
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to
com.giuggiola.controller.ParlamentareController#index()
2022-10-17 15:22:05.297 DEBUG 6912 --- [nio-8080-exec-8]
o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html'
given [text/html, application/xhtml+xml, image/avif,
image/webp, image/apng, application/xml;q=0.9,
application/signed-exchange;v=b3;q=0.9, */*;q=0.8]
2022-10-17 15:22:05.306 DEBUG 6912 --- [nio-8080-exec-8]
o.s.web.servlet.view.JstlView : View name
'index.jsp', model {}
2022-10-17 15:22:05.311 DEBUG 6912 --- [nio-8080-exec-8]
o.s.web.servlet.view.JstlView : Forwarding to
[index.jsp]
2022-10-17 15:22:05.313 DEBUG 6912 --- [nio-8080-exec-8]
o.s.web.servlet.DispatcherServlet : Completed 404
NOT_FOUND
2022-10-17 15:22:05.314 DEBUG 6912 --- [nio-8080-exec-8]
o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for
GET "/error", parameters={}
2022-10-17 15:22:05.314 DEBUG 6912 --- [nio-8080-exec-8]
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to
com.giuggiola.controller.IndexController#error()
2022-10-17 15:22:05.325 DEBUG 6912 --- [nio-8080-exec-8]
m.m.a.RequestResponseBodyMethodProcessor : Using 'text/html',
given [text/html, application/xhtml+xml, image/avif,
image/webp, image/apng, application/xml;q=0.9,
application/signed-exchange;v=b3;q=0.9, */*;q=0.8] and
supported [text/plain, */*, text/plain, */*, application/json,
application/*+json, application/json, application/*+json,
application/x-jackson-smile, application/cbor]
2022-10-17 15:22:05.325 DEBUG 6912 --- [nio-8080-exec-8]
m.m.a.RequestResponseBodyMethodProcessor : Writing ["Error
handling"]
2022-10-17 15:22:05.326 DEBUG 6912 --- [nio-8080-exec-8]
o.s.web.servlet.DispatcherServlet : Exiting from "ERROR"
dispatch, status 404
2022-10-17 15:22:08.594 DEBUG 6912 --- [nio-8080-exec-3]
o.s.web.servlet.DispatcherServlet : GET "/Parlamento",
parameters={}
2022-10-17 15:22:08.596 DEBUG 6912 --- [nio-8080-exec-3]
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to
com.giuggiola.controller.ParlamentareController#index()
2022-10-17 15:22:08.598 DEBUG 6912 --- [nio-8080-exec-3]
o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html'
given [text/html, application/xhtml+xml, image/avif,
image/webp, image/apng, application/xml;q=0.9,
application/signed-exchange;v=b3;q=0.9, */*;q=0.8]
2022-10-17 15:22:08.598 DEBUG 6912 --- [nio-8080-exec-3]
o.s.web.servlet.view.JstlView : View name
'index.jsp', model {}
2022-10-17 15:22:08.599 DEBUG 6912 --- [nio-8080-exec-3]
o.s.web.servlet.view.JstlView : Forwarding to
[index.jsp]
2022-10-17 15:22:09.542 DEBUG 6912 --- [nio-8080-exec-3]
o.s.web.servlet.DispatcherServlet : Completed 200 OK
2022-10-17 15:22:12.329 DEBUG 6912 --- [nio-8080-exec-7]
o.s.web.servlet.DispatcherServlet : GET
"/resources/js/jquery-1.11.1.min.js", parameters={}
2022-10-17 15:22:12.337 WARN 6912 --- [nio-8080-exec-7]
o.s.web.servlet.PageNotFound : No mapping for GET
/resources/js/jquery-1.11.1.min.js
2022-10-17 15:22:12.339 DEBUG 6912 --- [nio-8080-exec-7]
o.s.web.servlet.DispatcherServlet : Completed 404
NOT_FOUND
2022-10-17 15:22:12.340 DEBUG 6912 --- [nio-8080-exec-7]
o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for
GET "/error", parameters={}
2022-10-17 15:22:12.341 DEBUG 6912 --- [nio-8080-exec-7]
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to
com.giuggiola.controller.IndexController#error()
2022-10-17 15:22:12.343 DEBUG 6912 --- [nio-8080-exec-7]
m.m.a.RequestResponseBodyMethodProcessor : Using 'text/plain',
given [*/*] and supported [text/plain, */*, text/plain, */*,
application/json, application/*+json, application/json,
application/*+json, application/x-jackson-smile,
application/cbor]
2022-10-17 15:22:12.343 DEBUG 6912 --- [nio-8080-exec-7]
m.m.a.RequestResponseBodyMethodProcessor : Writing ["Error
handling"]
2022-10-17 15:22:12.345 DEBUG 6912 --- [nio-8080-exec-7]
o.s.web.servlet.DispatcherServlet : Exiting from "ERROR"
dispatch, status 404
2022-10-17 15:22:12.350 DEBUG 6912 --- [nio-8080-exec-9]
o.s.web.servlet.DispatcherServlet : GET
"/resources/js/bootstrap.min.js", parameters={}
2022-10-17 15:22:12.350 WARN 6912 --- [nio-8080-exec-9]
o.s.web.servlet.PageNotFound : No mapping for GET
/resources/js/bootstrap.min.js
2022-10-17 15:22:12.351 DEBUG 6912 --- [nio-8080-exec-9]
o.s.web.servlet.DispatcherServlet : Completed 404
NOT_FOUND
2022-10-17 15:22:12.352 DEBUG 6912 --- [nio-8080-exec-9]
o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for
GET "/error", parameters={}
2022-10-17 15:22:12.353 DEBUG 6912 --- [nio-8080-exec-9]
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to
com.giuggiola.controller.IndexController#error()
2022-10-17 15:22:12.354 DEBUG 6912 --- [nio-8080-exec-9]
m.m.a.RequestResponseBodyMethodProcessor : Using 'text/plain',
given [*/*] and supported [text/plain, */*, text/plain, */*,
application/json, application/*+json, application/json,
application/*+json, application/x-jackson-smile,
application/cbor]
2022-10-17 15:22:12.355 DEBUG 6912 --- [nio-8080-exec-9]
m.m.a.RequestResponseBodyMethodProcessor : Writing ["Error
handling"]
2022-10-17 15:22:12.356 DEBUG 6912 --- [nio-8080-exec-9]
o.s.web.servlet.DispatcherServlet : Exiting from "ERROR"
dispatch, status 404
2022-10-17 15:22:16.001 DEBUG 6912 --- [nio-8080-exec-4]
o.s.web.servlet.DispatcherServlet : GET
"/lista_parlamentari_circoscrizione?circoscrizione=Calabria",
parameters={masked}
2022-10-17 15:22:16.002 WARN 6912 --- [nio-8080-exec-4]
o.s.web.servlet.PageNotFound : No mapping for GET
/lista_parlamentari_circoscrizione
2022-10-17 15:22:16.002 DEBUG 6912 --- [nio-8080-exec-4]
o.s.web.servlet.DispatcherServlet : Completed 404
NOT_FOUND
2022-10-17 15:22:16.003 DEBUG 6912 --- [nio-8080-exec-4]
o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for
GET "/error?circoscrizione=Calabria", parameters={masked}
2022-10-17 15:22:16.004 DEBUG 6912 --- [nio-8080-exec-4]
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to
com.giuggiola.controller.IndexController#error()
2022-10-17 15:22:16.006 DEBUG 6912 --- [nio-8080-exec-4]
m.m.a.RequestResponseBodyMethodProcessor : Using 'text/html',
given [text/html, application/xhtml+xml, image/avif,
image/webp, image/apng, application/xml;q=0.9,
application/signed-exchange;v=b3;q=0.9, */*;q=0.8] and
supported [text/plain, */*, text/plain, */*, application/json,
application/*+json, application/json, application/*+json,
application/x-jackson-smile, application/cbor]
2022-10-17 15:22:16.007 DEBUG 6912 --- [nio-8080-exec-4]
m.m.a.RequestResponseBodyMethodProcessor : Writing ["Error
handling"]
2022-10-17 15:22:16.010 DEBUG 6912 --- [nio-8080-exec-4]
o.s.web.servlet.DispatcherServlet : Exiting from "ERROR"
dispatch, status 404
application.properties
spring.jpa.open-in-view=true
spring.mvc.static-path-pattern=/webapp/
spring.postgresql.console.enabled=true
view.prefix:/webapp/
suffix:.jsp
server.port=****
org.springframework.boot.autoconfigure.web.ResourceProperties=
/webapp/
org.springframework.web.servlet.resource.PathResourceResolver=
/webapp/
spring.sql.init.platform=postgres
spring.datasource.url=
jdbc:postgresql://localhost:****/Parlamento
spring.datasource.username=postgres
spring.jpa.properties.hibernate.dialect =
org.hibernate.dialect.PostgreSQL10Dialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.use-new-id-generator-mappings=true
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.jdbc.lob.
non_contextual_creation
=true
spring.datasource.password=**********
spring.jpa.properties.hibernate.format_sql=true
#spring.sql.init.mode=always
#spring.sql.init.schema-locations=classpath:/schema.sql
spring.sql.init.continue-on-error=true
spring.profiles.active=#spring.profiles.active#
logging.level.org.springframework.web: DEBUG
spring.datasource.tomcat.abandon-when-percentage-full=1
spring.datasource.xa.data-source-class-name= SELECT 1
spring.jpa.database-
platform=org.hibernate.dialect.PostgreSQL10Dialect
spring.main.allow-bean-definition-overriding=true
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
server.servlet.context-path=/
server.error.whitelabel.enabled=false
server.servlet.context-path=/
server.servlet-path=/
spring.resources.static-locations=/webapp/
#spring.web.resources.staticlocations=
#classpath:/webapp/,classpath:/webapp
spring.web.resources.static-locations=/webapp
#spring.autoconfigure.exclude=org.springframework.boot.
# autoconfigure.jdbc.DataSourceAutoConfiguration,
# org.springframework.boot.autoconfigure.orm.jpa.
# HibernateJpaAutoConfiguration
ParlamentoApplication.java
#SpringBootApplication
//#Configuration
#ComponentScan({"com.giuggiola.controller"})
/*
#EnableAutoConfiguration(
exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class
}
)
*/
#EnableAutoConfiguration
public class ParlamentoApplication{
public static void main(String[] args) {
SpringApplication.run(ParlamentoApplication.class, args);
}
}
WebConfig.java
//WebMvcAutoConfigurationAdapter
//#EnableSpringDataWebSupport
//#EnableWebMvc
#Configuration
#ComponentScan("com.giuggiola.controller")
public class WebConfig implements WebMvcConfigurer{
//WebMvcAutoConfigurationAdapter{//WebMvcConfigurer
{//WebMvcAutoConfiguration{
//WebMvcConfigurer { //public class WebConfig implements
WebMvcConfigurer {
// All web configuration will go here
// /Parlamento/src/main/webapp
// private static final String[] CLASSPATH_RESOURCE_LOCATIONS
=
{"classpath:/webapp/" }; // {"classpath:/webapp/" };
private static final String[]
CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/", "classpath:/public/" ,
"classpath:/webapp/"};
#Override
public void addResourceHandlers(ResourceHandlerRegistry
registry) {
registry.addResourceHandler("/**")
.addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
}
#Bean
public ViewResolver internalResourceViewResolver() {
InternalResourceViewResolver bean = new
InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/webapp/");
bean.setSuffix(".jsp");
return bean;
}
#Bean
public BeanNameViewResolver beanNameViewResolver(){
return new BeanNameViewResolver();
}
#Bean
public View cerca_parlamentare_dalla_circoscrizione() {
//JstlView
return new
JstlView("/webapp/cerca_parlamentare_dalla_circoscrizione.jsp");
}
#Bean
public View lista_parlamentari_circoscrizione() { //JstlView
return new
JstlView("/webapp/lista_parlamentari_circoscrizione.jsp");
}
}
hibernate.cgf.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"C:\Users\segreteria\Documents\Librerie/hibernate-
configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Related to the connection START -->
<property
name="connection.driver_class">org.postgresql.Driver</property>
<property
name="connection.url">jdbc:postgresql:
//localhost:****/Parlamento</property>
<property name="connection.user">postgres</property>
<property name="connection.password">**********</property>
<property name="show_sql">true</property>
<property
name="dialet">org.hibernate.dialect.PostgreSQL10Dialect
</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.giuggiola.entity.Parlamentare" />
<mapping class="com.giuggiola.entity.PK"/>
<mapping class="com.giuggiola.entity.Periodi_cariche"/>
<mapping class="com.giuggiola.entity.Range2PK"/>
</session-factory>
</hibernate-configuration>
I tried very simple Route:
restConfiguration()
.component("servlet");
rest().get("/hello")
.to("direct:hello");
from("direct:hello")
.log(LoggingLevel.INFO, "Hello World")
.transform().simple("Hello World");
And indeed, when lunching my spring boot application I can see that the route listens to it:
[enter image description here][1]
2021-04-14 15:03:31.759 INFO 25248 --- [ main] o.a.c.i.e.InternalRouteStartupManager : Route: route1 started and consuming from: direct://hello
2021-04-14 15:03:31.760 INFO 25248 --- [ main] o.a.c.i.e.InternalRouteStartupManager : Route: route2 started and consuming from: servlet:/hello
2021-04-14 15:03:31.768 INFO 25248 --- [ main] o.a.c.impl.engine.AbstractCamelContext : Total 2 routes, of which 2 are started
2021-04-14 15:03:31.768 INFO 25248 --- [ main] o.a.c.impl.engine.AbstractCamelContext : Apache Camel 3.7.1 (camel-1) started in 220ms
However, when I tried reaching this address, I get 404 error.
{
"timestamp": "2021-04-14T12:17:11.975+00:00",
"status": 404,
"error": "Not Found",
"message": "",
"path": "/hello"
}
and also in my console:
2021-04-14 15:17:11.973 WARN 25248 --- [nio-8080-exec-4] o.s.web.servlet.PageNotFound : No mapping for GET /hello
Any idea how to solve it?
I would say here that I googled this issue and solution like using "camel.component.servlet.mapping.context-path=/*
" or using "camel" prefix didn't work for me.
Thanks!
create a bean like that any configuration class
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Bean
public ServletRegistrationBean camelServletRegistrationBean() {
ServletRegistrationBean registration = new ServletRegistrationBean(new CamelHttpTransportServlet(), "/*");
registration.setName("CamelServlet");
return registration;
}}
for example camel rest and spring boot : https://github.com/erayerdem/camelrest
I have been working on Apache camel to connect https URLS' by providing TLS certificate via proxy but getting error org.apache.http.conn.UnsupportedSchemeException: http protocol is not supported
Below is the camel route and ssl context with proxy
public class HttpProxyRouter extends RouteBuilder {
#Override
public void configure() throws Exception {
configureSslForHttp4(getContext());
from("direct:httpproxy")
.log("Invoking dhttpproxy")
.setHeader("CamelHttpMethod")
.simple("GET").setHeader("Accept")
.simple(Constants.JSON_MEDIA_TYPE_VALUE)
.setHeader(Exchange.HTTP_PATH)
.simple("{{http.proxy.path}}")
.setHeader(Exchange.REST_HTTP_QUERY)
.simple("{{http.proxy.query.param}}")
.to("{{http.proxy.url}}")
.log("The Retrival of CCO subscription API response code is: ${header.CamelHttpResponseCode}, JSON Response ${body}")
.end();
}
private void configureSslForHttp4(CamelContext camelContext) {
KeyStore truststore = KeyStore.getInstance("JKS");
truststore.load(getClass().getClassLoader().getResourceAsStream("H:\config/AL/certpath/cert/keystore.jks"), "njfeijiiii".toCharArray());
TrustManagerFactory trustFactory = TrustManagerFactory.getInstance("SunX509");
trustFactory.init(truststore);
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, trustFactory.getTrustManagers(), null);
SSLSocketFactory factory = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry registry = new SchemeRegistry();
final Scheme scheme = new Scheme("https4", 443, factory);
registry.register(scheme);
HttpComponent http4 = camelContext.getComponent("https4", HttpComponent.class);
http4.setHttpClientConfigurer(new HttpClientConfigurer() {
#Override
public void configureHttpClient(HttpClientBuilder builder) {
builder.setSSLSocketFactory(factory);
HttpHost proxy = new HttpHost("MYcompany.proxy",8080);
builder.setProxy(proxy);
builder.setRoutePlanner(new DefaultProxyRoutePlanner(proxy));
Registry registry = RegistryBuilder.create().register("https", factory).build();
HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry);
builder.setConnectionManager(connectionManager);
}});
}
}
Error being encountered
org.apache.catalina.core.ApplicationContext logINFO: Initializing Spring FrameworkServlet 'dispatcherServlet'43953 [http-nio-6723-exec-2] INFO org.springframework.web.servlet.DispatcherServlet -FrameworkServlet 'dispatcherServlet': initialization started44033 [http-nio-6723-exec-2] INFO org.springframework.web.servlet.DispatcherServlet -FrameworkServlet 'dispatcherServlet': initialization completed in 80 ms44126 [http-nio-6723-exec-2] INFO com.db.gtbb.adapter.controller.HttpProxyRestController -httpProxyHandler has been started!44152 [http-nio-6723-exec-2] INFO route1 -Invoking dhttpproxy
44291 [http-nio-6723-exec-2] INFO org.apache.http.impl.execchain.RetryExec -I/O exception (org.apache.http.conn.UnsupportedSchemeException) caught when processing request to {tls}->http://mycompany.proxy:8080->https://mycompany.target:443: http protocol is not supported44293 [http-nio-6723-exec-2] INFO org.apache.http.impl.execchain.RetryExec -Retrying request to {tls}->http://mycompany.proxy:8080->https://mycompany.target:44344296 [http-nio-6723-exec-2] INFO org.apache.http.impl.execchain.RetryExec -I/O exception (org.apache.http.conn.UnsupportedSchemeException) caught when processing request to {tls}->http://mycompany.proxy:8080->https://mycompany.target:443: http protocol is not supported44296 [http-nio-6723-exec-2] INFO org.apache.http.impl.execchain.RetryExec -Retrying request to {tls}->http://mycompany.proxy:8080->https://mycompany.target:44344296 [http-nio-6723-exec-2] INFO org.apache.http.impl.execchain.RetryExec -I/O exception (org.apache.http.conn.UnsupportedSchemeException) caught when processing request to {tls}->http://mycompany.proxy:8080->https://mycompany.target:443: http protocol is not supported44296 [http-nio-6723-exec-2] INFO org.apache.http.impl.execchain.RetryExec -Retrying request to {tls}->http://mycompany.proxy:8080->https://mycompany.target:44344301 [http-nio-6723-exec-2] ERROR org.apache.camel.processor.DefaultErrorHandler -Failed delivery for (MessageId: ID-SGSINSD822483-57673-1614083753968-0-1on ExchangeId: ID-SGSINSD822483-57673-1614083753968-0-2). Exhausted after delivery attempt: 1 caught: org.apache.http.conn.UnsupportedSchemeException: http protocol is not supportedMessage History---------------------------------------------------------------------------------------------------------------------------------------RouteId ProcessorId Processor Elapsed (ms)[route1 ] [route1 ] [ ] [ 155][route1 ] [log1 ] [log ] [ 6][route1 ] [setHeader1 ] [setHeader[CamelHttpMethod] ] [ 3][route1 ] [setHeader2 ] [setHeader[Accept] ] [ 2][route1 ] [setHeader3 ] [setHeader[CamelHttpPath] ] [ 2][route1 ] [setHeader4 ] [setHeader[CamelRestHttpQuery] ] [ 16][route1 ] [to1 ] [{{http.proxy.url}} ] [ 118]Stacktrace---------------------------------------------------------------------------------------------------------------------------------------
org.apache.http.conn.UnsupportedSchemeException: http protocol is not supportedat org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:108)at org.apache.http.impl.conn.BasicHttpClientConnectionManager.connect(BasicHttpClientConnectionManager.java:338)at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:388)at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)at org.apache.camel.component.http4.HttpProducer.executeMethod(HttpProducer.java:306)at org.apache.camel.component.http4.HttpProducer.process(HttpProducer.java:178)at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:145)at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:542)at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197)at org.apache.camel.processor.Pipeline.process(Pipeline.java:120)at org.apache.camel.processor.Pipeline.process(Pipeline.java:83)at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197)at org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:62)at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:97)at org.apache.camel.impl.ProducerCache$1.doInProducer(ProducerCache.java:529)at org.apache.camel.impl.ProducerCache$1.doInProducer(ProducerCache.java:497)at org.apache.camel.impl.ProducerCache.doInProducer(ProducerCache.java:365)at org.apache.camel.impl.ProducerCache.sendExchange(ProducerCache.java:497)at org.apache.camel.impl.ProducerCache.send(ProducerCache.java:209)at org.apache.camel.impl.DefaultProducerTemplate.send(DefaultProducerTemplate.java:139)at org.apache.camel.impl.DefaultProducerTemplate.send(DefaultProducerTemplate.java:125)at com.db.gtbb.adapter.controller.HttpProxyRestController.httpProxyHandler(HttpProxyRestController.java:27)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:498)at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:105)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:107)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1100)at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)at java.lang.Thread.run(Thread.java:748)44318 [http-nio-6723-exec-2] INFO
you need to add http protocol to registry:
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslctxt, hnv);
Registry<ConnectionSocketFactory> lookup = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", sslSocketFactory).build();
I am using the below AngularJS client code to perform a HTTP post request with JSON formatted payload to the jersey rest service
patientMgmtModule.controller('NewPatientCtrl',
function NewPatientCtrl($scope, $http)
{
$scope.addPatient = function (){
var patientJSON = angular.toJson($scope.Patient);
console.log("Patient (JSON) is ============> " + patientJSON);
$http({
method: 'POST',
data: $scope.Patient,
url:'/ManagePatient/AddPatient',
headers: {'Content-Type':'application/x-www-form-urlencoded;application/json;'}
});
};
}
);
I have the following maven dependencies for Jersey:
<dependency>
<groupId>org.glassfish.jersey.archetypes</groupId>
<artifactId>jersey-quickstart-webapp</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.0</version>
</dependency>
On the Server Side, I have
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.hms.app.ui.beans.Patient;
#Path("/ManagePatient")
public class PatientController {
#POST
#Path("/AddPatient")
#Consumes({MediaType.APPLICATION_JSON})
public String addPatient(Patient patient) {
System.out.println("Sarat's servlet called" );
//patient.toConsole();
System.out.println("Done Calling Patient To Console");
return "Done Calling Patient To Console";
}
}
When I submit the form on the client side, I see the below error in the chrome console -
POST http://localhost:8080/HMS_Web/services/ManagePatient/AddPatient 500 (Internal Server Error) angular.min.js:99
and on the server end, I see (high level detail 1):
SEVERE: Servlet.service() for servlet [Jersey REST Service] in context with path [/HMS_Web] threw exception
org.glassfish.jersey.message.internal.HeaderValueException: Unable to parse "Content-Type" header value: "application/x-www-form-urlencoded;application/json;"
and the last stack trace has this:
Caused by: java.text.ParseException: Expected separator '=' instead of '/'
Detailed stack trace: (
Aug 01, 2013 9:28:18 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Jersey REST Service] in context with path [/HMS_Web] threw exception
org.glassfish.jersey.message.internal.HeaderValueException: Unable to parse "Content-Type" header value: "application/x-www-form-urlencoded;application/json;"
at org.glassfish.jersey.message.internal.InboundMessageContext.exception(InboundMessageContext.java:318)
at org.glassfish.jersey.message.internal.InboundMessageContext.singleHeader(InboundMessageContext.java:313)
at org.glassfish.jersey.message.internal.InboundMessageContext.getMediaType(InboundMessageContext.java:427)
at org.glassfish.jersey.servlet.WebComponent.filterFormParameters(WebComponent.java:482)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:303)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.ws.rs.ProcessingException: java.lang.IllegalArgumentException: Error parsing media type 'application/x-www-form-urlencoded;application/json;'
at org.glassfish.jersey.message.internal.InboundMessageContext$5.apply(InboundMessageContext.java:433)
at org.glassfish.jersey.message.internal.InboundMessageContext$5.apply(InboundMessageContext.java:427)
at org.glassfish.jersey.message.internal.InboundMessageContext.singleHeader(InboundMessageContext.java:311)
... 22 more
Caused by: java.lang.IllegalArgumentException: Error parsing media type 'application/x-www-form-urlencoded;application/json;'
at org.glassfish.jersey.message.internal.MediaTypeProvider.fromString(MediaTypeProvider.java:89)
at org.glassfish.jersey.message.internal.MediaTypeProvider.fromString(MediaTypeProvider.java:59)
at javax.ws.rs.core.MediaType.valueOf(MediaType.java:179)
at org.glassfish.jersey.message.internal.InboundMessageContext$5.apply(InboundMessageContext.java:431)
... 24 more
Caused by: java.text.ParseException: Expected separator '=' instead of '/'
at org.glassfish.jersey.message.internal.HttpHeaderReader.nextSeparator(HttpHeaderReader.java:115)
at org.glassfish.jersey.message.internal.HttpHeaderReader.readParameters(HttpHeaderReader.java:261)
at org.glassfish.jersey.message.internal.HttpHeaderReader.readParameters(HttpHeaderReader.java:242)
at org.glassfish.jersey.message.internal.MediaTypeProvider.valueOf(MediaTypeProvider.java:107)
at org.glassfish.jersey.message.internal.MediaTypeProvider.fromString(MediaTypeProvider.java:87)
... 27 more
Aug 01, 2013 9:29:00 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Jersey REST Service] in context with path [/HMS_Web] threw exception
org.glassfish.jersey.message.internal.HeaderValueException: Unable to parse "Content-Type" header value: "application/x-www-form-urlencoded;application/json;"
at org.glassfish.jersey.message.internal.InboundMessageContext.exception(InboundMessageContext.java:318)
at org.glassfish.jersey.message.internal.InboundMessageContext.singleHeader(InboundMessageContext.java:313)
at org.glassfish.jersey.message.internal.InboundMessageContext.getMediaType(InboundMessageContext.java:427)
at org.glassfish.jersey.servlet.WebComponent.filterFormParameters(WebComponent.java:482)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:303)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.ws.rs.ProcessingException: java.lang.IllegalArgumentException: Error parsing media type 'application/x-www-form-urlencoded;application/json;'
at org.glassfish.jersey.message.internal.InboundMessageContext$5.apply(InboundMessageContext.java:433)
at org.glassfish.jersey.message.internal.InboundMessageContext$5.apply(InboundMessageContext.java:427)
at org.glassfish.jersey.message.internal.InboundMessageContext.singleHeader(InboundMessageContext.java:311)
... 22 more
Caused by: java.lang.IllegalArgumentException: Error parsing media type 'application/x-www-form-urlencoded;application/json;'
at org.glassfish.jersey.message.internal.MediaTypeProvider.fromString(MediaTypeProvider.java:89)
at org.glassfish.jersey.message.internal.MediaTypeProvider.fromString(MediaTypeProvider.java:59)
at javax.ws.rs.core.MediaType.valueOf(MediaType.java:179)
at org.glassfish.jersey.message.internal.InboundMessageContext$5.apply(InboundMessageContext.java:431)
... 24 more
Caused by: java.text.ParseException: Expected separator '=' instead of '/'
at org.glassfish.jersey.message.internal.HttpHeaderReader.nextSeparator(HttpHeaderReader.java:115)
at org.glassfish.jersey.message.internal.HttpHeaderReader.readParameters(HttpHeaderReader.java:261)
at org.glassfish.jersey.message.internal.HttpHeaderReader.readParameters(HttpHeaderReader.java:242)
at org.glassfish.jersey.message.internal.MediaTypeProvider.valueOf(MediaTypeProvider.java:107)
at org.glassfish.jersey.message.internal.MediaTypeProvider.fromString(MediaTypeProvider.java:87)
... 27 more
After implementing LoggingFilter - I see that the server is responding with HTTP 415.
Aug 04, 2013 10:28:25 AM org.glassfish.jersey.filter.LoggingFilter log
INFO: 2 * LoggingFilter - Request received on thread tomcat-http--11
2 > POST http://localhost:8080/HMS_Web/services/ManagePatient/AddPatient
2 > host: localhost:8080
2 > connection: keep-alive
2 > content-length: 341
2 > accept: application/json, text/plain, */*
2 > origin: http://localhost:8080
2 > x-requested-with: XMLHttpRequest
2 > user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36
2 > content-type: application/json
2 > dnt: 1
2 > referer: http://localhost:8080/HMS_Web/views/Landing.html
2 > accept-encoding: gzip,deflate,sdch
2 > accept-language: en-US,en;q=0.8
Aug 04, 2013 10:28:25 AM org.glassfish.jersey.filter.LoggingFilter log
INFO: 2 * LoggingFilter - Response received on thread tomcat-http--11
2 < 415
Your Content-Type header is invalid (see spec 14.17 Content-Type). Based on you JAX-RS resource you should use application/json as Content-Type (without application/x-www-form-urlencoded):
$http({
method: 'POST',
data: $scope.Patient,
url:'/ManagePatient/AddPatient',
headers: {'Content-Type':'application/json'}
});
EDIT 1:
If you want to see requests that are coming to your server you can register LoggingFilter and it will show you some useful information. You can turn it on in:
web.xml (add it to the JAX-RS servlet definition):
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.filter.LoggingFilter</param-value>
</init-param>
Application extension:
public class MyApplication extends Application {
#Override
public Set<Class<?>> getClasses() {
return new HashSet<Class<?>>() {{
// Add your resources.
add(HelloWorldResource.class);
// Add LoggingFilter.
add(LoggingFilter.class);
}};
}
}
ResourceConfig instance (demonstrating also outputting the entity here):
public class MyApplication extends ResourceConfig {
public MyApplication() {
// Resources - add your package name here to enable package scanning.
packages(...);
// Enable LoggingFilter & output entity.
registerInstances(new LoggingFilter(Logger.getLogger(MyApplication.class.getName()), true));
}
}
EDIT 2:
Jersey 2.x does not support application/json media type out of the box - you need to add one of the JSON modules to your classpath (see JSON section in users guide), for example:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.0</version>
</dependency>