I am new to Spring MVC .
please excuse if this is a dumb question , i have tried a lot on my own , but couldn't able to resolve
I am facing here a issue which is my controller is never being getting called
Here is the code
index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="/hello.html" method="post">
Name:<input type="text" name="name"/><br/>
Password:<input type="password" name="password"/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>
dispatcher-servlet.xml
<context:component-scan base-package="com.javatpoint" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
hellopage.jsp
Message is: ${message}
errorpage.jsp
${message}
<jsp:include page="/index.jsp"></jsp:include>
HelloWorldController.java
#Controller
public class HelloWorldController {
#RequestMapping("/hello")
public ModelAndView helloWorld(HttpServletRequest request,HttpServletResponse res) {
String name=request.getParameter("name");
String password=request.getParameter("password");
System.out.println("The Name is"+name);
System.out.println("The password is"+password);
if(password.equals("admin")){
String message = "HELLO "+name;
return new ModelAndView("hellopage", "message", message);
}
else{
return new ModelAndView("errorpage", "message","Sorry, username or password error");
}
}
}
web.xml
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
Include your app context path in the form action:
<form action="${pageContext.request.contextPath}/hello.html" method="post">
Try changing your form's action from /hello.html to /hello, as that's what you have in your controller's #RequestMapping
Related
I am trying execute sample example for spring security using custom login page.The application is not throwing any error.From home.jsp, it is navigating into custom login page but even after entering correct user id and password it is going back to home.jsp instead of hello.jsp without showing any error.Requesting your help in identifying the error.
hello.jsp
<%# taglib prefix="c" uri="/WEB-INF/tld/c.tld" %>
<html>
<body>
<h3>message : ${message}</h3>
<h3>User name : ${username}</h3>
LogOut
</body>
</html>
home.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>
<h3>Welcome to spring security</h3>
<b>Click here to logon</b>
</body>
</html>
login.jsp
<%# taglib prefix="c" uri="/WEB-INF/tld/c.tld"%>
<html>
<head>
<title>Login Page</title>
<style>
.errorblock {
color: #ff0000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
</head>
<body onload='document.f.j_username.focus();'>
<h3>Login with Username and Password (Custom Page)</h3>
<c:if test="${SPRING_SECURITY_LAST_EXCEPTION !=null}"><!-- ${not empty error} -->
<div class="errorblock">
Your login attempt was not successful, try again.<br /> Caused :
${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
</div>
</c:if>
<form name='f' action="<c:url value='j_spring_security_check' />"
method='GET'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='j_username' value=''>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='j_password' />
</td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"
value="submit" />
</td>
</tr>
<tr>
<td colspan='2'><input name="reset" type="reset" />
</td>
</tr>
</table>
</form>
</body>
</html>
web.xml
<?xml version="1.0"?>
<web-app xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" id="WebApp_ID">
<display-name>Spring MVC</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</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/mvc-dispatcher-servlet.xml,/WEB-INF/spring-security.xml
</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
mvc-dispatcher-servlet.xml
<?xml version="1.0"?>
<beans xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans">
<context:component-scan base-package="test"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>mymessages</value>
</list>
</property>
</bean>
</beans>
LoginController.java
package test;
import java.security.Principal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class LoginController {
#RequestMapping(value = "/welcome", method = RequestMethod.GET)
public String printWelcome(ModelMap model,Principal principal) {
System.out.println("*****Hello controller called***");
String name = principal.getName();
model.addAttribute("username", name);
model.addAttribute("message","spring security custom form example");
return "hello";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(ModelMap model) {
return "login";
}
#RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
public String loginerror(ModelMap model) {
model.addAttribute("error","true");
return "login";
}
#RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(ModelMap model) {
return "login";
}
#RequestMapping(value = "/*", method = RequestMethod.GET)
public String home(ModelMap model) {
return "home";
}
}
spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
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-4.3.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.2.xsd">
<!-- <http auto-config="true">
<intercept-url pattern="/welcome*" access="hasRole('ROLE_USER')" />
<http-basic />
</http> -->
<!-- <http>
<intercept-url pattern="/welcome*" access="hasRole('ROLE_USER')"/>
<form-login/>
<logout logout-success-url="/home"/>
</http> -->
<http>
<intercept-url pattern="/welcome*" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login" default-target-url="/welcome" authentication-failure-url ="/loginfailed" />
<logout logout-success-url="/logout"/>
<csrf disabled="true"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="rahul" password="123" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
Try to add those parameters to your spring security form login to make sure your named requests parameters are correct.
<form-login login-page="/login" username-parameter="j_username"
password-parameter="j_password" default-target-url="/welcome"
authentication-failure-url ="/loginfailed" />
Also make sure to change your form:
<form name='loginForm'
action="<c:url value='j_spring_security_check' />" method='POST'>
Also your logout should be a POST, a GET is not supported for logout. Actually you don't need it. Just do something like:
<c:url value="/j_spring_security_logout" var="logoutUrl" />
<form action="${logoutUrl}" method="post" id="logoutForm">
</form>
I am trying to create a simple application using Spring MVC + Spring Security + Hibernate.
I want a distinct URI for 2 different flows which will be like:-
<context>/candidate/... and <context>/admin/...
To achieve this, I am now facing a weird issue where MVC is picking index.jsp from nowhere (I couldn't understand where actually). Here are my files:
web.xml
<display-name>spring</display-name>
<welcome-file-list>
<welcome-file>WEB-INF/pages/login.jsp</welcome-file>
</welcome-file-list>
<!-- Enables Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- End of Spring Security Configuration -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>5</session-timeout>
</session-config>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
</web-app>
applicationContext.xml
<context:annotation-config />
<context:property-placeholder location="/config/appConfig.properties" />
<context:component-scan base-package="com.ctlin">
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.jdbcurl}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
<property name="initialSize" value="${db.minPoolSize}" />
</bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.ctlin.bean.CandidateDetailsBean</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<!-- <prop key="hibernate.default_schema">${db.default_schema}</prop> -->
<prop key="hibernate.dialect">${db.dialect}</prop>
<prop key="hibernate.format_sql">${db.format_sql}</prop>
<prop key="hibernate.show_sql">${db.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="authenticateDao" class="com.ctlin.dao.impl.AuthenticateUserDAOImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="authenticateService" class="com.ctlin.service.impl.AuthenticateUserServiceImpl">
<property name="authenticateUserDao" ref="authenticateDao" />
</bean>
</beans>
mvc-dispatcher-servlet.xml
<context:annotation-config />
<context:component-scan base-package="com.ctlin.web.controller" />
<mvc:annotation-driven/>
<mvc:resources mapping="/**assets**" location="/assets/" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
spring-security.xml
<http auto-config="true" use-expressions="true">
<!-- <access-denied-handler error-page="AccessDenied"/> -->
<intercept-url pattern="/candidate**" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/**/assets/**" access="permitAll" />
<intercept-url pattern="/**/login" access="permitAll" />
<!-- <intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" /> -->
<intercept-url pattern="/**" access="isFullyAuthenticated()" />
<csrf/>
<session-management invalid-session-url="/login"
session-authentication-error-url="/login?sessionexpired"
session-fixation-protection="migrateSession">
<concurrency-control error-if-maximum-exceeded="true" expired-url="/login" max-sessions="1"/>
</session-management>
<form-login login-page="/candidate/login" authentication-failure-url="/candidate/login?error"
username-parameter="userId" password-parameter="password"
default-target-url="/candidate/registerDetails"
login-processing-url="/j_spring_security_check"/>
<logout delete-cookies="JSESSIONID" logout-success-url="/candidate/login?logout"
invalidate-session="true" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="test" password="test" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
Controller
#Controller
#RequestMapping("/candidate")
public class CandidateLoginController {
private static final Logger logger = LoggerFactory.getLogger(CandidateLoginController.class);
private HttpSession httpSession;
#Autowired(required=true)
private IAuthenticateUserSvc authenticateService;
public final void setAuthenticateService(IAuthenticateUserSvc authenticateService) {
this.authenticateService = authenticateService;
}
/**
* #param null
* #return the name of the login view
*/
#RequestMapping(value = { "/", "/login" }, method = RequestMethod.GET)
protected ModelAndView displayLoginPage(#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "sessionexpired", required = false) String sessionExpired,
#RequestParam(value = "logout", required = false) String logout) {
ModelAndView mav = new ModelAndView("login");
logger.debug("Inside displayLoginPage method");
if(error!=null) {
mav.addObject("error", "Either username or password is incorrect");
}
else if(sessionExpired != null) {
mav.addObject("error", "Your session has expired. Kindly login again.");
}
else if (logout != null) {
mav.addObject("msg", "You've been logged out successfully.");
}
return mav;
}
#RequestMapping(value = "/registerDetails")
public ModelAndView registerCandidateDetails() {
System.out.println("candidate get method");
ModelAndView model = new ModelAndView();
model.setViewName("registerDetails");
return model;
}
}
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page session="true"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Candidate Selection Tool</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" />
<link rel="stylesheet" href="assets/css/normalize.css" />
<link rel="stylesheet" href="assets/css/style.css" />
</head>
<body onload='document.loginForm.userId.focus();'>
<div class="container">
<!-- start of main body -->
<div class="row page-header text-center">
<h1>Candidate Selection Tool</h1>
</div>
<div class="col-md-6">
<form name="loginForm" action="<c:url value='j_spring_security_check' />"
class="form-horizontal" method="post" role="login">
<fieldset class="col-md-9 scheduler-border">
<legend class="scheduler-border">Login</legend>
<c:if test="${not empty error}">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<p class="bg-danger text-center lead">${error}</p>
</div>
</div>
</c:if>
<c:if test="${not empty msg}">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<p class="bg-info text-center lead">${msg}</p>
</div>
</div>
</c:if>
<div class="form-group has-feedback">
<label for="cuid" class="col-md-3 control-label">User ID</label>
<div class="col-sm-9">
<input id="cuid" type="text"
placeholder="Please enter your user id" name="userId"
class="form-control" /> <i
class="form-control-feedback glyphicon glyphicon-user"></i>
</div>
</div>
<div class="form-group has-feedback">
<label for="password" class="col-md-3 control-label">Password</label>
<div class="col-sm-9">
<input id="password" type="password"
placeholder="Please enter your password" name="password"
class="form-control" /> <i
class="form-control-feedback glyphicon glyphicon-lock"></i>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-2">
<button type="submit" class="btn btn-success" name="Login">Login</button>
</div>
<div class="col-md-offset-2 col-md-4">
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</fieldset>
</form>
</div>
</div>
<!-- end of main body -->
<script src="assets/js/bootstrap.min.js"></script>
</body>
</html>
Structure of web app:
────webapp
├───assets
│ ├───css
│ ├───fonts
│ ├───img
│ │ └───background
│ └───js
├───config
└───WEB-INF
└───pages
└───error
Now when I access this URL: http://localhost:8282/spring/login, I get HTTP Status 404 - /spring/WEB-INF/pages/index.jsp (The requested resource is not available.)
Why is it looking for index.jsp?
Whereas, when I access: http://localhost:8282/spring/candidate/login, I get No mapping found for HTTP request with URI [/spring/candidate/assets/css/normalize.css] in DispatcherServlet with name 'mvc-dispatcher' and even after entering correct credentials, it remains on the same URL, kind of loop.
Please help me identify the issue.
Try to change your servlet mapping form / to *
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>*</url-pattern>
</servlet-mapping>
Adding to #Paul answer for accessing the css can you try with below:
<mvc:resources mapping="/assets/css/**" location="/assets/css/" />
I have a jsp page called menu.jsp and I have given link to another page called ClsEdit.jsp by <a href="jsp/cls/ClsEdit.jsp?action=create">
When I give this line in menu.jsp, it loads without any problem. But when I give the same line in ClsEdit.jsp, I get the following exception. Please tell me what is the problem with the usage of links.
<form:hidden path="ukey" />
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/tradelc-servlet.xml
</param-value>
</context-param>
<listener>
<listener-class>com.bankofny.inx.omx.lc.web.util.SessionListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>tradelc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>tradelc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
tradelc-sevlet.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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:annotation-config />
<!-- Scans within the base package of the application for #Components to configure-->
<context:component-scan base-package="com.bankofny.inx.omx.lc.web" />
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<bean name="clsData" class="com.bankofny.inx.omx.lc.web.bean.ClauseData">
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="resources.application" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
menu.jsp
<%# page language="java" errorPage="errors/general.jsp" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib uri="/WEB-INF/tlc.tld" prefix="tlc" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<form:form action="/tradelc/ClsSave" method="POST">
<form:hidden path="ukey" />
<table width=100%>
<tr>
<td>
<a href="jsp/cls/ClsEdit.jsp?action=create">
Test clause link
</a href>
</td>
</tr>
</table>
</form:form>
Inside ClsEdit.jsp
<form:hidden path="ukey" />
ControllerJava.java:
#Controller
#SessionAttributes("clsData")//tried adding to sessions
public class ControllerJava{
#ModelAttribute("clsData")//mapped the model attribute
public ClauseData createBean() {
return new ClauseData();
}
#RequestMapping(value = "jsp/cls/ClsEdit")//tried mapping the link here, so that I can add the ‘bean’ to ‘command’ here, but the control did not come here at all, the SOP did not print
public ModelAndView returnClsEdit()
{
System.out.println("is it coming nside this method");
return new ModelAndView("ClsEdit");
}
#RequestMapping(value = "/informlogin", method = RequestMethod.GET)
public ModelAndView execute( HttpServletRequest request,
HttpServletResponse response,
#ModelAttribute("clsData") ClauseData clauseData,
BindingResult bindingResult)
throws Exception {
.
.
.
.
. return new ModelAndView("menu", "command", new ClauseData());
}
}
Exception:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
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.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:154)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:141)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:132)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:116)
org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:422)
org.springframework.web.servlet.tags.form.HiddenInputTag.writeTagContent(HiddenInputTag.java:79)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
Neither BindingResult nor plain target object for bean name 'command' available as request attribute
this is my index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#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>
<form:form action="loginform" method="post">
<form:input type="text" path="name" id="userName" />
<form:input type="password" path="pass" id="password" />
<form:button value="submit"></form:button>
</form:form>
</body>
</html>
this is my Bean
package com.ews.usman.controller;
public class loginBean {
private String name;
private String pass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
this is my Controller
package com.ews.usman.controller;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class LoginFormController {
#RequestMapping(value="/loginform", method=RequestMethod.POST)
public ModelAndView formReader(#ModelAttribute("loginBean") loginBean
loginbean, BindingResult result){
ModelAndView model = new ModelAndView();
model.addObject("name", loginbean.getName());
model.addObject("pass", loginbean.getPass());
model.setViewName("result");
return model;
}
}
this is my 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/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.ews.usman" />
<bean name="/loginform"
class="com.ews.usman.controller.LoginFormController"></bean>
</beans:beans>
this is my 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">
<!-- 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>appServlet</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-
value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>`
You need to add a modelAttribute with a proper name to your form, otherwise the form backing bean name will default to 'command' hence you get your error
<form:form action="loginform" modelAttribute="loginBean" method="post">
I know this question has already been asked before, but none of the solutions mentioned there seems to be working for me.
I'm writing a Spring MVC web application. But my request is not reaching the controller class.
Here are the relevant files.
Can anyone please help me by pointing out where I am going wrong? Thanks...
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>booksWorld</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:**/*applicationContext.xml</param-value>
</context-param>
</web-app>
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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Declare a view resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp"/>
</bean>
</beans>
applicationContext.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:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.booksworld.controllers" />
<context:annotation-config />
<mvc:annotation-driven />
<context:property-placeholder location="classpath:**/*config.properties" />
<!-- <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="resources/Messages" /> -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" p:sessionFactory- ref="sessionFactory" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
<property name="packagesToScan" value="com.booksworld"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
p:username="${jdbc.username}" p:password="${jdbc.password}" >
</bean>
</beans>
My controller class
package com.booksworld.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class CommonController {
#RequestMapping("/proceed")
public String loadLoginPage() {
System.out.println("we reached here");
return "login";
}
#RequestMapping(value="/login")
public String login() {
return "abc";
}
}
index.jsp (the welcome jsp file)
<%# 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>Welcome All</title>
</head>
<body>
<p>Hello World</p>
<%response.sendRedirect("proceed.do"); %>
</body>
</html>
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<!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>Books World - Login</title>
</head>
<body>
<sf:form method="POST" action="login.do" modelAttribute="Login">
<h3>Please enter your credentials</h3>
Login Name<sf:input path="userName" />
Password<sf:password path="password" />
</br>
</br>
<input type="submit" value="Log In" />
<input type="reset" value="Reset" />
</sf:form>
</body>
</html>
I'm developing in eclipse, and using Tomcat. the server log has no errors. Just the standard start-up log.
Please help me to point out where I am going wrong.
You haven't specified which URL you are hitting and what errors or output you are seeing so I will go by the files you have posted. There seem to be at least a few problems with what you have posted. I am assuming you are trying to access either http://[server]:[port]/index.jsp or http://[server]:[port]/.
Problem 1: When using an MVC framework you usually do not request web templates such as JSP files directly. Therefore, your welcome file list in web.xml should not contain index.jsp. It is more common to omit this section altogether. Instead, you should add a request mapping to the controller class for the application root, such as:
#RequestMapping("/")
public String home() { return "index"; }
Once you do this, you should be able to hit http://[server]:[port]/ and get a response.
Problem 2: The file index.jsp redirects to the URL proceed.do but there is no mapping for this URL in your controller. Instead, the controller has a mapping for the URL proceed. May be there was some confusion with Struts when you were trying to configure the URL mappings.
Problem 3: The file login.jsp submits to login.do but there is no mapping for this URL. Instead there is a mapping for login. The form action should therefore be changed from login.do to login.
Problem 4: The form in login.jsp is bound to a model attribute called Login but the controller does not add any model object with that name.
Problem 5: The form in login.jsp is submitted using an HTTP POST but the controller does not specify this for the login method. The default for controller methods annotated with #RequestMapping is HTTP GET so the login method will not be called when you submit the form.
Problem 6: The file index.jsp seems to be redundant as its sole purpose is to redirect to a different URL on the same server. You will be better off with the following simplified controller code:
#Controller
public class CommonController {
#RequestMapping("/")
public String loadLoginPage(Model model) {
model.addAttribute("Login", new Login()); // Or something like this, which represents the actual model object that should collect the login information.
return "login";
}
#RequestMapping(method = RequestMethod.POST, value="/login")
public String login(Login login) {
// Use the login object to authenticate the user.
return "abc";
}
}
I would also recommend that you keep the lines
<context:component-scan base-package="com.booksworld.controllers" />
<context:annotation-config />
<mvc:annotation-driven />
in the file dispatcher-servlet.xml as these lines are specific to your presentation layer.