I'm new in Spring MVC and try to make an exercise, like in the example. I have index.jsp and view.jsp. Index.jsp is loaded well, but when I try load view.jsp, it teturns empty field and logger doesnt show me any mistake. I use IntellijIDEA. Below all classes and files, let me know, if i have to give other info. Thanks.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.form</url-pattern>
</servlet-mapping>
dispatcher-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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
">
<context:component-scan base-package="controllers"/>
<bean id="vievResolver" class ="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="HttpGatewayInit" class ="controllers.HttpGatewayInit">
</bean>
<bean name="shape" class="shapes.Rectangle">
<constructor-arg index="0" value ="12" />
<constructor-arg index="1" value ="2" />
</bean>
<bean name="circle" class="shapes.Circle">
<constructor-arg index="0" value ="8" />
</bean>
<bean name="rectanglepoint" class="shapes.RectanglePoint">
<constructor-arg index="0" ref ="leftend" />
<constructor-arg index="1" ref ="rightend" />
</bean>
<bean name="leftend" class="shapes.Point">
<constructor-arg index="0" value ="4" />
<constructor-arg index="1" value ="3" />
</bean>
<bean name="rightend" class="shapes.Point">
<property name="x" value ="12" />
<property name="y" value ="8" />
</bean>
Controller (System.out.println(shape.square()) shows me, that mapping do work)
package controllers;
import org.springframework.asm.Attribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.portlet.ModelAndView;
import shapes.Shape;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
#Controller
public class MainController {
#Autowired
#Qualifier("shape")
private Shape shape;
public MainController(){
}
#RequestMapping (value="/shape.form",method = RequestMethod.GET)
public ModelAndView main(){
/*class HttpGatewayInit implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
}
}*/
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("view");
modelAndView.addObject("message", shape.square());
System.out.println(shape.square());
return modelAndView;
}
}
index.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
Next page
</body>
</html>
view.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>View</title>
</head>
<body>
<span>${message}</span>
</body>
</html>
Please check import
import org.springframework.web.portlet.ModelAndView;
I tried changing it to import org.springframework.web.servlet.ModelAndView;
and it worked for me.
Related
I have NetBeans Spring MVC project with Maven.But I got the following error: HTTP Status 404 - Not Found. How can I avoid this error?
Hierarchy:
-FinalWebStore
-Web Pages
-WEB-INF
+views
web.xml
mvc-dispatcher-servlet.xml
-Source Packages
+com.karans.finalwebstore.controllers
+com.karans.finalwebstore.daoimps
+com.karans.finalwebstore.daos
+com.karans.finalwebstore.models
+Dependecies
...
Here are my files:
web.xml:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring Web MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>
mvc-dispatcher-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"
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-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<bean name="/login"
class="com.karans.finalwebstore.controllers.UserController" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="ds"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/webstore" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="ProductDAOimpl" class="com.karans.finalwebstore.daoimps.ProductDAOimp">
<property name="template" ref="jt"></property>
</bean>
<bean id="UserDAOimpl" class="com.karans.finalwebstore.daoimps.UserDAOimp">
<property name="template" ref="jt"></property>
</bean>
<bean id="CartDAOimpl" class="com.karans.finalwebstore.daoimps.CartDAOimp">
<property name="template" ref="jt"></property>
</bean>
<bean id="UserController" class="com.karans.finalwebstore.controllers.UserController">
<property name="userdaoimp" ref="UserDAOimpl"></property>
</bean>
</beans>
UserController.java:
package com.karans.finalwebstore.controllers;
import com.karans.finalwebstore.daoimps.UserDAOimp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class UserController {
#Autowired
UserDAOimp userdaoimp;
public void setUserdaoimp(UserDAOimp userdaoimp) {
this.userdaoimp = userdaoimp;
}
public String login(){
return "login";
}
}
login.jsp:
<%--
Document : login
Created on : Jul 15, 2017, 2:57:13 PM
Author : raziyeh
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LOG IN PAGE</title>
</head>
<body>
<h1>Hello World Taze avvaleshe!</h1>
</body>
</html>
And I think other files are not important.
Change your login function as
#RequestMapping(value = "/")
public String login(){
return "login";
}
Also change the web.xml file in the below portion :
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
You need to delete the below line from mvc-dispatcher-servlet.xml
<bean name="/login"
class="com.karans.finalwebstore.controllers.UserController" />
Also, make sure that login.jsp file contains under the /WEB-INF/views/ folder.
Try the following:
Add the Spring MVC namespace to your mvc-dispatch-servlet.xml file xmlns:mvc="http://www.springframework.org/schema/mvc". You will need to update the xsi:schemaLocation as well with this "http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"
Second add <mvc:annotation-driven /> to the file. If I recall correctly, this enables processing of #RequestMapping annotations.
Third, remove the bean declared with the name "/login". It is the same type as the UserController declared at the bottom of the file.
When I add an autowire into my controller I get the following exception:
No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I am not sure how to solve this any suggestions please?
I was wondering whether or not it was something to do with my component scan in the application context?
My controller:
package com.projectShaun.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.projectShaun.service.AccountService;
#Controller
public class HomeController {
#Autowired
AccountService accountService;
#RequestMapping("/")
public ModelAndView welcome() {
ModelAndView modelAndView = new ModelAndView("welcome");
modelAndView.addObject("greeting", "Welcome to projectShaun!");
return modelAndView;
}
}
ApplicationContext.xml:
<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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd" >
<context:component-scan base-package="com.projectShaun" />
<tx:annotation-driven/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/projectshaun" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>com.projectShaun.model.Account</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory">
</bean>
</beans>
DefaultServlet-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"
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-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.projectShaun" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
AccountService:
package com.projectShaun.service;
import com.projectShaun.model.Account;
public interface AccountService {
void persistAccount(Account account);
}
HomeController:
package com.projectShaun.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.projectShaun.service.AccountService;
#Controller
public class HomeController {
#Autowired
AccountService accountService;
#RequestMapping("/")
public ModelAndView welcome() {
ModelAndView modelAndView = new ModelAndView("welcome");
modelAndView.addObject("greeting", "Welcome to projectShaun!");
return modelAndView;
}
}
accountServiceImpl:
package com.projectShaun.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.projectShaun.dao.AccountDao;
import com.projectShaun.model.Account;
#Service("accountService")
#Transactional
public class AccountServiceImpl implements AccountService {
#Autowired
private AccountDao accountDao;
public void persistAccount(Account account) {
accountDao.persistAccount(account);
}
}
Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
<servlet>
<servlet-name>DefaultServlet</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DefaultServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
You have lots of xml file that creating lots of confusion.First configure the simple mvc then add security and filter .So for simple mvc your web.xml be looks like below
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
applicationContext.xml
<context:component-scan base-package="com.projectShaun" />
<mvc:annotation-driven />
dispatcher-servlet.xml
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
I've the following error. I don't understand why.
[INFO] javax.servlet.UnavailableException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping': Initialization of bean failed; nested exception is java.lang.IllegalStateException: Cannot map handler [mapController] to URL path [/map.jsp]: There is already handler [com.application.myGoogleAppEngine.controller.MapController#978068] mapped.
Do you have any solutions ?
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">
<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>*.jsp</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:mvc="http://www.springframework.org/schema/mvc"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.application.myGoogleAppEngine.controller" />
<bean id="helloBean" class="com.application.myGoogleAppEngine.HelloWorld">
<property name="name" value="Mkyong" />
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="fr" />
</bean>
<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="language" />
</bean>
<bean class="org.springframework.context.support.ReloadableResourceBundleMessageSource" id="messageSource">
<property value="classpath:MessageBundle" name="basename"/>
<property value="UTF-8" name="defaultEncoding"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property value="org.springframework.web.servlet.view.JstlView" name="viewClass"/>
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
IndexController.java
package com.application.myGoogleAppEngine.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
#RequestMapping("/index.jsp")
public class IndexController {
#RequestMapping(method=RequestMethod.GET)
public ModelAndView initForm(HttpServletResponse res){
try{
PrintWriter out = res.getWriter();
out.println("Hello, world!");
out.close();
}
catch(IOException ex){}
return null;
//return new ModelAndView("address");
}
}
MapController.java:
package com.application.myGoogleAppEngine.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
#RequestMapping("/map.jsp")
public class MapController {
#RequestMapping(method=RequestMethod.GET)
public ModelAndView initForm(HttpServletResponse res){
try{
PrintWriter out = res.getWriter();
out.println("Hello, world!");
out.close();
}
catch(IOException ex){}
return null;
//return new ModelAndView("address");
}
}
Try it with the following changes
In your XML, add annotation-driven element:
<context:component-scan base-package="com.application.myGoogleAppEngine.controller" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/pages/" />
<property name="suffix" value=".jsp" />
</bean>
In web.xml, change the url pattern
<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>
So, you can use your Controllers like that:
#Controller
#RequestMapping("/map")
public class MapController {
...
}
I have a problem with providing static content using SpringMVC 3.2.1. (Tomcat 7)
So please have a look at the following configurations:
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_3_0.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>CrimeMapping IP5</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FirstController</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FirstController</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
FirstController-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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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">
<context:component-scan
base-package="ch.fhnw.ip5.cm.controller" />
<mvc:annotation-driven />
<mvc:resources location="/WEB-INF/, classpath:/META-INF/web-resources/" mapping="/resources/**"/>
<!-- Allows for mapping the DispatcherServlet to "/" by forwarding
static resource requests to the container's default Servlet -->
<mvc:default-servlet-handler/>
<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/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
MapController.java:
package ch.fhnw.ip5.cm.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
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 MapController {
#RequestMapping(value="/show/map/lat/{lat}/lng/{lng}/zoom/{zoom}", method=RequestMethod.GET)
public ModelAndView showMapDetail(#PathVariable("lat") double lat,
#PathVariable("lng") double lng, #PathVariable("zoom") double zoom, HttpServletRequest request ) {
request.getPathInfo();
double[] message = {lat,lng,zoom};
return new ModelAndView("map", "message", message);
}
So, I am able to show static content like images oder .js files.
But the path I use in .jsp files looks like:
<link rel="stylesheet" type="text/css" href="../../../../../../../../../CM/resources/javascript/leaflet/leaflet.css" />
<script type="text/javascript" src="../../../../../../../../../CM/resources/javascript/leaflet/leaflet.js"></script>
I would like to use
according to my
<mvc:resources location="/WEB-INF/, classpath:/META-INF/web-resources/" mapping="/resources/**"/>
entry in FirstController-servlet.java file.
Thank you for your help.
Best regards.
There are a few issues that I see here:
.1. The contents of WEB-INF should not be exposed using <mvc:resources tag, the content should be protected. Instead create a resources subfolder under WEB-INF resources or directly under the webapp and expose that alone for static content:
<mvc:resources location="/WEB-INF/resources/, /resources/, classpath:META-INF/resources/" mapping="/resources/**"/>
.2. Now, in order to refer to the resources, it is better to refer to them in an absolute way, this is typically using <spring:url/> or using jstl <c:url tags, for eg.
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<spring:url value="/resources/image.png" var="myImage" />
<img src="${myImage}"/>
How to use static resources in spring mvc? I just want to insert some images in jsp. In which place I must locate my resources? Last time I used to add mvc:recources in servlet-context, but it shows me few errors with mapping.
I'm still in trouble. I've made another question. Please, HALP.
https://stackoverflow.com/questions/18020129/troubles-with-static-resources-and-mvcresources
My config:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="net.babobka.blog" />
<import resource="../../db/db-config.xml" />
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.tiles2.TilesView" />
</bean>
</beans>
My jsp:
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<strong><h1>
Blog
</h1></strong>
<p>
<small>With Spring MVC</small><img src='<c:url value="/static/img/logo.gif"/>' />
And part of controller:
import org.springframework.stereotype.Controller;
import net.babobka.blog.domain.Content;
import net.babobka.blog.service.ContentService;
import net.babobka.blog.domain.News;
import net.babobka.blog.service.NewsService;
import net.babobka.blog.domain.Tags;
import net.babobka.blog.service.TagsService;
import java.util.Map;
import net.babobka.blog.form.SearchForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class HomeController {
#Autowired
private ContentService contentService;
#Autowired
private NewsService newsService;
#Autowired
private TagsService tagsService;
long HM = 3;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String listContacts(Map<String, Object> map,#ModelAttribute("search") SearchForm query, BindingResult result) {
long nums = newsService.getNumRows();
map.put("old", HM);
map.put("news", new News());
map.put("nums", nums);
map.put("newsList", newsService.getSomeNews(0, HM));
return "content";
}
#RequestMapping(value = "/about", method = RequestMethod.GET)
public String getAboutPage(Map<String, Object> map,#ModelAttribute("search") SearchForm query, BindingResult result) {
map.put("news", new News());
map.put("newsList", newsService.getAboutPage());
return "about";
}
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">
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/root-context.xml
/WEB-INF/spring/application-security.xml
</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<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/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
If you are getting 404 error means requested resource is not applicable it means you have mapping error,After this mapping there need to check also controller-servlet.xml mapping also. If you will get error provide your code.
Try this
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Controller-servlet.xml
<bean id="urlMapping" class="org.springframework.Handler.SimpleHandlerMapping">
<property name="mapping">
<props><prop key="app.do">hello</prop></props></property></bean>
Envious is right , that link contain an example you can see that. By the way , you can modify your code from the below snippet of code
<?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:mvc="http://www.springframework.org/schema/mvc"
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.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:annotation-config />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<context:component-scan base-package="com.ashish.stack.ques.controller"
annotation-config="true"
scope-resolver="org.springframework.context.annotation.AnnotationScopeMetadataResolver">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
</beans>
tiles.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
"http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
<tiles-definitions>
<definition name="base.definition"
template="/WEB-INF/jsp/layout.jsp">
<put-attribute name="title" value="" />
<put-attribute name="header" value="/WEB-INF/jsp/header.jsp" />
<put-attribute name="menu" value="/WEB-INF/jsp/menu.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/WEB-INF/jsp/footer.jsp" />
</definition>
<definition name="show" extends="base.definition">
<put-attribute name="title" value="Show Image" />
<put-attribute name="body" value="/WEB-INF/jsp/show.jsp" />
</definition>
</tiles-definitions>
show.jsp
<%# 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"%>
<!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>
Image:
<img src='<c:url value="/static/image/radar-icon.png"/>' />
</body>
</html>
controller
package com.ashish.stack.ques.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class IndexController {
#RequestMapping(value="/show.do",method=RequestMethod.GET)
public void index(){
System.out.println("Got an image");
}
}
I have modified my code , please follow the code and let me know , you get your solution or not :)