I’m developing Spring MVC, on Apache 7.xx application and have setup everything without any errors.
I have a my application map my dispatcher servlet to HomeController , which serves the view “home/View” which is also working.
I want to implement UserAccount & Registeration use case before wiring & itegrating with spring security.
However my registration form (Register.jsp) on form submit ( or action="UserRegisteration/RegisterForm" method="POST">) gives 404 error rather than serving a view via (for testing I have UserRegisterationController serve Register.jsp again)
Register.jsp (form snippet)
<form action="/UserRegisteration/RegisterForm" method="POST">
<table width="283" border="1">
<tr>
<td width="123"><label for="firstname">First Name</label></td>
<td width="144"><input type="text" name="firstname" id="firstname"></td>
</tr>
<tr>
<td><label for="lastname">Last Name</label></td>
<td><input type="text" name="lastname" id="lastname"></td>
</tr>
<tr>
<td><label for="email">Email</label></td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td><label for="phonecontact1">Phone Contact 1</label></td>
<td><input type="text" name="phonecontact1" id="phonecontact1"></td>
</tr>
<tr>
<td><label for="phonecontact2">Phone Contact 2</label></td>
<td><input type="text" name="phonecontact2" id="phonecontact2"></td>
</tr>
<tr>
<td><label for="address1">Address 1</label></td>
<td><input type="text" name="address1" id="address1"></td>
</tr>
<tr>
<td><label for="address2">Address 2</label></td>
<td><input type="text" name="address2" id="address2"></td>
</tr>
<tr>
<td><label for="industry ">Industry </label></td>
<td><input type="text" name="industry " id="industry "></td>
</tr>
<tr>
<td><label for="password">Enter Desired Password</label></td>
<td><input type="text" name="password" id="password"></td>
</tr>
<tr>
<td><input type="reset" name="clear " id="clear " value="Clear Fields"></td>
<td><input type="submit" name="register" id="register" value="Register"></td>
</tr>
</table>
</form>
I have the following method createUserAccountRegisteration()mapped to
#RequestMapping(value="/RegisterForm", method=RequestMethod.POST) see below:
(UserRegisterationController.java)
#Controller
#RequestMapping("/UserRegisteration")
public class UserRegisterationController {
#Autowired
private RegisterationService registerationService;
#Autowired
private UserAccountService userAccountService;
#Autowired
private PasswordService passwordService;
public UserRegisterationController() {
}
public UserRegisterationController(RegisterationService registerationService, UserAccountService userAccountService, PasswordService password) {
this.registerationService = registerationService;
this.userAccountService = userAccountService;
this.passwordService = password;
}
//if checked on register link , forward to registeration page
#RequestMapping(value="/RegisterForm", method=RequestMethod.GET)
public String serveRegisterationView()
{
return "UserAccount/Register";
}
#RequestMapping(value="/RegisterForm", method=RequestMethod.POST)
public String createUserAccountRegisteration()
{
//if submited registeration
//check for previous registeration
//if registered prompt , forward to sign in
//else create registeration , and user account , and password , forward to main user page
return "UserAccount/Register";
}
}
web.xml
<web-app metadata-complete="true" 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
/WEB-INF/hibernate-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>cmgr</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cmgr</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
spring-servlet relevat snippet (in my case cmgr-servlet)
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views/" p:suffix=".jsp" p:viewClass="org.springframework.web.servlet.view.JstlView" />
applicationContext.xml (relevant snippet)
<!-- 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="com.cmgr.*" />
<!-- 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/>
<!-- mapping of static resources-->
<mvc:resources mapping="/resources/**" location="/resources/" />
</beans>
Result of Register.jsp form sumbmit:
Browser URL: (http://localhost:8084/UserRegisteration/RegisterForm)
HTTP Status 404 - /UserRegisteration/RegisterForm
type Status report
message /UserRegisteration/RegisterForm
description The requested resource (/UserRegisteration/RegisterForm) is not available.
Apache Tomcat/7.0.22
What i noticed is the browser url is missing my applications context (/cmgr) the correct url should be "http://localhost:8084/cmgr/UserRegisteration/RegisterForm"
Result of Register.jsp form sumbmit:
Browser URL: (http://localhost:8084/UserRegisteration/RegisterForm)
What i noticed is the browser url is missing my applications context (/cmgr) the correct url >should be "http://localhost:8084/cmgr/UserRegisteration/RegisterForm"
This is right, the context root "/cmgr" is missing. Show us your view, presumably the form action is the problem.
You could use the Spring url tag, like this:
<spring:url value="/UserRegisteration/RegisterForm" var="targetURL"/>
<form action="${targetURL}" [...] >
</form>`
Related
I am new to Spring and trying one user registration example using maven with spring mvc.
I am able to lunch my home page but when i click on the login link than getting 404 error page not found.
Below are my application details:-
Web.xml
<web-app id = "WebApp_ID" version = "2.4"
xmlns = "http://java.sun.com/xml/ns/j2ee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
DispacterServlet:-
<?xml version="1.0" encoding="UTF-8"?>
<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">
<import resource="classpath.*:jbr/config/user-beans.xml" />
<context:component-scan base-package="jbr.springmvc" />
<context:annotation-config />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Controller:-
package jbr.springmvc.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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;
import jbr.springmvc.model.Login;
import jbr.springmvc.model.User;
import jbr.springmvc.service.UserService;
#Controller
public class LoginController {
#Autowired
UserService userService;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView showLogin(HttpServletRequest request, HttpServletResponse response) {
ModelAndView mav = new ModelAndView("login");
mav.addObject("login", new Login());
return mav;
}
#RequestMapping(value = "/loginProcess", method = RequestMethod.POST)
public ModelAndView loginProcess(HttpServletRequest request, HttpServletResponse response,
#ModelAttribute("login") Login login) {
ModelAndView mav = null;
User user = userService.validateUser(login);
if (null != user) {
mav = new ModelAndView("welcome");
mav.addObject("firstname", user.getFirstname());
} else {
mav = new ModelAndView("login");`enter code here`
mav.addObject("message", "Username or Password is wrong!!");
}
return mav;
}
}
Login.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# 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>Login</title>
</head>
<body>
<form:form id="loginForm" modelAttribute="login" action="loginProcess" method="post">
<table align="center">
<tr>
<td>
<form:label path="username">Username: </form:label>
</td>
<td>
<form:input path="username" name="username" id="username" />
</td>
</tr>
<tr>
<td>
<form:label path="password">Password:</form:label>
</td>
<td>
<form:password path="password" name="password" id="password" />
</td>
</tr>
<tr>
<td></td>
<td align="left">
<form:button id="login" name="login">Login</form:button>
</td>
</tr>
<tr></tr>
<tr>
<td></td>
<td>Home
</td>
</tr>
</table>
</form:form>
<table align="center">
<tr>
<td style="font-style: italic; color: red;">${message}</td>
</tr>
</table>
</body>
</html>
I have tried so many some but not able to find any solution for this.
Please help me to identify where I am doing wrong.It's my first application in spring so not able to perform any more analysis.
Please guide me with this
You Have specified home.jsp in your welcome file list. I don't see a home.jsp file in your file path. May be that's throwing you 404. You have a login.jsp. Make your controller return "login" from your controller. Either wise works. Since you mentioned as a beginner, you can check here for bootstrapping a basic app.
https://github.com/mrakhunathan/SpringWebSkeleton.git
When try to run spring sample application using maven i have got the exception mentioned.
Here is my program
Firstpage1.jsp [present in Webcontent]
<html>
<head>
<title>Finacle data retriever</title>
</head>
<body>
<h2>Enter the configuration details</h2>
<form:form method="POST" action="/formexample/Configgen" commandName="configbean">
<table>
<tr>
<td><form:label path="tnu">Total number of Users</form:label></td>
<td><form:input path="tnu" /></td>
</tr>
<tr>
<td><form:label path="cnu">Concurrent number of Users</form:label></td>
<td><form:input path="cnu" /></td>
</tr>
<tr>
<td><form:label path="kat">Keep Alive Timeout</form:label></td>
<td><form:input path="kat" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
result.jsp [ Webcontent/WEB-INF/jsp]
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Result page</title>
</head>
<body>
<h2> Result page information</h2>
<table>
<tr>
<td>Total Number of users</td>
<td>${congibean.tnc}</td>
</tr>
<tr>
<td>Concurrent Number of users</td>
<td>${congibean.cnu}</td>
</tr>
<tr>
<td>Keep alive timeout</td>
<td>${congibean.kat}</td>
</tr>
</table>
</body>
</html>
**spring dependencies are present in maven dependencies.**
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">
<jsp-config>
<taglib>
<taglib-uri>/WEB-INF/spring-form.tld</taglib-uri>
<taglib-location>spring-form.tld</taglib-location>
</taglib>
</jsp-config>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/formex-servlet.xml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>Firstpage1.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>formex</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>formex</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
formex-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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:component-scan base-package="formexamplepack1"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
formexamplepack1 - package
configbean.java
package formexamplepack1;
public class configbean {
private int tuc;
private int cnu;
private int kat;
public int getTuc() {
return tuc;
}
public void setTuc(int tuc) {
this.tuc = tuc;
}
public int getCnu() {
return cnu;
}
public void setCnu(int cnu) {
this.cnu = cnu;
}
public int getKat() {
return kat;
}
public void setKat(int kat) {
this.kat = kat;
}
}
ConfigurationController.java
package formexamplepack1;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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(value = "/Configgen")
public class ConfigurationController {
#RequestMapping(method=RequestMethod.GET)
public String showform(ModelMap model) {
configbean configbean=new configbean();
model.addAttribute("configbean",configbean);
return "Firstpage";
}
#RequestMapping(method=RequestMethod.POST)
public String getdetails(#ModelAttribute("configbean")configbean configbean,ModelMap model,BindingResult bindingResult){
model.addAttribute("tnu", configbean.getTuc());
model.addAttribute("cnu", configbean.getCnu());
model.addAttribute("kat",configbean.getKat());
return "result";
}
}
Help me in resolving the below exception. I have gone through all the answers but not able to figure out. Using java 1.8 and spring jars latest [4.2.6]
tomcat- 7.0.68
Below is the exception
org.apache.jasper.JasperException: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'configbean' available as request attribute
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:556)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:472)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'configbean' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:130)
org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:120)
org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:90)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
org.apache.jsp.Firstpage1_jsp._jspx_meth_form_005flabel_005f0(Firstpage1_jsp.java:216)
org.apache.jsp.Firstpage1_jsp._jspx_meth_form_005fform_005f0(Firstpage1_jsp.java:152)
org.apache.jsp.Firstpage1_jsp._jspService(Firstpage1_jsp.java:105)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Try:
without ModelAttribute annotation
Binding Result direct after the command object
like:
#RequestMapping(method=RequestMethod.POST)
public String getdetails(configbean configbean, BindingResult bindingResult){
model.addAttribute("tnu", configbean.getTuc());
model.addAttribute("cnu", configbean.getCnu());
model.addAttribute("kat",configbean.getKat());
return "result";
}
you are trying to use ${congibean.tnc} in your result.jsp file , but you are not passing it as a model attribute . Instead you are trying to pass "tnu","cnu" and "kat" .
As a result it's giving you a jasper exception , as the compiler is unable to find any model attribute called "configbean" .
To solve this either pass only "configBean" as your model Attribute in the getdetails() method , or change your result.jsp file to use only "${tnc}", "${cnu}" and "${kat}"
I have my LDAP configuration in server.xml in Websphere Liberty profile as follows.
<ldapRegistry baseDN="dc=mydc,dc=myroot,dc=myorg" bindDN="cn=myname,OU=Users,OU=myou,DC=mydc,DC=myroot,DC=myorg" bindPassword="xxxx" host="mycompanyldap" id="ldap" ignoreCase="true" ldapType="Microsoft Active Directory" port="389" realm="LdapRegistry" sslEnabled="false">
<activedFilters groupMemberIdMap="memberof:member" />
<activedFilters groupMemberIdMap="memberOf:member" />
</ldapRegistry>
I have my login.jsp which has this call in it..
<form name="frmLogin" action="j_security_check" method="POST">
<table width="100%">
<tr>
<td align="center">
<table id="loginPanel">
<thead>
<th id="titleRow" colspan="2">Media Inquiries</th>
</thead>
<tbody>
<tr id="firstRow">
<td class="label">LAN ID:</td>
<td class="field"><input type="text" id="j_username" name="j_username" maxlength="20" style="width: 150;"></td>
</tr>
<tr>
<td class="label"> Password: </td>
<td class="field"><input type="password" id="j_password" name="j_password" maxlength="20" style="width: 150;"></td>
</tr>
<tr>
<td id="submitRow" colspan="2">
<input type="submit" id="btnSubmit" value="Logon" onclick="return submitPage()">
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
I have the following defined in my web.xml
<!-- ========== Begin Authentication ========== -->
<security-constraint>
<display-name>All Users Constraint</display-name>
<web-resource-collection>
<web-resource-name>Protected Pages</web-resource-name>
<url-pattern>*.htm</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<description>All Users Authorization Constraint</description>
<role-name>All Users</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>LdapRegistry</realm-name>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/login.jsp?loginFailed=true</form-error-page>
</form-login-config>
</login-config>
<security-role>
<role-name>All Users</role-name>
</security-role>
<!-- ========== End Authentication ========== -->
<!-- Declare Spring Security filter -->
<!-- Add a DelegatingFilterProxy -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<!-- Add a springSecurityFilterChain mapping -->
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>*.htm</url-pattern>
</filter-mapping>
When I do the login using the form login , nothing happens on the front end.
I check the logs and there is this message.
[2/9/16 11:42:27:593 CST] 00000054 com.ibm.ws.logging.internal.impl.IncidentImpl I FFDC1015I: An FFDC Incident has been created: "com.ibm.ws.security.registry.RegistryException: CWIML0515E: The user registry operation could not be completed. The CN=myname,OU=Users,OU=myou,DC=mydc,DC=myroot,DC=myorg entity is not in the scope of the defined realm. Specify an entity that is in the scope of the configured realm in the server.xml file. com.ibm.ws.security.authentication.jaas.modules.UsernameAndPasswordLoginModule 93" at ffdc_16.02.09_11.42.27.0.log
WebSphere documentation shows this.. which is the exact message I received but I am not clear as to what I need to do to fix my server.xml.
http://www-01.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.messages.doc/com.ibm.ws.wim.util.resources.WimUtilMessages.html
CWIML0515E: The user registry operation could not be completed. The {0} entity is not in the scope of the {1} realm. Specify an entity that is in the scope of the configured realm in the server.xml file.
**Explanation** The operation cannot be performed because the specified entity is not in the scope of the realm.
**Action** Ensure that the unique name of the entity is specified correctly. If a realm name is specified in the Context object of the input object, ensure that the name is spelt correctly.
Can someone please help as to what I need to do to have my LDAP work correctly with my login. What do I need to change in my server.xml ?
Thanks
Dhiren
Here is the solution.
This needs to be added to either the web application or ear.
Note the realm of the ldap should be the LdapRealm that you set.
<application-bnd>
<security-role name="All Users">
<special-subject id="group:LdapRegistry/cn=yourCN,OU=Users,OU=,DC=,DC=,DC=" type="ALL_AUTHENTICATED_USERS"/>
<special-subject id="user:LdapRegistry/cn=yourCN,OU=Users,OU=,DC=,DC=,DC=" type="ALL_AUTHENTICATED_USERS"/>
</security-role>
</application-bnd>
Once you set this up. the war and ear can communicate with LDAP
Project Folder structureI have gone through most of the question on this site related to 404 resource not found error on Sring mvc application. I tried all solutions and still ended up with no resolution for over two days. I am new to spring MVC and tried out a sample application from the link
Simple Spring MVC app
My code is exactly as mentioned on the site above. But no matter what change I make, still get a 404 error.
Here's my web.xml section
<?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>abc</display-name>
<welcome-file-list>
<welcome-file>/</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>sdnext</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name><param-value>/WEB-INF/config/sdnext-servlet.xml</param-value></init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sdnext</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
The controller file,
EmployeeController.java
#Controller
public class EmployeeController {
#RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView employee() {
return new ModelAndView("employeeForm", "command", new Employee());
}
#RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String addEmployee(#ModelAttribute("SpringWeb")Employee employee, ModelMap model) {
model.addAttribute("name", employee.getName());
model.addAttribute("age", employee.getAge());
model.addAttribute("empId", employee.getEmpId());
model.addAttribute("salary", employee.getSalary());
return "employeeDetail";
}
}
where Employee is my POJO class with setter and getter methods.
Here is my employeeForm.jsp
<form:form action="/addEmployee" method="POST">
<table><tbody>
<tr> <td><form:label path="empId">Employee :</form:label></td> <td><form:input path="empId"></form:input></td> </tr>
<tr> <td><form:label path="name">EmployeeName:/form:label></form:label></td> <td><form:input path="name"></form:input></td> </tr>
<tr> <td><form:label path="age">Employee Age:</form:label></td> <td><form:input path="age"></form:input></td> </tr>
<tr> <td><form:label path="salary">Employee Salary:</form:label></td> <td><form:input path="salary"></form:input></td> </tr>
<tr> <td colspan="2"><input type="submit" value="Submit"/> </td> </tr>
</tbody></table>
</form:form>
here is my sdnext-servlet.xml
<context:component-scan base-package="com.dineshonjava.emp.controller">
</context:component-scan>
<context:annotation-config/>
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
You are doing a fundamental mistake. Say your project name is bunbub-proj, so the url to access is localhost:8080/bunbub-proj. When you POST to /addEmployee, you are actually hitting localhost:8080/addEmployee instead of localhost:8080/bunbub-proj/addEmployee
The fix is to simply append a . to all of your links/urls. E.g. <form:form action="./addEmployee" method="POST">
Note: Browser considers localhost:8080 as the base url or the host
url.
Can some one help me with this?
My Controller class looks like this, and i have created the customer model class..
/**
* Handles requests for the application home page.
*/
#Controller
#RequestMapping("/customer")
public class CustomerController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("customer", "command", new Customer());
}
#RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
public String addStudent(#ModelAttribute Customer customer,
ModelMap model) {
model.addAttribute("customerName", customer.getCustomerName());
model.addAttribute("emailId", customer.getEmailId());
model.addAttribute("sex", customer.getSex());
return "customerDetails";
}
}
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>Customer Form Handling</display-name>
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>Customer</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/Customer/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Customer</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
JSP Pages
customer.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Customer Form Handling</title>
</head>
<body>
<h2>Customer Information</h2>
<form:form method="POST" commandName = "command" action="/addCustomer">
<table>
<tr>
<td><form:label path="customerName">customerName</form:label></td>
<td><form:input path="customerName" /></td>
</tr>
<tr>
<td><form:label path="emailId">emailId</form:label></td>
<td><form:input path="emailId" /></td>
</tr>
<tr>
<td><form:label path="sex">sex</form:label></td>
<td><form:input path="sex" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
customerDetails.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Customer Form Handling</title>
</head>
<body>
<h2>Customer Detail Information</h2>
<table>
<tr>
<td>CustomerName</td>
<td>${customerName}</td>
</tr>
<tr>
<td>emailId</td>
<td>${emailId}</td>
</tr>
<tr>
<td>sex</td>
<td>${sex}</td>
</tr>
</table>
</body>
</html>
Servlet-Context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.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.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<!-- <resources mapping="/resources/**" location="/resources/" /> -->
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.customerinfo.controller" />
</beans:beans>
But when I run this application in Tomcat Server.. The first url points to
localhost:8080/controller/.
If I append localhost:8080/controller/customer I get the first form page..
But once I click on submit.. it says page not found error.
It's a relative path problem. Your form action is /addCustomer (has / prefix), if you resolve it it's http://localhost:8080/addCustomer. What you wanted is probably http://localhost:8080/appname/customer/addCustomer.
In some cases simply changing it into customer/addCustomer might resolve it, but if your page can also be accessed by http://localhost:8080/appname/customer/ (pay attention to the trailing slash) then this could be a problem. The relative path will translate into http://localhost:8080/appname/customer/customer/addCustomer
Of course now you can think to just do /appname/customer/addCustomer and problem solved, but in fact you are now hard-coding the context path name. If one day the context path changes all this code will break.
One approach I like to use so my JSP can figure out the context path is by defining a root variable
<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<form:form action="${root}/customer/addCustomer">
try as
<form:form method="POST" commandName = "command" action="addCustomer">
instead of
<form:form method="POST" commandName = "command" action="/addCustomer">