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.
Related
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
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 6 years ago.
I'm new to Spring & Request Mapping and I currently have a maven web project setup that doesn't seem to handle my initial request properly
In my web.xml I have:
<servlet>
<servlet-name>Example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/Example-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Example</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
And my Example-servlet.xml:
<context:component-scan base-package="com.example.controller" /> //right package
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
And lastly my ExampleController:
#Controller
#RequestMapping("/")
public class ExampleController {
#RequestMapping(value = "/start")
public String start() {
System.out.println("Example Starting...");
}
}
My example directory structure:
however when I navigate to localhost:8080/example/ my page loses all of it's CSS styling and pretty much all calls to other files in the project. I get the Warning
No mapping found for HTTP request with URI [/example/css/main.css] in DispatcherServlet with name 'Example'
And a bunch of other warnings/404's for files I'm not trying to map.
Could someone help me understand exactly where my project is misconfigured?
Hi,
Your css and js files should be located in the resource folder that needs to be configured in servlet context configuration.
For example (Example-servlet.xml):
<resources mapping="/css/**" location="/css/" />
<resources mapping="/js/**" location="/js/" />
The means that all files located in {your webapp folder}/js/ will be automatically mapped to the path with prefix /js/ (and the same for css).
Using such configuration you will be able to load your js and css files in the following way:
<link rel="stylesheet" href="css/main.css">
<script src="js/util.js"></script>
Spring Configuration Example
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.
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;
Trying to configure spring 3 MVC, here is what I did so far:
I added all the spring 3.0 libraries to my netbeans project.
My web.xml is:
<?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">
<servlet>
<servlet-name>WebApplication1</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>WebApplication1</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Next I created a WebAppliation1-servlet.xml, also in my /web-inf folder:
<?xml version="1.0" encoding="UTF-8"?>
<!--
- DispatcherServlet application context for PetClinic's web tier.
-->
<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"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">
<!--
- The controllers are autodetected POJOs labeled with the #Controller annotation.
-->
<context:component-scan base-package="org.springframework.Hi"/>
<!--
- The form-based controllers within this application provide #RequestMapping
- annotations at the type level for path mapping URLs and #RequestMapping
- at the method level for request type mappings (e.g., GET and POST).
- In contrast, ClinicController - which is not form-based - provides
- #RequestMapping only at the method level for path mapping URLs.
-
- DefaultAnnotationHandlerMapping is driven by these annotations and is
- enabled by default with Java 5+.
-->
<!--
- This bean resolves specific types of exceptions to corresponding logical
- view names for error views. The default behaviour of DispatcherServlet
- is to propagate all exceptions to the servlet container: this will happen
- here with all other types of exceptions.
-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.servlet.PageNotFound">pageNotFound</prop>
<prop key="org.springframework.dao.DataAccessException">dataAccessFailure</prop>
<prop key="org.springframework.transaction.TransactionException">dataAccessFailure</prop>
</props>
</property>
</bean>
<!--
- The BeanNameViewResolver is used to pick up the visits view name (below).
- It has the order property set to 2, which means that this will
- be the first view resolver to be used after the delegating content
- negotiating view resolver.
-->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="1"/>
<!--
- This bean configures the 'prefix' and 'suffix' properties of
- InternalResourceViewResolver, which resolves logical view names
- returned by Controllers. For example, a logical view name of "vets"
- will be mapped to "/WEB-INF/jsp/vets.jsp".
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" p:order="2"/>
</beans>
I then created a simple welcome.jsp in the folder /WEB-INF/jsp/welcome.jsp
I then created a package:
org.springframework.Hi
And I created a TestController.java file:
package org.springframework.Hi;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class TestController {
#RequestMapping("/")
public String welcomeHandler(){
return "welcome";
}
}
I wanted this to work w/o any file extensions, so I don't have to end my urls with xxx.htm etc.
So when I run the netbeans project I get the error:
type Status report
message Servlet WebApplication1 is not available
description The requested resource (Servlet WebApplication1 is not
available) is not available.
What exactly am I missing here?
Tomcat logs
Thanks for the feedback
My tomcat logs show this:
SEVERE: Servlet /WebApplication1 threw load() exception
java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:316)
at org.springframework.web.servlet.DispatcherServlet.<clinit>(DispatcherServlet.java:207)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
I'm asuming that error message you quoted was the error message the browser sees when it tries to access the application. This is because it didn't deploy properly.
You need to look through the web server startup logs, that will give you much more information as to why it didn't deploy.
edit: OK, that helps a lot... you need to add Apache Commons Logging to your classpath.
I used to encounter a similar problem... except it happened only when I try to run the Spring Web MVC app via the STS IDE (version 2.3.2). However, if I packaged as a WAR and deployed it to a running instance of tcServer or even Tomcat, the app worked just fine.
I ended up adding commons-logging and some other JARs to the server's launch configuration in STS IDE, in the User Entries section under the Classpath tab. This solved my problem. Why some JARs don't get added to the Java EE module dependency while running within STS, I don't still understand.
Hope this helps.