Spring MVC 3.0 404 error - model-view-controller

I'm trying to build an application using Spring MVC 3.0 within Eclipse using the Dynamic Web Project. I'm able to get to the initial page, but I can not navigate to any other pages from there w/out getting a 404 error and I'm not hitting any of my breakpoints in the controller class. Please let me know if there's something I'm missing. Thanks!
applicationContext.xml 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: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">
<!-- Activates various annotations to be detected in bean classes -->
<context:annotation-config />
<!-- Scans the classpath for annotated components that will be auto-registered
as Spring beans. For example #Controller and #Service. Make sure to set the
correct base-package -->
<context:component-scan base-package="src" />
<!-- Configures the annotation-driven Spring MVC Controller programming
model. Note that, with Spring 3.0, this tag works in Servlet MVC only! -->
<mvc:annotation-driven />
<!-- Load Hibernate related configuration -->
<import resource="hibernate-context.xml" />
</beans>
spring-servlet.xml Code:
<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation=" http://www.springframework.org/schema/beans
...
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans">
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<!-- Declare a view resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
web.xml Code:
<?xml version="1.0" encoding="UTF-8"?>
<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">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/SpringHibernateExample/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/jsp/personspage.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
MainController.java Code:
package controller;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import service.PersonService;
import domain.Person;
/**
* Handles and retrieves person request
*/
#Controller
#RequestMapping("/main")
public class MainController {
protected static Logger logger = Logger.getLogger("controller");
#Resource(name = "personService")
private PersonService personService;
/**
* Handles and retrieves all persons and show it in a JSP page
*
* #return the name of the JSP page
*/
#RequestMapping(value = "/persons", method = RequestMethod.GET)
public String getPersons(Model model) {
logger.debug("Received request to show all persons");
// Retrieve all persons by delegating the call to PersonService
List<Person> persons = personService.getAll();
// Attach persons to the Model
model.addAttribute("persons", persons);
// This will resolve to /WEB-INF/jsp/personspage.jsp
return "personspage";
}
/**
* Retrieves the add page
*
* #return the name of the JSP page
*/
#RequestMapping(value = "/persons/add", method = RequestMethod.GET)
public String getAdd(Model model) {
logger.debug("Received request to show add page");
// Create new Person and add to model
// This is the formBackingOBject
model.addAttribute("personAttribute", new Person());
// This will resolve to /WEB-INF/jsp/addpage.jsp
return "addpage";
}
/**
* Adds a new person by delegating the processing to PersonService. Displays
* a confirmation JSP page
*
* #return the name of the JSP page
*/
#RequestMapping(value = "/persons/add", method = RequestMethod.POST)
public String add(#ModelAttribute("personAttribute") Person person) {
logger.debug("Received request to add new person");
// The "personAttribute" model has been passed to the controller from
// the JSP
// We use the name "personAttribute" because the JSP uses that name
// Call PersonService to do the actual adding
personService.add(person);
// This will resolve to /WEB-INF/jsp/addedpage.jsp
return "addedpage";
}
/**
* Deletes an existing person by delegating the processing to PersonService.
* Displays a confirmation JSP page
*
* #return the name of the JSP page
*/
#RequestMapping(value = "/persons/delete", method = RequestMethod.GET)
public String delete(
#RequestParam(value = "id", required = true) Integer id, Model model) {
logger.debug("Received request to delete existing person");
// Call PersonService to do the actual deleting
personService.delete(id);
// Add id reference to Model
model.addAttribute("id", id);
// This will resolve to /WEB-INF/jsp/deletedpage.jsp
return "deletedpage";
}
/**
* Retrieves the edit page
*
* #return the name of the JSP page
*/
#RequestMapping(value = "/persons/edit", method = RequestMethod.GET)
public String getEdit(
#RequestParam(value = "id", required = true) Integer id, Model model) {
logger.debug("Received request to show edit page");
// Retrieve existing Person and add to model
// This is the formBackingOBject
model.addAttribute("personAttribute", personService.get(id));
// This will resolve to /WEB-INF/jsp/editpage.jsp
return "editpage";
}
/**
* Edits an existing person by delegating the processing to PersonService.
* Displays a confirmation JSP page
*
* #return the name of the JSP page
*/
#RequestMapping(value = "/persons/edit", method = RequestMethod.POST)
public String saveEdit(#ModelAttribute("personAttribute") Person person,
#RequestParam(value = "id", required = true) Integer id, Model model) {
logger.debug("Received request to update person");
// The "personAttribute" model has been passed to the controller from
// the JSP
// We use the name "personAttribute" because the JSP uses that name
// We manually assign the id because we disabled it in the JSP page
// When a field is disabled it will not be included in the
// ModelAttribute
person.setId(id);
// Delegate to PersonService for editing
personService.edit(person);
// Add id reference to Model
model.addAttribute("id", id);
// This will resolve to /WEB-INF/jsp/editedpage.jsp
return "editedpage";
}
}
personspage.jsp Code:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>People Page</title>
</head>
<body>
<h1>Persons</h1>
<c:url var="addUrl" value="/main/persons/add" />
<table style="border: 1px solid; width: 500px; text-align:center">
<thead style="background:#fcf">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Money</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<c:forEach items="${persons}" var="person">
<c:url var="editUrl" value="/persons/edit?id=${person.id}" />
<c:url var="deleteUrl" value="/persons/delete?id=${person.id}" />
<tr>
<td><c:out value="${person.firstName}" /></td>
<td><c:out value="${person.lastName}" /></td>
<td><c:out value="${person.money}" /></td>
<td>Edit</td>
<td>Delete</td>
<td>Add</td>
</tr>
</c:forEach>
</tbody>
</table>
<c:if test="${empty persons}">
There are currently no persons in the list. Add a person.
</c:if>
</body>
</html>

Possibly this might be your issue:
<context:component-scan base-package="src" />
You are supposed to input your base package name for "base-package". eg
<context:component-scan base-package="com.stackoverflow.project" />
where "com.stackoverflow.project" is the package name you used in your controller.
eg: Controller Class:
package com.stackoverflow.project.controller
#Controller
public class DashboardController { ...
Hope that helps.

Related

Spring MVC http 500 error apache

Above is the directory hierarchy of my program
I am new to spring and learning MVC concepts I have written a program which takes input(Name) into a text box and prints Hello...'name'. Tha following is my directory structure and the various files I have created.
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" version="3.1">
<display-name>MVC_HelloWorld</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- default configuration -->
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.ap</url-pattern> <!-- this same extension should bbe used in form action -->
</servlet-mapping>
</web-app>
HelloWorld-servlet.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!-- default handler mapping -->
<!-- file should be created under web inf annd it's view resolver file -->
<!-- handler(Not rqd in case of default handler) -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<!-- controller configuration -->
<bean name="/HelloWorld.ap" class="controller.HelloController"> <!-- mapping url pattern to controller class using 'name' -->
<!-- view resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" vlaue="/"/> <!-- default location (prefix used foor rqd page locations) -->
|<property name="sufix" value=".jsp"/> <!-- sufix used forr rqd page extensions -->
</bean>
</bean>
</beans>
HelloController.java
package controller;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import com.sun.javafx.collections.MappingChange.Map;
public class HelloController implements Controller {
#Override
public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {
String name=req.getParameter("name");
Map m= new HashMap(); // creating output object
m.put("msg","Hello..."+name);
ModelAndView mav=new ModelAndView("success"+m);
return mav;
}
}
index.jsp
<h1> Hello World</h1>
<form action="./hello.ap">
NAME: <input type="text" name="name">
<input type="Submit" value="Say Hello">
</form>
success.jsp
${msg}
when I am running this code the index.jsp page is running properly bur upon further execution It shows Error 404.
what's wrong with the code..??
I am using Eclipse oxygen in that apache 8.5
Your servlet name in definition is HelloWorld
but in mapping servlet, is hello.
These names must be the same.
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.ap</url-pattern> <!-- this same extension should bbe used in form action -->
</servlet-mapping>
</web-app>
here you have used HelloWorld as the servlet name previously and you referring to that as hello later on which is not correct so please correct that just change the hello in servelt-mapping to HelloWorld and access the servlet as HelloWorld.ap it will work.

URL mapping is not working in web.xml in spring

Package name controller where WelcomeController is there
folder view in WEB-INF where view files are there means html and static jsp
In view welcome.jsp
In WebContent web.xml and welcome-servlet.xml are there
When I mapped / but when I changed the url-pattern then it's not working e.g. /user/* following url is working for only /
http://localhost:3000/SpringPractice/user/welcome
Error is
WARNING: No mapping found for HTTP request with URI
[/SpringPractice/user/welcome] in DispatcherServlet with name
'welcome'
it's working if I set the to /.
Even I checked the controller no error because if no mapping is found then it'd not work for / pattern.
WEB.XML
<servlet>
<servlet-name>welcome</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>welcome</servlet-name>
<url-pattern>/user/*</url-pattern>
</servlet-mapping>
WelcomeController.java
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class WelcomeController {
#RequestMapping(method=RequestMethod.GET,value="/user/welcome")
public String GET(ModelMap model){
//second is the message name
//3rd is the message
model.addAttribute("message","GET Method");
return "welcome"; //we'll always return the name of the view here welcome.jsp e.g. welcome
}
#RequestMapping(method=RequestMethod.POST,value="/user/welcome")
public String POST(ModelMap model){
model.addAttribute("message","POST Method");
return "welcome";
}
}
welcome-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"
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="controller" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/view/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Your web.xml needs to be modified if you want the servlet to map to SpringPractice as the root
Change your web.xml to look like this:
<servlet-mapping>
<servlet-name>welcome</servlet-name>
<url-pattern>/SpringPractice/*</url-pattern>
</servlet-mapping>
It's also possible you are using the wrong port. Tomcat (Which I am assuming you are using here) uses port 8080 by default.
The URL: http://localhost:8080/SpringPractice/user/welcome
Should now work just fine
The following is not needed, is just might be helpful
Also, you can use #RequestMapping on the class level if you wish.
#Controller
#RequstMapping(value="/user/welcome")
public class WelcomeController {
#RequestMapping(method=RequestMethod.GET, value="")
public String GET(ModelMap model){
//second is the message name
//3rd is the message
model.addAttribute("message","GET Method");
return "welcome"; //we'll always return the name of the view here welcome.jsp e.g. welcome
}
#RequestMapping(method=RequestMethod.POST, value="")
public String POST(ModelMap model){
model.addAttribute("message","POST Method");
return "welcome";
}
}
By adding RequestMapping(value="/user/welcome") to the top of your controller class all the mappings under it will use that as a base. It's nice if you know a certain controller will be handeling all requests from "www.MyCoolSite.com/user/welcome"
I hope this helps.

I am getting a 404 not found Error in Spring Application

I am not able to navigate to the next page search can you please tell me what am I doing wrong here.I am getting a 404 not found Error.
I am trying to assemble a code found in https://github.com/christophstrobl/spring-data-solr-showcase
SearchController.java
/*
* Copyright 2012 - 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.solr.showcase.product.web;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Path;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.solr.core.query.result.FacetFieldEntry;
import org.springframework.data.solr.core.query.result.FacetPage;
import org.springframework.data.solr.showcase.product.ProductService;
import org.springframework.data.solr.showcase.product.model.Product;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
#Path("/")
#Controller
#Component
#Scope("prototype")
public class SearchController {
private ProductService productService;
#RequestMapping("/search")
public String search(Model model, #RequestParam(value = "q", required = false) String query, #PageableDefault(
page = 0, size = ProductService.DEFAULT_PAGE_SIZE) Pageable pageable, HttpServletRequest request) {
model.addAttribute("page", productService.findByName(query, pageable));
model.addAttribute("pageable", pageable);
model.addAttribute("query", query);
return "search";
}
#ResponseBody
#RequestMapping(value = "/autocomplete", produces = "application/json")
public Set<String> autoComplete(Model model, #RequestParam("term") String query,
#PageableDefault(page = 0, size = 1) Pageable pageable) {
if (!StringUtils.hasText(query)) {
return Collections.emptySet();
}
FacetPage<Product> result = productService.autocompleteNameFragment(query, pageable);
Set<String> titles = new LinkedHashSet<String>();
for (Page<FacetFieldEntry> page : result.getFacetResultPages()) {
for (FacetFieldEntry entry : page) {
if (entry.getValue().contains(query)) { // we have to do this as we do not use terms vector or a string field
titles.add(entry.getValue());
}
}
}
return titles;
}
#Autowired
public void setProductService(ProductService productService) {
this.productService = productService;
}
}
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>Testing2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<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>
<!-- applies log4j configuration -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>org.springframework.data.solr.showcase.product.web</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false"%>
<html>
<head>
<title>spring-data-solr-showcase</title>
<link href="<c:url value="/resources/css/styles.css" />" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<c:url value="/resources/jquery/jquery-1.8.2.js" />"></script>
</head>
<body>
Welcome.<br />
Search Sample > goto
</body>
My applicationContext.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"
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="org.springframework.data.solr.showcase" />
</beans>

how does Spring know from the jsp what controller to use?

I have this in web.xml:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Dispatching handled by StaticFilter -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
I have this in 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:annotation-config/>
<!-- Activates scanning of #Repository -->
<context:component-scan base-package="com.pronto.mexp" />
<!-- View Resolver for JSPs -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="requestContextAttribute" value="rc"/>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
I have this in AlertsController:
#Controller
public class AlertsController {
protected final Log logger = LogFactory.getLog(getClass());
#Autowired
private AlertManager alertManager;
#RequestMapping("/alerts")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// display in view
logger.info("Returning alerts view");
List<Alert> alerts = alertManager.getAlerts();
request.setAttribute("alerts", alerts);
return new ModelAndView();
}
public void setAlertManager(AlertManager alertManager) {
this.alertManager = alertManager;
}
}
And I have this in alerts.jsp:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<h3>ALERTS</h3>
<table border="1">
<c:forEach var="alert" items="${alerts}">
<tr>
<td>${alert.hostname}</td>
<td>${alert.message}</td>
<td>${alert.program}</td>
<td><fmt:formatDate value="${alert.date}" dateStyle="medium"/></td>
</tr>
</c:forEach>
</table>
But when I start the app up and point my browser to localhost:8080/alerts.jsp, I get only the header "ALERTS" and nothing else. It's like Spring doesn't know to use the AlertsController. I know I'm leaving out some key config but I can't see it.
You're doing it opposite of what you're supposed to. It's not the JSP that knows which controller to use, but the Controller knows which view (JSP) to render. The controller is executed by it's url mapping, which is defined in the #RequestMapping attribute. When you access your JSP directly like that, you're not going through Spring at all. So try using the url http://localhost:8080/context/alerts instead, replacing context with the context path of the web application.
One line Answer : you are calling it in wrong way you have to call /alerts not alerts.jsp
but why you are getting this empty page, because you are calling jsp direct without setting values by controller, you are putting Jsp files under root
<property name="prefix" value="/"/>
so that it is accessible it is better to put it in WEB-INF to prevent direct access
<property name="prefix" value="/WEB-INF/jsps/"/>
My coworker pointed out my dispatcher-servlet.xml was also missing the mvc instruction to scan for annotations in my Controllers:
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven/>
So even when I pointed my browser at localhost:8080/alerts (since I have no context path configured), it was still failing. Once I added the mvc instruction, the controller was invoked, and the dynamic content was sent to the jsp.

Spring MVC HTTP 404 error

I learning SpringMVC so I am followed Spring 3.0 MVC Series from HERE.
As you can see, I completed Part1, Part2, and I am right now on Part3 where I am learning how to handle forms with Spring 3 MVC.
But I get this HTTP 404 eror, when I try to run my application. Project strucutre and this error you can see at image below.
How I can fix this?
ContactController.java code:
package net.viralpatel.spring3.controller;
import net.virtalpatel.spring3.form.Contact;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
#Controller
#SessionAttributes
public class ContactController {
#RequestMapping(value = "/addContact", method = RequestMethod.POST)
public String addContact(#ModelAttribute("contact")
Contact contact, BindingResult result) {
System.out.println("First Name:" + contact.getFirstname() +
"Last Name:" + contact.getLastname());
return "redirect:contacts.html";
}
#RequestMapping("/contacts")
public ModelAndView showContacts() {
return new ModelAndView("contact", "command", new Contact());
}}
spring-servlet.xml code:
<?xml version="1.0" encoding="UTF-8"?>
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" />
<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>
****index.jsp code:****
<jsp:forward page="contacts.html"></jsp:forward>
web.xml code:
<?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>
Just change contact to contacts
change
return new ModelAndView("contact", "command", new Contact());
to
return new ModelAndView("contacts", "command", new Contact());
The issue is in your forward it will check for the contact.jsp but actually you have contacts.jsp (you have suffix property as .jsp )
your index.jsp is forwarded to contacts.html.
But you spring configuration does not have mapping for /contacts.html, you have mapped /contacts instead.
You need to change the /contacts mapping to
#RequestMapping("/contacts.html")
public ModelAndView showContacts() {
return new ModelAndView("contact", "command", new Contact());
}
localhost:8080/Spring3MVC/index.jsp As you can see, I try first to open index.jsp and then redirect to contact.jsp – Zookey 44 mins ago
I think you have it mixed up. 1) There is a typo, you say contact.jsp but the file name is contacts.jsp (file name in eclipse)
2) Where is the contacts.html file ?
I would suggest, you first return to the jsp and see if you can get your controller to return the jsp after that try redirecting to the html file after you create one.

Resources