Need help on Spring MVC hello world - spring

I am trying to learn Spring MVC on NetBeans 8.0.2 using Hibernate and frankly I am stuck. Any help is appreciated. I am only trying to do a very simple "hello world" type site.
Someone would on the first page hit a submit button and the resulting page would have a list of values from the DB. Sounds pretty simple right?
I've included 5 very short files here that will hopefully help you to help me if you are so inclined.
"web.xml", "dispatcher-servlet.xml","index.jsp", "TeamController.java", "secondView.jsp"
The way I understand how Spring MVC should work, using my files, is as follows...
1) Running the project from NetBeans, the index.jsp file is brought up.
This happens because the Web.xml is consulted, which has the following line...
"<welcome-file>redirect.jsp</welcome-file>"
once the redirect.jsp is consulted, we see that it has the following...
"<% response.sendRedirect("index.htm"); %>"
so with that redirect we go back to the web.xml which has the following...
"<servlet-name>dispatcher</servlet-name>"
"<url-pattern>*.htm</url-pattern>"
so with that request coming in as index.htm it is to be handled by the dispatcher servlet.
In the dispatcher servlet's config file, the view resolver will add the following...
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
so index.htm gets changed to /WEN-INF/jsp/index.jsp and that page is brought up.
2) At this point the index.jsp is brought up. The only thing in this file is a form with a submit button. The intent is just to have someone press the button and info from the DB is returned on screen. I have Hibernate as part of this web project and I have created a java class "Team.java" based on a DB table "Team". It is populated with a few records.
Currently what I am seeing is that once the index.jsp comes up and I hit submit, it is giving a 404.
This is the URL shown for the form
"host:port/HelloWebFour/index.htm "
if I do a view source it shows it as the index.jsp. When I hit submit it gives a 404 with this url
"host:port/HelloWebFour/team? "
btw, "HelloWebFour" is the name of my project in NetBeans.
I am not sure what is happening, if my understanding is right or if I need to add anything. any help is appreciated...
The very short code files are below...
"Web.xml"
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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">
<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>*.htm</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
"dispatcher-servlet.xml"
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd" xmlns:context="http://www.springframework.org/schema/context">
<context:component-scan base-package="testnew1" />
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</beans>
"index.jsp"
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!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>index.jsp - the submit page</title>
</head>
<body>
<h2>Hit submit to get DB information</h2>
<form:form method="GET" action="/HelloWebFour/team">
<table>
<tr>
<td>
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
"TeamController.java"
package testnew1;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.servlet.ModelAndView;
#Controller
public class TeamController {
#RequestMapping(value = "/team", method = RequestMethod.GET)
public String getTeam(#ModelAttribute("SpringWeb") Team team,
ModelMap model) {
model.addAttribute("city", team.getCity());
model.addAttribute("state", team.getState());
model.addAttribute("nickname", team.getNickname());
return "secondView";
}
}
"secondView.jsp"
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>secondView.jsp - the results page</title>
</head>
<body>
<h2>Database Information</h2>
<table>
<tr>
<td>City</td>
<td>${city}</td>
</tr>
<tr>
<td>State</td>
<td>${state}</td>
</tr>
<tr>
<td>Nickname</td>
<td>${nickname}</td>
</tr>
</table>
</body>
</html>

As far I see you Submiting to "/HelloWebFour/team but your only request handler method is mapped to /team, try to submit to just /team. I don't use any prefix on Dispatcher mapping so can be a missed .htm on url combining with the unknown request url /HelloWebFour/team.
Then if one of above solutions work, your method may fail because you are expecting a modelAttribute named as "SpringWeb" of type Team, but your form actually dont post any data and it's modelAttribute is mapped to "command", the default value, so removing this can possibly remove a further error if occurs.

Related

How to Pass a view from controller?

I am new to Spring MVC. And I am trying to work with multiple views. When I use a single view and a single controller it works perfectly. But when I try to open a view from another view, I am getting HTTP 404 error (The requested resource is not found)
Project Directory Structure
As in the picture, I am having index.jsp as my home page view. From this page, I need to navigate another page(viewpage1.jsp) which is inside the WEB-INF/jsp directory. When I do so, I get HTTP 404 not found error.
HelloController.java
package com.springwebproject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class HelloController
{
#RequestMapping("/")
public String home()
{
return "index";
}
#RequestMapping("/hello")
public String display()
{
return "viewpage1";
}
}
index.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<f:view>
<h1>Home Page</h1>
Go to Next View
</f:view>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" 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>SpringWebProject</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>SpringWebProject</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringWebProject</servlet-name>
<url-pattern>/viewpage1.jsp</url-pattern>
</servlet-mapping>
</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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.springwebproject" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
</bean>
</beans>
viewpage1.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<f:view>
<h1>First View Page after Home page</h1>
</f:view>
</body>
</html>
Add this bean to your configuration:
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver =
new InternalResourceViewResolver();
viewResolver.setPrefix("/views/"); // locate your directory with *.jsp files here
viewResolver.setSuffix(".jsp");
return viewResolver;
}
as you have given the mapping as "/hello" to view viewpage1, you have to change your href like this:
Go to Next View
Let me know, if this helps.

Issue with Spring Form Tag in spring MVC

I am trying to build a simple application to create and update few records using spring MVC. But not able to proceed further as I am facing issue that my spring form tag has some error and I am not able to figure out since 2 days. error says:
java.lang.IllegalStateException: No WebApplicationContext found: not in a DispatcherServlet request and no ContextLoaderListener registered?
Few Doubts as well :
Why do I need ContextLoaderListener when I am using dispatcherServlet.
Every DispatcherServlet has its own or instantiates WebApplicationContext. Then why is the error saying its not available ?
Anything that I am missing, conceptually or programmatically ?
Welcome.jsp
<html>
<body>
<h2>Welcome to the ADStore Portal</h2>
Add Employee<br>
<!-- Update Employee -->
</body>
</html>
addEmp.jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Add Employee</h1>
<form:form action = "/add" modelAttribute = "employee">
<table>
<tr>
<td>Name :</td>
<td><form:input path="empname"/>
</tr>
<tr>
<td>Id :</td>
<td><form:input path="empid"/>
</tr>
<tr>
<td>Designation :</td>
<td><form:input path="designation"/>
</tr>
<tr>
<td>Department :</td>
<td><form:input path="department"/>
</tr>
<tr>
<td><input type="submit" name="Submit"/></td>
</tr>
</table>
</form:form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>AD Store</display-name>
<servlet>
<servlet-name>adstore</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>adstore</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
adstore-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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
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.2.xsd">
<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="com.adstore" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
EmployeeController.java
package com.adstore.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.adstore.bean.Employee;
import com.adstore.dao.EmployeeDAO;
#Controller
public class EmployeeController {
private EmployeeDAO dao;
#RequestMapping(value="/add")
public ModelAndView saveEmployee(#ModelAttribute("employee") Employee emp) {
System.out.println("In saveEmployee");
dao.saveEmp(emp);
return new ModelAndView("viewEmployee","command",new Employee());
}
}
EmployeeDAO.java
package com.adstore.dao;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import com.adstore.bean.Employee;
public class EmployeeDAO {
private JdbcTemplate jdbcTemplate;
public boolean saveEmp(final Employee emp) {
boolean result = false;
String query = "INSERT INTO ADSTORE VALUES(?,?,?,?)";
result = jdbcTemplate.execute(query, new PreparedStatementCallback<Boolean>() {
public Boolean doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
ps.setString(1, emp.getEmpName());
ps.setInt(2, emp.getEmpId());
ps.setString(3, emp.getDesignation());
ps.setString(4, emp.getDepartment());
return ps.execute();
}
});
return result;
}
}
Error Image::
No application context is found because the request is not being handled by the DispatcherServlet as you are going directly to the JSP page. Hence there is no required Spring infrastructure to process the form:form tags.
You should access the page using the url defined in the #Controller using #RequestMapping or its variants. Its not good practice to put the JSP pages in a location which makes them accessible directly by clients. Instead you should hide them in the /WEB-INF/ directory
According to your view resolver the jsp pages should reside in the /WEB-INF/views folder. Move the JSPs to this folder.
You need to add following code in your web.xml
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>/WEB-INF/views/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-security.xml //if you need
/WEB-INF/adstore-servlet.xml
</param-value>
</context-param>
and about your doubts-
1- If you want to put your Servlet file with custom name or at your custom location, rather than the default naming convention [servletname]-servlet.xml and path under Web-INF/ ,then you can use ContextLoaderListener.
Basically you can isolate your root application context and web application context using ContextLoaderListner.
The config file mapped with context param will behave as root application context configuration. And config file mapped with dispatcher servlet will behave like web application context.
In any web application we may have multiple dispatcher servlets, so multiple web application contexts.
But in any web application we may have only one root application context that is shared with all web application contexts.
We should define our common services, entities, etc in root application context. And controllers, interceptors etc are in relevant web application context.
and for more information--
The blog, "Purpose of ContextLoaderListener – Spring MVC" gives a very good explanation.
The code which you have posted is absolutely working fine.
I don't get any exception what is posted here. But few pointers I can point it out.
Check your files in the project which should be exactly same as below
You can call directly call addEmp.jsp in the starting as replacing your code.
#RequestMapping(value = "/", method = RequestMethod.GET)
public String printWelcome(#ModelAttribute("employee") Employee emp) {
return "addEmp";
}
Hope it resolves. If still you are facing issue, commit code to github and share the link.

Unable to Setup Spring + Maven Project

I am new to working with Spring and decided to follow this tutorial:
http://www.programcreek.com/2014/02/spring-mvc-helloworld-using-maven-in-eclipse/
My files and file structure match the tutorial, and index.jsp is working. However, when I click to go to helloworld.jsp, I get the following 404 error:
The origin server did not find a current representation for the target
resource or is not willing to disclose that one exists.
Can anybody suggest places to dig? Is there something wrong with the tutorial that is not suited to Tomcat 8.5? Or is it more likely that there is something wrong with my setup?
EDIT:
I have the following installed:
Tomcat 8.5.14
Eclipse Neon with Spring IDE
Maven 3.5.0
If it helps, Maven has been working before I tried using it with a Web/Spring (ie mvn install downloads the correct libraries)
I have included an image
of my files and a below is the actual code of the files that I believe are relevant:
UserController.java
package com.ankurmgoyal.hellotest.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class HelloWorldController {
String message = "Welcome to Spring MVC!";
#RequestMapping("/hello")
public ModelAndView showMessage(
#RequestParam(value = "name", required = false, defaultValue = "World") String name) {
System.out.println("in controller");
ModelAndView mv = new ModelAndView("helloworld");
mv.addObject("message", message);
mv.addObject("name", name);
return mv;
}
}
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>Archetype Created Web Application</display-name>
<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>/</url-pattern>
</servlet-mapping>
<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>
</web-app>
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring 4 MVC - HelloWorld Index Page</title>
</head>
<body>
<center>
<h2>Hello World</h2>
<h3>
Click Here
</h3>
</center>
</body>
</html>
helloworld.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring 4 MVC -HelloWorld</title>
</head>
<body>
<center>
<h2>Hello World</h2>
</center>
</body>
</html>
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"
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="com.ankurmgoyal.hellotest.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
index.jsp is served by DefaultServlet. The url-pattern for dispatcher is /. / pattern overrides the defaultServlet and all the calls are routed through this servlet. Change the url pattern to some non-empty string and try it out.
Refer to this SO Question for more details.

Spring MVC - app with no default index page and textfield not showing

All,
A Spring newbie here.
I am trying to build a spring mvc(Sping 4.1.6 release) app. This app does not have a default landing page(like index.jsp, I have removed index.jsp from my app). This app will be called from another app by URL links or directly typing the path. My issue is I am not able to get this working. When I type localhost:8080/app/user.jsp(this is in WEB-INF/jsp folder) or localhost:8080/app/jsp/user.jsp(I would prefer not to use this path though).
Another question: I tweaked the app to have an index.jsp redirecting to user.jsp in the WEB-INF folder(not the WEB-INF/jsp) and the Controller #RequestMapping("/"), the user.jsp loads but the textbox is not displayed.
My 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>selfsrvc</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
my spring-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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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="com.company"></context:component-scan>
<mvc:annotation-driven />
<mvc:resources mapping="/**" location="/" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value="/WEB-INF/jsp/" />
<property name = "suffix" value=".jsp" />
</bean>
<bean class="org.springframework.context.support.ResourceBundleMessageSource"
id="messageSource">
<property name="basename" value="messages" />
</bean>
My Controller
#Controller
#RequestMapping("/user.jsp")
public class userController {
#RequestMapping(method = RequestMethod.GET)
public String initForm(Model model){
user user = new user();
model.addAttribute("user", user);
System.out.println("IIIIIIIIInside user Controller");
return "user";
}
}
My jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form method="POST" commandName="user">
<table>
<tr>
<td>Enter your name:</td>
<td><form:input path="user" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
<tr>
</table>
</form:form>
</body>
</html>
I am not sure what I am missing in both the scenarios. Thanks.
EDIT: The suggestion by minion solved my issue. Thanks.
There are couple of issues or changes you need to do. Here is the Gist of the issue :
Your spring servlet is mapped to / and the requested url is of the
pattern *.jsp. So it would never hit the controller that you wrote.
So change your controller to like one below.
#Controller
#RequestMapping("/user")
public class userController {
#RequestMapping(method = RequestMethod.GET)
public String initForm(Model model){
user user = new user();
model.addAttribute("user", user);
System.out.println("IIIIIIIIInside user Controller");
return "user";
}
Use the url localhost:8080/app/jsp/user to hit the controller.
}

Spring 3 MVC extra #RequestMapping value getting appended to returned view

I have a view 'hi.jsp' with user name and password text fields. I need to submit 'hi.jsp' to 'LoginController.java'. If there is any error in the data submitted then 'LoginController.java' must redirect the request back to 'hi.jsp' (with text fields retaning the entered data) with respective error messages. After changing data and re-submitting 'hi.jsp' I get 404 error.
So the first submission is successful however problem occurs during second submission.
The source code of files is mentioned below:
hi.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="s" %>
<%# page session="false" %>
<html>
<body>
<s:form method="POST" modelAttribute="loginObj" action="login/validatelogin">
<label for="userName">UserName</label>
<s:input path="userName" id="userName" size="15"/><br>
<div style="{color:red}"> <s:errors path="userName"></s:errors></div>
<label for="password">Password</label>
<s:input path="password" id="password" size="15" /><br>
<s:errors path="password"></s:errors>
<input name="submit" type="submit" value="login"/>
</s:form>
</body>
</html>
LoginController.java
package rajeev.spring.spitter.mvc.controller;
import javax.validation.Valid;
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;
#Controller
#RequestMapping("/login")
public class LoginController {
#RequestMapping(value="/validatelogin", method=RequestMethod.POST)
public String validateLogin(#Valid #ModelAttribute("loginObj") LoginBean loginObj, BindingResult bindingResult)
{
System.out.println(bindingResult.hasErrors());
if(bindingResult.hasErrors())
{
return "hi";
}
return "home";
}
}
spitter-servlet.xml (spring configuration)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="rajeev.spring.spitter.mvc.controller"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
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 Hello World</display-name>
<welcome-file-list>
<welcome-file>/</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springDispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spitter-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
During the second submission of 'hi.jsp' tomcat log also displays a warning:
WARNING: No mapping found for HTTP request with URI [/SpringMVC/login/login/validatelogin] in DispatcherServlet with name 'springDispatcher'
It seems that during second submission of 'hi.jsp' an extra '/login' is getting appended to the submission path of the form.
Kindly suggest if something is wrong with above code or do I need to modify it to make it working.
Thanks for your help.
This is because the relative form post URL changed when you map your handler method into a different URL
<s:form method="POST" modelAttribute="loginObj" action="login/validatelogin">
Common solution to this problem is to use absolute path, but instead of hardcoding, lookup your context-path using
<c:set var="root" value="${pageContext.request.contextPath}"/>
Then on your form
<s:form method="POST" modelAttribute="loginObj" action="${root}/login/validatelogin">
Other option you might consider is to use Post-Redirect pattern in your controller handler method to avoid switching the URL
public String validateLogin(#Valid #ModelAttribute("loginObj") LoginBean loginObj, BindingResult bindingResult) {
....
return "redirect:/login";
}
Try this:
<c:url var="myAction" value="/login/validatelogin"/>
<s:form method="POST" modelAttribute="loginObj" action="${myAction}">

Resources