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.
Related
I am trying to configure a project using spring on intellij but I am still showing error 404.The configuration files come from the udemy course Any suggestion would be helpful.
Tomcat version: 9.0.7
Project structure:
Project structure
:
Controllers class:
package com.Controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HelloController {
#RequestMapping("/")
public String showPage(){
return "main";
}
}
main.jsp:
<!DOCTYPE html>
<html>
<body>
<h2>Works</h2>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>test2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--suppress XmlPathReference -->
<param-value>\WEB-INF\spring-mvc-demo-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-mvc-demo-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:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="com.Controllers" />
<context:component-scan base-package="com" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/webservice?useSSL=false" />
<property name="user" value="root" />
<property name="password" value="root" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.Entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
spring-mvc-demo-servlet.xml: continued
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
<!-- Add support for reading web resources: css, images, js, etc ... -->
<mvc:resources location="/web/resources/" mapping="/resources/**"></mvc:resources>
Try adding #RequestMapping("/") under #Controller like this:
#Controller
#RequestMapping("/")
public class HelloController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String showPage(){
return "main";
}
}
I've had a similar problem as you. It was beacuse of the project structure.
Can you please check your main.jsp hierarchy.
It must be under the
../WEB-INF/view/main.jsp
and you must call it like
http://localhost:portNumber/yourProjectName/
(E.g.: http://localhost:8080/1-SpringMVC-Demo/ )
I am new in SpringMVC and trying to execute simple hello world program. However, when run this in my browser (http://localhost:8080/FirstspringMVCwithannotation/welcome) I got HTTP Status- 404 Error. Here, is the code:
HelloController.java
package com.example;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.ModelAndView;
#Controller
public class HelloController {
#RequestMapping("/welcome")
public ModelAndView helloWorld(){
ModelAndView model=new ModelAndView("HelloPage");
model.addObject("msg","hello world");
return model;
}
}
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" 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>FirstspringMVCwithannotation</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<context:component-scan base-package="com.example" />
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
HelloPage.jsp
<html>
<body>
<h1>
First Spring MVC Application Demo
</h1>
<h2>
${msg}
</h2>
</body>
</html>
Here is my project structure and I added all spring jar files under lib folder
I tried to see other solution but that does not solved my problem..can anyone help me please, why i get HTTP Status- 404 Error? Thanks in advance
You received HTTP 404 because your dispatcher controller can't find you view.
Your view is under lib folder, which is under WEB-INF folder.
All you need to do is the reconfigure you view resolver, instead of what you wrote:
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
write it like this: configure your view resolver to extract views from lib folder
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/lib/" />
<property name="suffix" value=".jsp" />
</bean>
One more thing, I would recommend that you place your jsp files under views folder under WEB-INF and not under lib folder.
lib under WEB-INF is a folder dedicated to 3rd party libraries and jars.
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.
I am just starting with spring so I started with a SpringMVC on Heroku. By choosing the Spring MVC Template in Eclipse I got a very basic Application. Now I am trying to modify this.
However if I create another .jsp and I visit the URL given in the Controller I get an 404, that's pretty clear, because I never mapped the Controller to the .jsp. But how should I do this?
Here is everything I changed (Even if I'm not sure that you will need it):
The Controller:
#Controller
public class BookingController {
#Autowired
BookingService bookingService;
#RequestMapping("/AvailableBikes")
public String getAvailableBikes(Model model){
// TOOD: Fix Date
int availableBookings = bookingService.getAvailableBookings(Calendar.getInstance().getTime());
model.addAttribute("NumAvailableBikes", Integer.toString(availableBookings));
return "NumAvailableBikes";
}
}
The Entity:
#Entity
public class Booking {
#Id
#GeneratedValue
private Integer id;
// Lots of getters setters an attributes ...
}
The Service:
#Service
public class BookingServiceImpl implements BookingService {
#Override
public void addBooking(Booking booking) {
// TODO Auto-generated method stub
}
#Override
public int getAvailableBookings(Date bookingDay) {
// TODO Auto-generated method stub
return 12;
}
#Override
public void removeBooking(Booking booking) {
// TODO Auto-generated method stub
}
}
booking.jsp:
<!doctype html>
<%#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"%>
<html>
<head>
<meta charset="utf-8">
<title>Spring MVC and Hibernate Template</title>
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" rel="stylesheet">
<link href="http://twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css" rel="stylesheet">
</head>
<body>
Test!
<h2>${NumAvailableBikes}</h2>
</body>
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_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring-Hibernate-Template</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>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/booking/*</url-pattern>
</servlet-mapping>
</web-app>
applicationContext.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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config />
<context:component-scan base-package="org.stuttgart.fahrrad" />
<mvc:annotation-driven/>
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource"/>
</bean>
<beans profile="default">
<jdbc:embedded-database id="dataSource"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
</beans>
<beans profile="prod">
<bean class="java.net.URI" id="dbUrl">
<constructor-arg value="#{systemEnvironment['DATABASE_URL']}"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="#{ 'jdbc:postgresql://' + #dbUrl.getHost() + #dbUrl.getPath() }"/>
<property name="username" value="#{ #dbUrl.getUserInfo().split(':')[0] }"/>
<property name="password" value="#{ #dbUrl.getUserInfo().split(':')[1] }"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- change this to 'verify' before running as a production app -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
</beans>
</beans>
return "NumAvailableBikes"; should be changed to return "booking";
First consider how your dispatcher servlet is configured. Currently it is mapped to the following url pattern:
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/booking/*</url-pattern>
</servlet-mapping>
This means that only urls which contain the booking directory directly after the context root will be mapped. So a url like `contextroot/AvailableBikes' will never get picked up and processed by the dispatcher. I would recommend changing your url pattern to:
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
This mapping serves as almost a catch all mapping. It will match all urls which are not mapped to another servlet. Please note: it will also create the need for you to setup configuration to map static resources such as css and js files. This is explained in the Spring documentation.
Once you have made this change I think you should be able to hit the Controller with a URL like rootcontext/AvailableBikes. Setup a debug point in the controller to confirm. Also note that you will not use a url containing a direct path to the .jsp file but the path specified in the request mapping. Your jsp file should be available # webcontent directory/WEB-INF/jsp/NumAvailableBikes.jsp.
In order to display the booking.jsp which should be available # webcontent dir/WEB-INF/jsp/booking.jsp the controller must be modified to return the String booking.
#RequestMapping("/AvailableBikes")
public String getAvailableBikes(Model model){
// TOOD: Fix Date
int availableBookings = bookingService.getAvailableBookings(Calendar.getInstance().getTime());
model.addAttribute("NumAvailableBikes", Integer.toString(availableBookings));
return "booking";
}
I have an interesting problem with Spring 3.1.0. JSP pages are not having their EL evaluated. I've debugged the view resolution process and JstlView is being used and the Jstl libraries are detected. However, my JSP pages just render things like
<%="Hello World!"%>
There are lots of references on here about this problem, none of which have worked for me.
Script tags not rendered in JSP page (using Spring + Tiles + JSPX)
Spring and JSP EL not being processed
From the top, here's my config;
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="2.5">
<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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
</web-app>
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"
xmlns:aop="http://www.springframework.org/schema/aop" 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/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!--
https://stackoverflow.com/questions/3652090/difference-between-applicationcontext-and-spring-servlet-xml-in-spring
-->
</beans>
applicationContext.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"
xmlns:aop="http://www.springframework.org/schema/aop" 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/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.csc.fs.emea" />
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<mvc:resources mapping="/static/**" location="/" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver" p:order="1" />
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" p:order="2" p:defaultErrorView="sorry" />
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/freemarker/" />
<property name="freemarkerSettings">
<props>
<prop key="default_encoding">UTF-8</prop>
<prop key="output_encoding">UTF-8</prop>
<prop key="auto_include">macros.ftl</prop>
<prop key="auto_import">spring.ftl as spring</prop>
<prop key="template_update_delay">${freemarker.template.update.delay}</prop>
</props>
</property>
<property name="freemarkerVariables">
<props>
<prop key="googleAnalyticsId">${google.analytics.id}</prop>
</props>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
<property name="contentType" value="text/html;charset=UTF-8"></property>
</bean>
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="suffix" value=".html" />
<property name="contentType" value="text/html;charset=UTF-8"></property>
<property name="exposeSpringMacroHelpers" value="true" />
</bean>
</list>
</property>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
</bean>
<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver"></bean>
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
</beans>
I'm using the ContentNegotiatingViewResolver as I have some freemarker stuff and REST in there too.
Controller
#RequestMapping("/")
#Controller
public class RootResource extends AbstractResource {
...abridged...
#RequestMapping(value="/jsp", method = RequestMethod.GET, produces = "text/html")
public String getJSP(final Model m) {
return "example";
}
}
example.jsp
<%# page isScriptingEnabled="true" isELIgnored="false" %>
<html>
<head>
<title>Hello World JSP Page.</title>
</head>
<body>
<font size="10"><%="Hello World!"%></font>
</body>
</html>
I return "example" as the view name from my controller and you can see in the logs it resolves to the correct WEB-INF/jsp/example.jsp
22:35:13,049 DEBUG [1168657208#qtp-1342126426-0] [org.springframework.web.servlet.view.ContentNegotiatingViewResolver] Returning [org.springframework.web.servlet.view.JstlView: name 'example'; URL [/WEB-INF/jsp/example.jsp]] based on requested media type 'text/html'
22:35:13,050 TRACE [1168657208#qtp-1342126426-0] [org.springframework.web.servlet.view.JstlView] Rendering view with name 'example' with model {} and static attributes {}
22:35:13,054 DEBUG [1168657208#qtp-1342126426-0] [org.springframework.web.servlet.view.JstlView] Forwarding to resource [/WEB-INF/jsp/example.jsp] in InternalResourceView 'example'
So everything looks ok, it's just that the JSP page is never evaluated correctly.
example.jsp looks like this
<%# page isScriptingEnabled="true" isELIgnored="false" %> <%="Hello World!"%>
I'm using the Maven jetty 6 plugin to run the webapp.
I'm sure I'm missing something simple, it's probably one of those "looked at it for too long" issues.
Thanks for any pointers you can give.
Update 1 - I've just changed the Spring servlet mapping from /* to /spring/* and now it works. So there's some detail around the spring servlet being mapped to /* that I've missed.
Absolutely a case of "looked at it for too long".
The spring servlet needs to be the default servlet. ie mapped to / and not /*.
<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>