Spring MVC Error 404 Bad Request Kotlin - spring

I am using Kotlin for developing Spring MVC Application.
I have a simple form which when i submit, I am getting Error 404 bad Request. I am using Jetty server and Intellij Community Edition.I tried debugging but since i have never debugged a web application, it wasnt that helpful.
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>frontDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>frontDispatcher</servlet-name>
<url-pattern>/springkotlinmvc/*</url-pattern>
</servlet-mapping>
</web-app>
frontDispatcher-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-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:annotation-config/>
<mvc:annotation-driven/>
<context:component-scan base-package="org.manya.kotlin"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
DataClasses.kt
package org.manya.kotlin
data class Address (val city : String, val state : String)
data class Student ( val name : String , val age : Int, val address : Address)
StudentController.kt
package org.manya.kotlin
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.*
import org.springframework.web.servlet.ModelAndView
#Controller
#RequestMapping("/student")
class StudentController
{
//#GetMapping("/student/form")
#GetMapping("form")
fun studentForm() : ModelAndView{
println("called from studentForm()")
return ModelAndView("form")
}
//#PostMapping("springkotlinmvc/student/submitted")
//#RequestMapping(value = "/student/submitted" , method = arrayOf(RequestMethod.POST))
//#RequestMapping("/submitted")
#PostMapping("/submitted")
fun submitted(#ModelAttribute("student") stud : Student) : ModelAndView {
println("called from submitted()")
return ModelAndView("submitted")
}
}
Here the method studentForm() is perfectly getting mapped to the view(form.jsp) but the method submitted is not getting mapped.
form.jsp
<%# 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>Insert title here</title>
</head>
<body>
<form action="./submitted" method="post">
NAME : <input id="name"/>
AGE : <input id="age"/>
CITY : <input id="address.city"/>
STATE : <input id="address.state"/>
<input type="submit"/>
</form>
</body>
</html>

check your link 404 means not found ,it may cause by not pointing to root here ./submitted , change to ${pageContext.request.contextPath}/foo or configuration of WEB-INF location.
4×× Client Error
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Payload Too Large
414 Request-URI Too Long
415 Unsupported Media Type
416 Requested Range Not Satisfiable
417 Expectation Failed
418 I'm a teapot
421 Misdirected Request
422 Unprocessable Entity
423 Locked
424 Failed Dependency
426 Upgrade Required
428 Precondition Required
429 Too Many Requests
431 Request Header Fields Too Large
444 Connection Closed Without Response
451 Unavailable For Legal Reasons
499 Client Closed Request

I found the mistake in my code and it was a small mistake but i was not aware of it because of my lack of knowledge in web domain.
In form.jsp, in the form I was giving id attribute to all the input elements. I changes those to the name and it was working fine.

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.

Jersey Freemarker MVC

I try to configure jersey-mvc-freemarker on TomEE 1.7.2. But I can't ...
Configure Jersey
#ApplicationPath("resources")
public class JerseyConfig extends ResourceConfig{
public JerseyConfig() {
packages("my.pack.controllers")
.property(MvcFeature.TEMPLATE_BASE_PATH, "/WEB-INF/classes/my/pack")
.register(org.glassfish.jersey.server.mvc.freemarker.FreemarkerMvcFeature.class);
}
}
Controller
#Path("main")
public class MainController {
#Inject
private TestBean bean;
#GET
public Viewable getIt() {
return new Viewable("test");
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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"
version="2.4">
<display-name>ui</display-name>
</web-app>
I put my test.ftl to my.pack
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
test
</body>
</html>
When I go to http://localhost:8080/resources/main I get message
No message body writer has been found for response class Viewable.
Thanks you
UPDATE:
I configured tracing in Jersey and got:
javax.servlet.ServletException: Error processing webservice request
org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:98)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
org.apache.openejb.server.cxf.rs.CxfRsHttpListener.doInvoke(CxfRsHttpListener.java:227)
org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:94)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat (TomEE)/7.0.62 (1.7.2) logs.

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.

Sending HTML/JSON from REST Spring MVC Web app

I have developed a REST web application with Spring MVC and I can send JSON objects to a client.
I would like to construct a Javascript/AJAX client that connects to my web application but I don't know how to send the first HTML page (using JSP).
I understand I should serve JSP pages with some embedded AJAX. This AJAX will send requests to my web services.
Update:
The requirement I am not able to achieve is to write the default URI (http://localhost:8084) in browser and see the HTML page I have written in JSP page (home.jsp).
My approach is following:
I have a Controller that sends the root JSP page
#Controller
public class SessionController {
#RequestMapping(value="/", method=RequestMethod.GET)
public String homeScreen(){
return "home";
}
}
But when I run the server I receive this warning
WARNING: No mapping found for HTTP request with URI [/home] in DispatcherServlet with name 'dispatcher'
and nothing is loaded in browser.
Here is my application-context file:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="com.powerelectronics.freesun.web" />
<mvc:annotation-driven />
</beans>
And 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">
<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>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Is my approach correct? Am I wrong at any basic concept?
Can I modify something in my code to make it run?
I would like to see the first page loaded in browser and keep going in that direction.
Thanks in advance.
Try adding a #ResponseBody annotation on the method:
#Controller
public class SessionController {
#RequestMapping(value="/", method=RequestMethod.GET)
#ResponseBody
public String homeScreen(){
return "home";
}
}
This should output home on the page.
If you'd like to use View technologies, e.g. JSP, review the following chapter on the official Spring Framework documentation: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#view
Update
"Just as with any other view technology you're integrating with Spring, for JSPs you'll need a view resolver that will resolve your views ". If you'd like to use JSP you should then add the following to your Web application context, then return the name of the file that shall be processed:
<!-- the ResourceBundleViewResolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views"/>
</bean>
<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>
Is the above present in your Web application context? You can review the official documentation for further information: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#view-jsp-resolver
Place a welcome file tag in web.xml file.
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
You must be having this index.jsp outside of WEB-INF. Put following code in it.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
response.sendRedirect("home");
%>
</body>
</html>
When application is loaded, it will call index.jsp and jsp will redirect it to /home action.
Then your controller will get called.
#Controller
public class SessionController {
// see the request mapping value attribute here, it is /home
#RequestMapping(value="/home", method=RequestMethod.GET)
public String homeScreen(){
return "home";
}
}
This will call your home jsp.
If you want to to return JSON from your spring controller, then you need jackson mapper bean initialized in spring context xml file.
<beans:bean id="jacksonMessageChanger" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<beans:property name="supportedMediaTypes" value="application/json" />
</beans:bean>
<beans:bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<beans:property name="messageConverters">
<util:list id="beanList">
<beans:ref bean="jacksonMessageChanger" />
</util:list>
</beans:property>
</beans:bean>
You need to add jar or maven dependency to use jackson mapper.
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.8.5</version>
</dependency>
And to return JSON from controller, method would be like this :
#RequestMapping(value="/getContacts", method=RequestMethod.GET)
public #ResponseBody List<Contacts> getContacts(){
List<Contacts> contactList = prepareContactList();
return contactList;
}
This way you will get List in the success function of ajax call in the form of object and by iterating it you can get the details.
Finally I solve this only with configuring the dispatcher in web.xml on a different way.
First I added the view resolver to the servlet configuration file as David Riccitelli suggested me:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>
And then I configured the servlet mapping in web.xml:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
That's what I was looking for, and no extra configuration is needed.
Doing this I call my root URL http://localhost:8084 and I can see the home screen I have coded in home.jsp.
Thanks for your support and suggestions.

Spring MVC 3.0 404 error

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.

Resources