Spring MVC resource Mapping - java

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

Related

404 error displayed when Spring MVC basic web app is run

I am learning spring MVC. This is a basic code which I found online and trying to run locally. I have added all the dependencies but I am still getting this error:
The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Here is the code:
This is the landing page which contains the form. On submit, controller will be called.
index.jsp
<html>
<body>
<form action="hello">
UserName : <input type="text" name="name"/> <br><br>
Password : <input type="text" name="pass"/> <br><br>
<input type="submit" name="submit">
</form>
</body>
</html>
This is the maven xml which has the spring dependencies.
pom.xml
Added the below two dependencies:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
This is the controller. Login is successful when password is 'admin'.
HelloController.java
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HelloController {
#RequestMapping("/hello")
public String display(HttpServletRequest req,Model m)
{
//read the provided form data
String name=req.getParameter("name");
String pass=req.getParameter("pass");
if(pass.equals("admin"))
{
String msg="Hello "+ name;
//add a message to the model
m.addAttribute("message", msg);
return "viewpage";
}
else
{
String msg="Sorry "+ name+". You entered an incorrect password";
m.addAttribute("message", msg);
return "errorpage";
}
}
}
web.xml
<web-app>
<display-name>SpringMVC</display-name>
<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>/</url-pattern>
</servlet-mapping>
</web-app>
spring-servlet.xml
<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"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.javatpoint" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
viewpage.jsp
<html>
<body>
${message}
</body>
</html>
errorpage.jsp
<html>
<body>
${message}
<br><br>
<jsp:include page="/index.jsp"></jsp:include>
</body>
</html>
In your web.xml <context:component-scan base-package="com.javatpoint" />,but I don't see package com.javatpoint; in your HelloController.You need to create a package and put your contorller in it and set it up in web.xml.
Try to create com.javatpoint package and put your controller in it.
And you also set <property name="prefix" value="/WEB-INF/jsp/"></property> you need to put your viewpage.jsp and errorpage.jsp in /WEB-INF/jsp. I don't konw whether you create jsp directory in WEB-INF.
Sometimes controller can't find your jsp cause 404.
I create a project using your code,I work well.

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";
}
}
}

HTTP Status 404 - /EventTracker/greeting

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

resource in spring mvc

I know that there are other topics about adding resources(CSS, Javascript) in Spring MVC, but in my case that doesn't work. I have this error when adding: HTTP Status 404 The requested resource is not available.
mvc:resources mapping="/resources/**" location="/, classpath:/META-INF/web-resources/"
My application works properly until this point.
In my index.jsp I've got:
link type="text/css" rel="stylesheet" href="c:url value="/resources/css/test.css"
script type="text/javascript" src="c:url value="/resources/js/carousel.js"
I had a similar problem and I think I solved it by adding a default mapping in web.xml
<servlet-mapping>
<servlet-name>dispatherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Problem solved.
In DispatcherServlet I added :
<mvc:default-servlet-handler />
<mvc:annotation-driven />
At this point 'HTTP Status 404 The requested resource is not available.' has disappeared, but my resources were not available at all. So i found another way to solve the problem, configuring the base tag like
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath %>">
<title>index</title>
<link href="resources/css/test.css" rel="stylesheet" type="text/css" />
</head>
...
And now it works properly.

JSP Expression Language Error

I have created a dynamic web module project usig STS and Spring MVC. The problem is I have add a string into a Model but it cannot be display on the JSP page using EL.
May I know what wrong with it?
Below is the details:
JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC</title>
</head>
<body>
Home
<br />
<c:out value="${message}" />
</body>
</html>
Web.xml
<?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_3_0.xsd" version="3.0">
MVC Controller:
#Controller
public class HomeController {
public HomeController() {
super();
}
#RequestMapping(value="/home", method=RequestMethod.GET)
public ModelAndView showHomePage() {
// View Name - Model Name - Model Data
return new ModelAndView("home", "message", "Hello Spring MVC");
}
}
Dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- http://www.jpalace.org/docs/tutorials/spring/mvc_10.html -->
<!-- Context Scan -->
<context:component-scan base-package="com.peter.controller"/>
<!-- Handler Mapping -->
<bean id="handlerMapping" class="org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>
<!-- Handler Adapter - AnnotationMethodHandlerAdapter -->
<!-- Invoke Handler Method -->
<bean id="handlerAdapter" class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter">
</bean>
<!-- Pre/Post Handler Interceptor -->
<!--
Implement HandlerInterceptor
Declare HandlerInterceptor inside DefaultAnnotationHandlerMapping property or
globally inside <mvc:interceptors>
Need configure Filter object inside web.xml
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<bean class="pckg.MyInterceptor1"/>
<bean class="pckg.MyInterceptor2"/>
</list>
</property>
</bean>
<mvc:interceptors>
<bean class="pckg.MyInterceptor1"/>
<bean class="pckg.MyInterceptor2"/>
</mvc:interceptors>
-->
<!-- View Resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- Exception Resolver -->
<!-- Register Interceptor, Message Resource, Bean validation support, Message conversion and field formatting -->
<mvc:annotation-driven />
</beans>
I have JSTL.jar in my build path. There is warning message about the The tag handler class for "c:out" (org.apache.taglibs.standard.tag.rt.core.OutTag) was not found on the Java Build Path
Please help.
Thanks.
Download jstl-1.2.jar from the maven repo (http://repo1.maven.org/maven2/javax/servlet/jstl/1.2/).
Ensure that
the jar is available in WEB-INF\lib folder of your web application.
I would like to view your viewResolver configuration. Are you able to view the home page?? or there is 404 error?
If home.jsp is displaying properly then according to me the problem is in your jsp.
Look at the first line of the jsp where you have defined the page directive.
In that declaration remove the attribute isELIgnored="false" it is bydefault false everytime. So no need to define it explicitely.
I think if you remove that attribute. Your ${message} would display correctly.
Hope this helps you.
Cheers.

Categories

Resources