j_security_check login.jsp is not working with WebSphere Liberty profile - spring

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

Related

Spring MVC:ERROR 404-Description The origin server did not find a current representation for the target resource or is not willing

I'm a beginner in Spring framework. I'm trying to build a shopping project in Spring MVC framework. The project is to implement a shopping cart (but in small scale). It includes 2 JSP files as a view to take users requests and respond to them, namely ViewAddproduct.jsp and ViewCart.asp. In addition, the project has 4 files pom.xml, web.xml, NikiAbb-servlet.xml and AddController.java. (I open Maven project and add all required dependencies) It seems all code or added dependencies in my files are correct and I can run each page individually on the server (Tomcat). But when I run whole package I get error 404. I have checked lots of tutorials to solve it but it doesn't work. Any help would be appreciated.
I am using JDK 9.0.4, Eclipse Java EE IDE for Web Developers. Oxygen 2 Release (4.7.2), and Tomcat 9
Package hierarchy:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>NikiAbb</groupId>
<artifactId>Testut</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Testut Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<properties>
<java.version>9.0.4</java.version>
</properties>
<build>
<finalName>Testut</finalName>
</build>
</project>
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>NikiAbb</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>NikiAbb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
NikiAbb-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:p="http://www.springframework.org/schema/p"
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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package = "NikiCart" />
<bean class
= "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
</beans>
Addcontroller.java
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
#Controller
public class AddController
{
#RequestMapping("/add")
public ModelAndView add(HttpServletRequest request,HttpServletRespose
response)
{
int H-box=Integer.parseInt(request.getParameter("horse-box");
int H-unit=Integer.parseInt(request.getParameter("horse-unit");
int P-box=Integer.parseInt(request.getParameter("ping-box");
int P-unit=Integer.parseInt(request.getParameter("ping-unit");
AddService as = new AddService();
if (H-box=!"") || (H-uint=!)
{
int k = as.add(H-box,H-uint,0);
}else if(P-box=!"") || (P-uint=!)
{
int k = as.add(P-box,P-uint,1);
}
ModelAddview mv = new ModelAndView();
mv.setViewName("ViewCart.jsp");
mv.addObject("Apro-price",k);
return mv;
}
}
ViewAddproduct.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">
</head>
<body>
<h1 align="center">Wellcome To Online Shopping</h1>
<h3 align="center"><font color="blue">Get 10% Discount for shopping 3 box
or more</font></h3>
</br></br>
<form action ="add">
<table border="1" align="center">
<tr>
<td align="center"><img
src="http://www.yourpresents.co.uk/user/products/large/penguine-figurine- trinket-box.jpg" alt="penguin" height="420" width="400"/>
</br></br>
<font size=5>Penguin-jewelry-box</font></br>
<font size=3>Price per box : 175 Nok</br>
20 Unit in each box</font>
</br></br><font size=3>Number Of Box : </font><input name="ping- box" type="number" min="0" max="50" step="1" value ="0"/>
</br></br><font size=3>Number Of Units : </font><input name="ping- unit" type="number" min="0" max="50" step="1" value ="0"/>
</br>
</br>
<input type = "button" value = "Add To Cart"/>
</br>
</td>
<td align="center" height="420" width="400"><img
src="https://cdn0.rubylane.com/shops/632271/005849.1L.jpg" alt="horse"
height="320" width="300">
</br></br></br></br></br></br></br>
<font size=5>HorseShoe-Card</font>
</br>
<font size=3>Price per box : 829 Nok</font></br>
5 Units in each box</font>
</br></br><form:label path = "horse-box"><font size=3>Number Of
Box : </font></form:label><form:input path="horse-box"
</br></br><form:label path = "horse-unit"><font size=3>
Number Of Units : </font></form:label><form:input
path="horse- unit" type="number" min="0" max="50" step="1" value ="0"/>
</br></br>
<input type = "button" value = "Add To Cart"/>
</br>
</td>
</tr>
</table>
</form>
</body>
</html>
ViewCart.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false"%>
<!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">
</head>
<hr width="1700" size="2" color="black">
<table border="0.5" align="left">
<tr align="center"><td width="400">
<img
src="http://www.yourpresents.co.uk/user/products/large/penguine-figurine- trinket-box.jpg" alt="penguin" height="220" width="200"/> </td>
<td width="300">
<font size=5 color="blue">${product-name}</font></td>
<td width="700" align="right"><font size=3>Amount:</font></br>
<font size=3>${Aprod-box}</font><font size=3>Box</font>
</br>
<font size=3>${Aprod-unit}Units</font>
</br></br></br></br></br><font size=3></font>Price:
<font size=4>${Apro-price}</font>
</td>
</tr>
<tr><td width="700">
<hr width="1700" size="1" color="black"></td>></tr>
<tr align="cente" ><td width="700" align="left">
<font size=4>Total:</font>
<td width="400" align="right"><font size=5>${price-total} Nok</font>
</td>
</tr>
<tr> <td>
</br></br></br>
<font align="center"></font></font><input type = "submit"
style="height:50px;width:250px" value = "continoue to shopping"/>
<input type = "submit" align="center" style="height:50px;width:250px"
value = "continue shopping"/>
</td></tr></table>
</body>
</html>
# NikiAbb-servlet.xml file <property name = "prefix" value = "/WEB-INF/jsp/" /> should be <property name = "prefix" value = "/WEB-INF/" /> couldn't see any jsp folder under WEB-INF.
# Addcontroller.java
#RequestMapping("/add")
public ModelAndView.add(HttpServletRequest request,HttpServletRespose rsponse) should remove that "." #RequestMapping("/addProd")
public ModelAndView add(HttpServletRequest. Even your RequestMapping also wrong.
Another thing mv.setViewName("ViewCart.jsp");, no need to add .jsp again just change as mv.setViewName("ViewCart");.

404 error on a simple spring mvc aplication

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.

Debugging LDAP with shiro in Tomcat

I have a web service, and for that I want to authenticate users.
I'm trying to have a form based authentication with org.apache.shiro.realm.ldap.JndiLdapRealm as my realm.
But when I enter the credentials nothing happens but redirecting to login page again. And there's nothing get printed on the log.
My Question is how can I debug the shiro to figure out what is happening?
Edit:
Here is my shiro ini file
[main]
authc.loginUrl = /login.jsp
authc.successUrl = /index.jsp
ldapRealm = org.apache.shiro.realm.ldap.JndiLdapRealm
ldapRealm.userDnTemplate = sAMAccountName={0},DC=aaa,DC=bbb
ldapRealm.contextFactory.url = ldap://aaa.bbb.ccc:3268
ldapRealm.contextFactory.systemUsername = admin
ldapRealm.contextFactory.systemPassword= password
securityManager.realms = $ldapRealm
[urls]
/login.jsp = authc
/logout = logout
/** = authc
Edit 2: my login jsp
<form name="loginform" method="post">
plain
<label for="username">Username:</label>
<input type="text" id="username" name="username" />
<br/>
<label for="password">Password:</label>
<input type="password" id="password" name="password" />
<br/>
<label for="rememberMe">Remember me:</label>
<input type="checkbox" id="rememberMe" name="rememberMe" value="true" />
<br/>
<input type="submit" value="Login" />
</form>
my web.xml
<listener>
<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>
<filter>
<filter-name>ShiroFilter</filter-name>
<filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ShiroFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>

Spring MVC, Form Submission not working

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">

Spring MVC 404 Error on some requests

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>`

Resources