HTTP Status 404 - /EventTracker/greeting - java

I am trying to access the http://localhost:8080/EventTracker/greeting on my machine. However, I am getting a 404 error. I am following the PluralSight Introduction to Spring MVC4 tutorial and it seems like my code is matching the ones in the video. I am using the two java files WebConfig and WebAppInitializer to configure my application. Am I missing anything? I think I have copied over line by line but still not working.
HelloController.java
#Controller
public class HelloController {
#RequestMapping(value="/greeting")
public String sayHello(Model model) {
model.addAttribute("greeting", "Hello World");
return "hello.jsp";
}
}
WebAppInitializer.java
public class WebAppInitializer implements WebApplicationInitializer{
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context) );
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context) );
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("*.html");
}
private WebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.pluralsight.WebConfig");
return context;
}
}
WebConfig.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.pluralsight")
public class WebConfig {
}
hello.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>${greeting}</h1>
</body>
</html>
EDITED 9/15 4:25 PM PST
When using http://localhost:8080/EventTracker/greeting.html, I still get the same error, the error being:
16:24:41.925 [http-nio-8080-exec-3] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name 'DispatcherServlet' processing GET request for [/EventTracker/greeting.html]
16:24:41.931 [http-nio-8080-exec-3] WARN o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/EventTracker/greeting.html] in DispatcherServlet with name 'DispatcherServlet'
16:24:41.931 [http-nio-8080-exec-3] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request

Because it was first question which I found in google and here no right answer, here is what helped me.
You should add in WebAppInitializer.java next
context.register(com.pluralsight.WebConfig.class);
So your file should looks like:
public class WebAppInitializer implements WebApplicationInitializer{
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context) );
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context) );
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("*.html");
}
private WebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.pluralsight.WebConfig");
context.register(com.pluralsight.WebConfig.class);
return context;
}
}

I've never created a Spring MVC app that didn't have XML config files. I'm sure it's possible, but I'd have to look into it. If you don't mind using XML files for configuration, you could do something similar to the following (this is a little side project I did awhile ago to better familiarize myself with Spring MVC):
web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3MVC</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<!--if not using jsp, can omit this -->
<jsp-config> <!-- if taglib not inside jsp-config, will cause deployment errors -->
<taglib>
<taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/taglib/c.tld</taglib-location>
</taglib>
</jsp-config>
web.xml is the top tier of configuration. From the above, the important thing to remember is that the names which file (it will also be an XML file) is the dispatcher servlet file. Whatever you include inside tags will have -servlet.xml appended to it, so in this case, my dispatcher servlet will be a file called spring-servlet.xml. The tag tells the app which type of url patterns are associated with the dispatcher servlet. So in this example, any url ending in .html will be handled by spring-servlet.xml.
If you are using JSP, make sure that all your tags are within a tag, otherwise it won't work correctly.
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan
base-package="net.viralpatel.spring3.controller" />
<!-- declares package where controller(s) stored. Don't need to declare indvd controllers -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" /> <!-- hello.jsp must be located in this directory for link to work -->
<property name="suffix" value=".jsp" />
</bean>
This is what the dispatcher servlet file looks like. You can ignore the code at the top. Based on the error you posted, my guess is that your java code has left out or incorrectly mapped your view resolver. The view resolver is what converts the strings you pass into your controller (ie: hello) into your relative URL paths (ie: /WEB-INF/jsp/hello.jsp). For this to work correctly, make sure all your jsp files are in the same directory, and list that directory as part of your prefix value. In this example, I stored all my jsp files inside a directory called jsp in my WEB-INF directory. The suffix in this example is just the file extension. Any file that isn't stored in this directory will cause your app to throw a 404 error when it tries to load that missing file.
I know this isn't exactly what you set out to do, but if you choose to use XML files, I hope this helps. Let me know if you have any questions.

I had the same problem.
The problem was that "native library" wasn't there in my Tomcat installation folder.
I solve that with:
sudo apt-get install libtcnative-1
Then I had the problem my native library version was too old and I solve that with upgrade:
sudo apt-get upgrade libtcnative-1
I hope it will help :)

context.register(WebConfig.class)
adding this in webapp intializer will solve your problem

Your url http://localhost:8080/EventTracker/greeting doesn't match your dispatcher mapping: dispatcher.addMapping("*.html");. Try http://localhost:8080/EventTracker/greeting.html

Related

Spring MVC - simple file upload HTTP Status 500 - Could not parse multipart servlet request

I'm starting learning the Spring MVC. Want to make web app with Excel file upload to database.
I'm starting with simple file upload and got problems at beginning.
My project made in Netbans using Maven and Tomcat 8.
I made simple example project with tutorial
https://saarapakarinen.wordpress.com/2015/01/11/building-a-basic-spring-3-web-project-netbeans-and-maven/
and it worked perfectly, but I wanted to change it a little to file upload based on official Spring help
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-multipart
I got opening form with file upload, when I select file and submit it i got an error:
HTTP Status 500 - Could not parse multipart servlet request; nested exception is
java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided
How to solve this and where is error? It is error in my code or I'm missing somthing, or got wrong configuration?
I have one form on form.jsp file and one controller class HelloController why its not working?
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- name of the project//-->
<display-name>HelloProject</display-name>
<servlet>
<servlet-name>front-controller</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>front-controller</servlet-name>
<url-pattern>/application/*</url-pattern>
</servlet-mapping>
<!-- max time of the session //-->
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<!-- default page //-->
<welcome-file-list>
<welcome-file>application/form.jsp</welcome-file>
</welcome-file-list>
</web-app>
front-controller-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- configuration to fetch jsp files automatically from WEB-INF/jsp -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="1000000"/>
</bean>
<context:component-scan base-package="helloweb"/>
</beans>
form.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form Page</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="">
<label>file to send: <input type="file" name="file" /></label>
<input type="submit" />
</form>
</body>
</html>
HelloController.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package helloweb;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
#Controller
public class HelloController
{
private String startmessage="start";
#RequestMapping("form")
public String viewLoginPage(Model model)
{
model.addAttribute("message", startmessage);
return "form";
}
#RequestMapping(value = "form", method = RequestMethod.POST)
public String login(
#RequestParam(value = "file", required = true) MultipartFile file)
{
if((file.isEmpty()) )
{
startmessage="file empty";
return "redirect:form";
}
else
{
byte[] bytes = file.getBytes();
return "hello";
}
}
}

Spring MVC resource Mapping

I have been testing some request mapping in Spring MVC, and I came across a strange situation in my application. I decided to create a simple cenario so that you can understand my problem. I will first show you the details of my project (the source), and then I'll get to my question.
I have the following directory structure in my project:
+webapp
+WEB-INF
+recursos
+estilos
test.css
+spring
fronte-beans.xml
+views
+testes
page1.jsp
page2.jsp
web.xml
My Tomcat deployment descriptor:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.4">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>fronte</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/spring/fronte-beans.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>fronte</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
My application context for DispatcherServlet:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd ">
<mvc:annotation-driven />
<mvc:resources mapping="/recursos/**" location="/WEB-INF/recursos/" />
<context:component-scan base-package="com.regra7.minhaapp.contro" />
<bean id="handlerMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
My controller class for page1.jsp:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping(value="/path")
public class TestController
{
#RequestMapping(value="/to/something")
public String getPage()
{
return "testes/page2";
}
}
My page1.jsp:
<!DOCTYPE html>
<%# page
language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html lang="pt-BR">
<!-- ############################################### -->
<!-- HEADER -->
<!-- ############################################### -->
<head>
<title>Test Page</title>
<meta name="author" content="RDS" />
<meta name="description" content="? ? ?" />
<meta charset="UTF-8" />
<link rel="stylesheet" type="text/css" href="recursos/estilos/test.css" media="all" />
</head>
<!-- ############################################### -->
<!-- BODY -->
<!-- ############################################### -->
<body>
<h1>PAGE 1</h1>
<p>This is a test, p1.</p>
<p>This is a test, p2.</p>
<p>This is a test, p3.</p>
CLICK TO PAGE 2
</body>
</html>
I can access page1.jsp and page2.jsp smoothly, but the CSS file of page2.jsp ends up not being found. The following text is printed on my console:
dez 29, 2014 8:16:22 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/testeSpringMvc/path/to/recursos/estilos/test.css] in DispatcherServlet with name 'fronte'
For what reason "/path/to" is being included in the resulting path? If I try to add different combinations of mapping, both class or method-level, the same thing happens. However, if I map the link to a query string (URL) as follows, the file is found without problems...
page1.jsp:
CLICK TO PAGE 2
Controller:
#Controller
#RequestMapping(value="/")
public class TestController
...
#RequestMapping(params="cd=page2")
public String getPage()
What's happening? How can I set a path I want so that my pages use and find the necessary resources? I'm trying to separate pages in different paths so that I can apply the security features from Tomcat (security constraints).
NOTE: I've tried using contextPath to help me in setting the CSS file path, but nothing worked. In fact, the situation worsened because Page1.jsp also turned out not having stylization:
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}recursos/estilos/test.css" media="all" />
As always, thank you for your attention and time.
Same was happening to me, and I found a solution. I hope this can help someone else:
As you see in the error message, paths you use for resources /testeSpringMvc/path/to/recursos/estilos/test.css are trying to be resolved by Spring's DispatchServlet.
This happens because in your web.xml file you have the following:
<servlet-mapping>
<servlet-name>fronte</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Your fronte servlet will try to resolve anything that starts with /.
Just add a simple extension to you <url-pattern>. Something like <url-pattern>/*.html</url-pattern> should do the job.
I just found the answer to my problems. I will leave here the solution, but unfortunately I did not understand how it solves the seen scenario.
I have found that this can be solved with JSTL. I read the JSTL documentation, and all I found was this description:
Creates a URL with optional query parameters.
If reference to the CSS file is changed by the following sentence, the problem will be solved:
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<link rel="stylesheet" type="text/css" href="<c:url value="/recursos/estilos/test.css" />" media="all" />
If any moderator see this and know the explanation of how this is resolved, I kindly ask you to expose it here. Edit my answer, or comment it out, please. I'm sure other people can have the same doubt as me in the future.
Thank you all for the attention and time.
Take a look at this blog entry. The relevant passage is:
If I want to apply main.css to url: www.mysite.com/index.html, I need
to use following construction in HTML code:
< link href="resources/css/main.css" rel="stylesheet" type="text/css"/ >
If I want to apply main.css to url: www.mysite.com/some/location.html,
I need to use following construction in HTML code:
< link href="../resources/css/main.css" rel="stylesheet" type="text/css"/ >
As a possible workaround, perhaps this might work:
<mvc:resources mapping="/**/recursos/**" location="/WEB-INF/recursos/" />
You can access resource as given below.
<link rel="stylesheet" type="text/css" href="/recursos/estilos/test.css" media="all" />
you are missing / at the beginning

JAX-RS rest services working fine. How to add JSP pages? Stuck with configuration

I have some rest services running already, using cxf-rt-frontend-jaxrs 2.7.7
/myservice/customers
/myservice/items
My rest service provides 2 endpoints:
#Component
public class CustomerService {
#GET
#Path("customers")
#Produces({MediaType.APPLICATION_JSON})
public ... getCustomers() { ... }
#GET
#Path("items")
#Produces({MediaType.APPLICATION_JSON})
public ... getItems() { ... }
}
This works great, and now I would like to add some jsp pages.
I've read about Redirecting requests and serving static content, but I can't get it to work and I am confused about the configuration in the web.xml and applicationContext.xml.
Here's what I have so far:
web.xml
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
applicationContext.xml
<jaxrs:server id="rest" address="/">
<jaxrs:serviceBeans>
<ref bean="customerWebService" />
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider"/>
<ref bean="dispatchProvider"/>
</jaxrs:providers>
</jaxrs:server>
<bean id="dispatchProvider" class="org.apache.cxf.jaxrs.provider.RequestDispatcherProvider">
<property name="dispatcherName" value="jsp"/>
<property name="resourcePath" value="/admin/item.jsp"/>
<property name="beanNames">
<map>
<entry key="com.company.domain.Item" value="item"/>
</map>
</property>
</bean>
jsp page
I have put a jsp web page named item.jsp into webapp/WEB-INF.
<%# page import="com.company.domain.Item" %>
<%
Item item = (Item) request.getAttribute("item");
%>
<html>
<head></head>
<body>
Item: <%= item.getEnglishName() %>.
</body>
</html>
Errors
If I open /customerservice/items I receive a valid JSON response from the rest service.
However if I open /customerservice/admin/item.jsp I receive this:
[10:34:45.791] [qtp104543434-33] WARN JAXRSUtils - No operation matching request path "/customerservice/admin/item.jsp" is found, Relative Path: /admin/item.jsp, HTTP Method: GET, ContentType: /, Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8,. Please enable FINE/TRACE log level for more details.
[10:34:45.796] [qtp104543434-33] ERROR DefaultExceptionMapper - DefaultExceptionMapper returned response: Internal Server Error
javax.ws.rs.ClientErrorException: null
at org.apache.cxf.jaxrs.utils.JAXRSUtils.findTargetMethod(JAXRSUtils.java:503) ~[cxf-rt-frontend-jaxrs-2.7.7.jar:2.7.7]
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:227) ~[cxf-rt-frontend-jaxrs-2.7.7.jar:2.7.7]
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:103) ~[cxf-rt-frontend-jaxrs-2.7.7.jar:2.7.7]
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:272) [cxf-api-2.7.7.jar:2.7.7]
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121) [cxf-api-2.7.7.jar:2.7.7]
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:239) [cxf-rt-transports-http-2.7.7.jar:2.7.7]
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:248) [cxf-rt-transports-http-2.7.7.jar:2.7.7]
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:222) [cxf-rt-transports-http-2.7.7.jar:2.7.7]
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:153) [cxf-rt-transports-http-2.7.7.jar:2.7.7]
What am I doing wrong?
Do I need separate servlets and url-mappings in my web.xml?
Does my request dispatcher require furhter configuration (e.g. dispatcherName property) ?
Many thanks for any guidance.
I changed my CXFServlet url-pattern to /rest/*
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
My rest urls are now /customerservice/rest/items and /customerservice/rest/customers.
And now I get a response for url /customerservice/admin/item.jsp, when my jsp pages are placed under webapp/admin (not webapp/WEB-INF/admin), which I presume is correct.
It appears that the request "falls through" to a default apache jasper JspServlet (which I have not configured in any way).
The response:
Hello World.
Great, thanks to Lutz for the initial comment!
Now I need to inject some beans into the jsp pages, perhaps there is there something like exposeContextBeansAsAttributes that I can use here.

Spring MVC 404 error [duplicate]

This question already has answers here:
Why does Spring MVC respond with a 404 and report "No mapping found for HTTP request with URI [...] in DispatcherServlet"?
(13 answers)
Closed 5 years ago.
I'm going crazy and can't understand what the problem is:
I have the following structure:
SpringMVC
+WebContent
-web-inf
-web.xml
-springMVC-servlet.xml
-index.jsp
-security
-login.jsp
web.xml
<display-name>springMVC</display-name>
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/index.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
springMVC-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans">
<context:annotation-config/>
<context:component-scan base-package="com.vanilla.springMVC"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
My Controller:
package com.vanilla.springMVC;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.portlet.ModelAndView;
#Controller
public class DefaultController {
#RequestMapping(value="/index.html", method=RequestMethod.GET)
public ModelAndView index(){
ModelAndView mv = new ModelAndView("index");
return mv;
}
#RequestMapping(value="/login.html", method=RequestMethod.GET)
public ModelAndView loginPage(){
ModelAndView mv = new ModelAndView("/security/login");
return mv;
}
}
I have no problem to navigate to /index.html
http://localhost:8080/SpringMVC/index.html
works perfect.
however when I'm navigating to
http://localhost:8080/SpringMVC/login.html
i have 404 error.
HTTP Status 404 - /SpringMVC/login.jsp
type Status report
message /SpringMVC/login.jsp
description The requested resource (/SpringMVC/login.jsp) is not available.
I don't want to move login.jsp on the same level as index.jsp, but why do I have this problem?
I'll just add this in here, because it solved my 404 issue. It turned out my problem was the url-mapping value in web.xml. Using Spring WebMVC version org.springframework:spring-webmvc:4.1.6.RELEASE
I was using the following (which didn't work):
<url-pattern>/rest</url-pattern>
I should've been using the following value (which works):
<url-pattern>/rest/*</url-pattern>
or
<url-pattern>/</url-pattern>
Reference: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html
HTTP 404 means that the resource is not found.
This means the controller or a direct accessed resource (like a CSS file) is not found
It does NOT mean that the JSP referred in the controller is not found (this would be a 500 Internal Server Error)
HTTP Status 404 - /SpringMVC/login.jsp
It looks like that you send a HTTP request /SpringMVC/login.jsp but your controller method is bound to .html, so you need to change your HTTP request to /SpringMVC/login.html
Because of the name (login) may your Spring Security configuration is not correct.
create a folder under WEB-INF "jsps" for all your views, and under "jsps" a "security" folder for your case.
NOTICE: Moving the JSP files into WEB-INF, you can prevent direct access on these files. It is needed for application security. Think about a situation, in which your JSPs gives personal informations about your customer and the access has to be granted/checked by your controller. If your JSPs are existing out of WEB-INF, they are accessible with a request directly on them.
configure your view resolver like this:
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsps"/>
<property name="suffix" value=".jsp"/>
</bean>
next, put your login JSPs into the "WEB-INF/jsps/security"
and return "security/login" from your loginPage.
Now, the view resolver searchs for the views under "WEB-INF/jsps". Because your method return "security/login", the view resolver expects a directory under jsps called "security" and a JSP file under this, which is called "login.jsp" (suffix = jsp)
I suspect that ModelAndView mv = new ModelAndView("/security/login"); is where the problem is. Make sure you have a directory 'security' folder in your root directory and it contains a login.jsp file. Or try moving the security folder inside WebContent
Provide the contextConfigLocation init parameter of your DispatcherServlet
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springMVC-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
I am using Spring MVC with eclipse and a MacOS X system and encountered a 404 error when controller returning the correct jsp name. I later figured out that the problematic jsp file has no x(execution) right on the file system. I then `chmod +x some.jsp' and the issue is resolved.
Adding this ans here just in case someone else faces the same issue.
My app was working fine earlier, then I upgraded Spring version and in the process also upgraded spring-security version. When I tried to access my login html page I was facing this issue. I had made all the necessary configurations changes because of the change of spring-security version from 3 to 4. I referred to this link and it was very helpful.
I was facing this problem because of the below configuration in my web-servlet.xml file
<mvc:resources mapping="/app/*.html" location="/app/*.html" cache-period="0"/>
<mvc:resources mapping="/app/**/*.html" location="/app/**/*.html" cache-period="0"/>
It worked after I modified both location values to "/app/". It seems like newer version of spring matches either the whole string or checks if the requested location starts with the location value configured above.
I found the below code in org.springframework.web.servlet.resource.PathResourceResolver:
if (locationPath.equals(resourcePath)) {
return true;
}
locationPath = (locationPath.endsWith("/") || locationPath.isEmpty() ? locationPath : locationPath + "/");
if (!resourcePath.startsWith(locationPath)) {
return false;
}
The second if condition was evaluating to false in my case and hence the 404 HTTP response
Another tip, if you face such error try enabling highest level of springframework logging. You might get to know the error reason from there.
This answer may be outdated for the above question, but it will help others who are just starting with spring.
I was also struggling with 404 WEB-INF/welcome.jsp page not found error.
Here issue is with ModelAndView import
Replace
import org.springframework.web.servlet.ModelAndView;
With
import org.springframework.web.portlet.ModelAndView;

404 with spring 3

hi
I am going through my first lessons with spring 3.I created a dynamic web app in eclipse with the following structure.
spring3mvc \src\my.spring.HelloWorldController.java
\WebContent
|
|-----WEB-INF\jsp\hello.jsp
|-----index.jsp
|-----WEB-INF\web.xml
|-----WEB-INF\spring-servlet.xml
|-----WEB-INF\lib\...*.jar files
I created the spring-servlet.xml as below
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/context
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="my.spring" />
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp">
<property name="contentType" value="text/html; charset=utf-8" />
</bean>
</beans>
and coded the controller
package my.spring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class HelloWorldController {
#RequestMapping("/hello")
public ModelAndView helloWorld() {
String message = "Hello World, Spring 3.0!";
return new ModelAndView("hello", "message", message);
}
}
index.jsp has a link to hello view
<html>
<body>
Say Hello
</body>
</html>
finally in hello.jsp I have put
<html>
<body>
${message}
</body>
</html>
My web.xml has
<display-name>Spring3MVC</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
When I run the app on Tomcat6 server( thru eclipse),I can see the index page at
http://localhost:8080/Spring3MVC/ .It displays the link to hello page.When I click on it(http://localhost:8080/Spring3MVC/hello.html),I get a 404 error.
message /Spring3MVC/hello.html
description The requested resource (/Spring3MVC/hello.html) is not available.
Any idea how I can solve this?
thanks
mark.
You need to configure ViewResolver.
Here is sample configuration:
<bean id="viewResolver"
class=" org.springframework.web.servlet.view. InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
When you do return new ModelAndView("hello", "message", message);
from above conf. it will try loading
prefix value + view name + suffix value
which will be required jsp.
Also you need to map your servlet in web.xml following way
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
I belive the problem is not the View resolver (it would print other exceptions).
Read the error message carfully, it tells what the problem is:
message /Spring3MVC/hello.html description
The requested resource (/Spring3MVC/hello.html) is not available.
It is that the hello .html (handler) can not be found, not the jsp. -- But I don't know what the exact problem it. -- I tryed to reproduce the error, but I did not get exact the same error message.
added -- find the problem
When you start the Server it prints all mappings to the controller in the log file. In your case there must by something like
INFO : org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/hallo] onto handler 'halloController'
If you don't have such a statement, then something is wrong with your context scan, or you have forget to enable the annotation driven MVC #Controller programming model. This can be enabled by adding:
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
I had the same issue.
Steps to Recreate
Open the Dashboard in Spring Tool Suite
Click "Spring Template
Project" in the "Create" area on the Dashboard
Right click on the newly created project in the Package Explorer pane of STS
SelectRun As > Run on Server
Choose Tomcat as your server and click Finish
Expected Result
The browser should launch and display the Hello World home page as defined by the HomeController > home action and the home.jsp view page.
Actual Result
404 Error
The Solution
1. Open up HomeController.java
2. Add a space anywhere in the file. Yeah. A space. Hit the spacebar. This is the solution. LOL
3. Run the project again as you did before.
This gives you the expected result.
My Hypothesis
The HomeController class isn't compiling initially, so the component-scan method isn't finding it; making it necessary to make a change to the file, and save it. This forces the class to be compiled, and therefore makes the home controller and the /home action discoverable.
I messed around with configuration files until I was pulling my hair out. I can't even tell you what made me think to try this. ;-) Glad I got it figured out though. Hopefully the Spring MVC 3 team will look into this, as it could easily create a serious barrier to entry to an otherwise cool framework.

Categories

Resources