Post function not binding in Spring 3.0 - java

This may have been asked many times but I have not been able to find a concrete answer over last two days. Using Spring 3.2.
I have two methods. One is for form creation and the other is for the form to post. Form creation works fine. But when I try to post/submit the form, I don't see the log statement getting executed in the login() method and I get a 404 error HTTP Status 404 - /sample/login.
I think the problem is the form cannot submit to URL but I don`t know how to fix the mapping to make it work.
If there are any other files that are needed please let me know. BTW following example from sprin/mvc-basic and spring/petclinic
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 example.domain.User;
import example.service.UserValidator;
#Controller
#RequestMapping(value="/login")
public class LoginFormController {
protected final Log logger = LogFactory.getLog(getClass());
#RequestMapping(method=RequestMethod.GET)
public String loadForm(Model model) {
logger.info("LoginFormController login");
model.addAttribute("user", User.getUserInstance());
return "login";
}
#RequestMapping(method=RequestMethod.POST)
public String login(#ModelAttribute User user, BindingResult result) {
logger.info("post");
new UserValidator().validate(user, result);
if (result.hasErrors()) {
return "login";
} else {
logger.info("Email Id: " + user.getEmailId());
//this.clinic.storeOwner(owner);
//status.setComplete();
return "redirect:/landing/" + user.getEmailId();
}
}
}
login.jsp
<%# include file="/WEB-INF/jsp/include.jsp"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title><fmt:message key="title" /></title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h1>
<fmt:message key="login.heading" />
</h1>
<form:form method="post" modelAttribute="user" action="login">
<table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5">
<tr>
<td align="right" width="20%"><form:label for="emailId" path="emailId" cssErrorClass="error">Email ID:</form:label></td>
<td width="20%"><form:input path="emailId" /></td>
<td width="60%"><form:errors path="emailId" cssClass="error" /></td>
</tr>
<tr>
<td align="right" width="20%"><form:label for="password" path="password" cssErrorClass="error">Password:</form:label></td>
<td width="20%"><form:input path="password" /></td>
<td width="60%"><form:errors path="password" cssClass="error" /></td>
</tr>
</table>
<br>
<input type="submit" align="center" value="Login">
</form:form>
Signup
</body>
</html>
name-servlet.xml
<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="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</bean>
Your help appreciated.

Seems you have mapped *.htm URL to DispatcherServlet (Guessing from /signup.htm). Change the action in your form tag to login.htm instead of login:
<form:form method="post" modelAttribute="user" action="login.htm">

Related

HTTP Status 405 - Request method 'POST' not supported Spring Security Java Config

Hello I am facing the 'HTTP Status 405 - Request method 'POST' not supported'
exception when trying to do login using spring security.
Following is my code :
pgLogin.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
<script type="text/javascript">
function focusOnLoad() {
document.getElementById("username").focus();
}
</script>
</head>
<body onload="focusOnLoad()">
<div align="center">
<c:if test="${not empty error}">
<div>
<p style="color: red;">${error}</p>
</div>
</c:if>
<c:if test="${not empty message}">
<div>
<p style="color: red;">${message}</p>
</div>
</c:if>
<c:url var="loginUrl" value="/login" />
<form action="${loginUrl}" method="post">
<div>
<table>
<tr>
<td><label for="username">Email</label></td>
<td><input type="text" id="username" name="email" placeholder="Enter Email" required></td>
</tr>
<tr>
<td><label for="password">Password</label></td>
<td><input type="password" id="password" name="password" placeholder="Enter Password" required></td>
</tr>
</table>
</div>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<div>
<input type="submit" value="Log In">
</div>
</form>
</div>
</body>
</html>
DesertLampSecurityConfiguration.java
package co.in.desertlamp.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class DesertLampSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {
authenticationMgr.inMemoryAuthentication()
.withUser("subodh.ranadive#desertlamp.com")
.password("Dlpl123#")
.authorities("ROLE_SUPER_USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/home").access("hasRole('ROLE_SUPER_USER')")
.and()
.formLogin().loginPage("/loginPage")
.defaultSuccessUrl("/homePage")
.failureUrl("/loginPage?error")
.usernameParameter("email").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/loginPage?logout");
}
}
DefaultController.java
package co.in.desertlamp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class DefaultController {
#RequestMapping(value = { "/"}, method = RequestMethod.GET)
public ModelAndView welcomePage() {
ModelAndView model = new ModelAndView();
model.setViewName("common/pgDefault");
return model;
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView loginPage(#RequestParam(value = "error",required = false) String error) {
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid Email OR Password");
}
model.setViewName("common/pgLogin");
return model;
}
#RequestMapping(value = { "/home"}, method = RequestMethod.GET)
public ModelAndView homePage() {
ModelAndView model = new ModelAndView();
model.setViewName("common/pgWelcome");
return model;
}
}
Change your config as following to match your method handlers:
...
.formLogin().loginPage("/login")
.defaultSuccessUrl("/home")
.failureUrl("/login?error")

Spring MVC Add and Modification doesn't work properly as I want

Currently in my project, addEmployee.jsp show properly when "Add Employee" or "Edit" is clicked, but when I try to hit submit button in "Add Employee" page, page return "Http status 500 Request processing failed; nested exception is java.lang.NullPointerException", or when I try to hit submit button in "Add Employee" page for update employee info, I will get "HTTP Status 405 - Request method 'POST' not supported"
The way I want is when I add a new employee or update the existing employee info, I will still using addEmployee.jsp page. If it is add a new one, all the field will be empty, otherwise, all the field will contain the existing information for update.
Here is the code for employee.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee List</title>
</head>
<body>
<div align="center">
<h1 style="background-color: lightgreen; color: darkgreen">Employee
Page</h1>
<table align="center" width="80%" cellspacing="0" cellpadding="5">
<tr>
<td align="center">
<table cellspacing="0" cellpadding="6" border="0" width="100%">
<tr bgcolor="lightblue">
<td align="left"><a
href="${pageContext.request.contextPath}/employee/addEmployee"
style="background-color: lightblue;"> Add Employee </a></td>
</table>
</td>
</tr>
<tr>
<td>
<table cellspacing="0" cellpadding="6" border="1" width="100%">
<tr>
<td colspan="8"
style="background-color: lightblue; color: darkgreen; font-size: 16pt"
align="center">Employee List</td>
</tr>
<tr bgcolor="grey" style="color: white">
<th>No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Job Title</th>
<th>Department</th>
<th>Salary</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach var="employee" items="${employeesList}"
varStatus="status">
<tr bgcolor="lightyellow">
<td><b>${status.index + 1}</b></td>
<td>${employee.firstName}</td>
<td>${employee.lastName}</td>
<td>${employee.jobTitle}</td>
<td>${employee.department}</td>
<td>${employee.salary}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
</td>
</tr>
</table>
</div>
</body>
</html>
And Here is the code for addEmployee.jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#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>Add Employee</title>
</head>
<body>
<div align="center">
<h1 style="background-color: lightgreen; color: darkgreen">Add
New Employee Page</h1>
<table width="80%" align="center">
<tr bgcolor="lightblue">
<td align="left"><a href="listEmployees"
style="background-color: lightblue;">List Employee</a></td>
</table>
</div>
<br />
<div align="center">
<table cellspacing="0" cellpadding="6" border="1" width="80%">
<tr>
<td colspan="8"
style="background-color: lightblue; color: darkgreen; font-size: 16pt"
align="center">Employee Information</td>
</tr>
<tr>
<td><form:form method="POST" action="updateEmployee">
<table width="100%">
<tr>
<td><form:label path="firstName">First Name</form:label></td>
<td align="left" width="70%"><form:input path="firstName" /></td>
</tr>
<tr>
<td><form:label path="lastName">Last Name</form:label></td>
<td align="left" width="70%"><form:input path="lastName" /></td>
</tr>
<tr>
<td><form:label path="jobTitle">Job Title</form:label></td>
<td align="left" width="70%"><form:input path="jobTitle" /></td>
</tr>
<tr>
<td><form:label path="department">Department</form:label></td>
<td align="left" width="70%"><form:input path="department" /></td>
</tr>
<tr>
<td><form:label path="salary">Salary</form:label></td>
<td align="left" width="70%"><form:input path="salary" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form></td>
</tr>
</table>
</div>
</body>
</html>
Here is the code for EmployeeController.java
package com.vincent.springmvc.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.vincent.springmvc.model.Employee;
import com.vincent.springmvc.service.EmployeeService;
#Controller
#RequestMapping("/employee")
public class EmployeeController {
//Logger file
private static Logger logger = LoggerFactory.getLogger(EmployeeController.class);
#Autowired
private EmployeeService employeeService;
#RequestMapping(method = RequestMethod.GET)
public String welcomeEmployee(ModelMap model){
model.addAttribute("name", "Hello World!");
model.addAttribute("greetings", "Welcome to Spring MVC");
return "hello";
}
#RequestMapping(value = "/listEmployees", method = RequestMethod.GET)
public String listEmployees(ModelMap model){
model.addAttribute("employeesList", this.employeeService.listEmployee());
return "employee";
}
#RequestMapping(value = "/addEmployee", method = RequestMethod.GET)
public ModelAndView addEmployee(ModelMap model){
return new ModelAndView("addEmployee", "command", new Employee());
}
#RequestMapping(value = "/updateEmployee", method = RequestMethod.POST)
public String updateEmployee(#ModelAttribute("employee") Employee employee, ModelMap model){
if(employee.getId() == 0)
this.employeeService.insertEmployee(employee);
else
this.employeeService.updateEmployee(employee);
model.addAttribute("employeesList", this.employeeService.listEmployee());
return "employee";
}
#RequestMapping(value = "/delete/{empId}", method = RequestMethod.GET)
public String deleteEmployee(#PathVariable("empId") Integer empId, ModelMap model){
this.employeeService.deleteEmployee(empId);
model.addAttribute("employeesList", this.employeeService.listEmployee());
return "employee";
}
#RequestMapping(value = "/edit/{empId}", method=RequestMethod.GET)
public ModelAndView editEmployee(#PathVariable("empId") int id, ModelMap model){
return new ModelAndView("addEmployee", "command", this.employeeService.getEmployeeById(id));
}
}
Here is the project structure
Project Structure
and the rest of the code you can find in https://github.com/zhengye1/SpringMVC
Thank you for the help
Kind of resolve for now.... but seems like not a very good idea, it is time to looking for good advice..
The way I fix is, in my controller class, I change the annotation in updateEmployee with following annotation #RequestMapping(value = {"/updateEmployee", "/edit/updateEmployee"}, method = RequestMethod.POST). This because when I tracing the log, I realize somehow the server try to mapping the page called edit/updateEmployee, originally is not exists, that is why it raising the 504 error for update.
For adding issue is causing by the form, since the form return the null id, therefore when I try to compare the null object with 0, it raise the null pointer exception. The way I fix is, change that line to if (employee.getId() == null), and also in addEmployee.jsp page, I add the this line to my form, <form:hidden path="id" />. That is resolve the issue.

Spring MVC second Post method #ModelAttribute is null

I have a form that has two buttons, a submit button and an update button.
Here is the JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- Bootstrap core CSS !-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- Custom scripts/styles for this page !-->
<script type="text/javascript" src="${pageContext.request.contextPath}/static/script/jquery.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/script/script.js"></script>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/style.css" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test</title>
</head>
<body>
<!-- General Information Form -->
<form:form id="form" method="POST" action="${pageContext.request.contextPath}/create" modelAttribute="task">
<div id="general">
<table style="width: 224px;">
<tr>
<td colspan="2"><form:select id="systemType" path="systemType" items="${systemTypes}" /></td>
</tr>
<tr>
<td id="buffer"></td>
</tr>
<tr>
<td colspan="2"><form:select id="userName" path="user.fullName" items="${userFullNames}" /></td>
</tr>
<tr>
<td id="buffer"></td>
</tr>
<tr>
<td style="width: 50%;"><label for=line><b>Line: </b></label></td>
<td><form:select path="location.line" items="${lines}" id="line"/></td>
</tr>
<tr>
<td id="buffer"></td>
</tr>
<tr>
<td style="width: 50%;"><label for=position><b>Position: </b></label></td>
<td><form:select path="location.position" items="${positions}" id="position" /></td>
</tr>
<tr>
<td id="buffer"></td>
</tr>
<tr>
<td colspan="2">
<input id="submitButton" type="submit" name="submit" value=Submit />
<input style="display:none;" id="updateButton" type="submit" name="update" value="Update" />
<input id="cancel" style="float: right;" type="Reset" value="Cancel" />
</td>
</tr>
</table>
</div>
</form:form>
</body>
</html>
Here is my controller:
#Controller
#RequestMapping("/")
public class HomeController {
private TaskService taskService;
#Autowired
public void setTaskService(TaskService taskService) {
this.taskService = taskService;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public String initForm(Model model, HttpServletRequest request) {
Task task = new Task();
model.addAttribute("task", task);
return "home";
}
#RequestMapping(value="/create", params="submit", method = RequestMethod.POST)
public String submitForm(#ModelAttribute("task")Task task,BindingResult result, Model model) {
taskService.create(task);
return "redirect:/";
}
#RequestMapping(value="/create", params="update", method = RequestMethod.POST)
public String updateForm(#ModelAttribute("task")Task task, BindingResult result, Model model) {
System.out.println("Updating: " + task.toString());
taskService.update(task);
return "redirect:/";
}
The idea being that hitting the submit button will make a new item, and the update button will edit an existing one. The two .POST methods have different parameters specified to distinguish them.
The submit button is working as expected. However when the update button is pressed a Task object is delivered to the updateForm controller method - but all of its fields are null.
I am not sure why the form is binding the fields to the Task correctly on the submit method, but seemingly creating a new Task and not binding it at all in the update method.
I am inclined to just combine these methods into a single controller method and use some Java logic to determine whether to submit/update based on the parameter - but am curious as to what I'm missing and why this doesn't work.
Ok, I feel very stupid. This was not a SpringMVC issue at all. The problem was caused by a Jquery method that was disabling a part of the form. This gave the appearance that the form was not binding, but actually it was just binding to null values.

Data not get bind with the Binding result in Spring mvc

I have been facing this problem for the past 2 days. Although I have gone through so many post I did not find a solution for my question.
Actually I was trying to validate my login form using Spring validations but even if I had given some wrong inputs it is not showing me any error , it accepts my every input.
For example, I have used #NotEmpty and #Email annotations for email it even accepts my plain inputs like "user". It has to throw the error as "Invalid email format" but this errors are not get bind into my Bindingresult.
My Controller : ContactController.java
import java.util.ArrayList;
import java.util.List;
import net.viralpatel.spring3.form.loginform;
import javax.validation.Valid;
import net.viralpatel.spring3.form.Contact;
import net.viralpatel.spring3.form.ContactForm;
import net.viralpatel.spring3.form.loginform;
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;
import org.springframework.web.servlet.ModelAndView;#Controller{
#RequestMapping(value = "/get", method = RequestMethod.GET)
public String get(ModelMap model) {
loginform ud = new loginform();
ud.setUser("");
ud.setEmail("");
model.addAttribute("lform",ud);
return "login";
}
#RequestMapping(value="/login",method=RequestMethod.POST)
public String loginCheck(#ModelAttribute("lform") #Valid loginform lform, BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "login";
} else {
model.addAttribute("lfobj", lform);
return "success";
}
}
My login.jsp file :
<form:form action="login.html" commandName="lform">
<table>
<tr>
<td><font face="verdana" size="2px">User</font></td>
<td>:</td>
<td>
<font face="verdana" size="2">
<form:input path="user" /> <form:errors path="user"></form:errors>
</font>
</td>
</tr>
<tr>
<td><font face="verdana" size="2px">Email</font></td>
<td>:</td>
<td>
<font face="verdana" size="2">
<form:input path="email" /> <form:errors path="email"></form:errors>
</font>
</td>
</tr>
<tr>
<td><font face="verdana" size="2px">Phone</font></td>
<td>:</td>
<td>
<font face="verdana" size="2">
<form:input path="phone" /> <form:errors path="phone"></form:errors>
</font>
</td>
</tr>
<tr>
<td><font face="verdana" size="2px">Blog</font></td>
<td>:</td>
<td>
<font face="verdana" size="2">
<form:input path="blog" /> <form:errors path="blog"></form:errors>
</font>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form:form>
My loginform.java :
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.URL;
import org.springframework.validation.BindingResult;
public class loginform{
#NotEmpty
private String user;
#NotEmpty
#Email
private String email;
#NotEmpty(message = "Phone should not be blank.")
#Size(min = 10,max = 10)
private String phone;
#NotEmpty(message = "Enter your blog URL")
#URL
private String blog;
//get & set methods
}
My spring-servlet.xml :
<context:annotation-config />
<context:component-scan base-package="net.viralpatel.spring3.controller" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="props" />
</bean>
This is my first program in Spring validation so may be I hit low but kindly give any solutions for my issue.
Add this to your spring config:
<mvc:annotation-driven/>
This will enable Bean Validation.
Document: Reference
Your jsp form tag is missing the http method attribute method="POST (without this attribute for form data are submit an http GET, and this is bound to the request handler method):
<form:form method="POST" action="login.html" commandName="lform">...

Bring jsp form page after previous submit (java spring)

New to spring (and HTML/forms etc for that matter) and been stuck on this problem for long time.
So I want to have a front page where you enter a username. Then click submit, and takes you to a dashboard (ultimately, there will be a page with a list of connected users, a load of submit buttons to send predefined messages out - using qpid jms).
The front page is fine, but I click submit and I get an error (java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'dashboardModel' available as request attribute)
This only happens if I have a form:form in dashboard.jsp. I literally have no idea how to fix this and have tried everything I can find. My code is simple, and is just modified from a tutorial, so here it is:
login.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Login Page:</h2>
<form:form modelAttribute="loginModel" method="POST"
action="/HelloWeb/dashboard">
<table>
<tr>
<td><form:label path="username">Name</form:label></td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
Login.java
package com.tutorialspoint;
public class Login {
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
LoginController.java
package com.tutorialspoint;
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 org.springframework.ui.ModelMap;
#Controller
public class LoginController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login() {
return new ModelAndView("login", "loginModel", new Login());
}
#RequestMapping(value = "/loggedIn", method = RequestMethod.POST) //never actually used
public String loggedIn(#ModelAttribute("Login") Login login, ModelMap model) {
model.addAttribute("username", login.getUsername());
return "dashboard";
}
}
dashboard.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>DASHBOARD</title>
</head>
<body>
<table>
<tr>
<td>Dashboard</td>
<td>DASHBOARD</td>
</tr>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>variable</td>
<td>${variable}</td>
</tr>
</table>
<form:form modelAttribute="dashboardModel" method="POST"
action="/HelloWeb/dashboard">
<table>
<tr>
<td><form:label path="variable">Name</form:label></td>
<td><form:input path="variable" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
Dashboard.java
package com.tutorialspoint;
public class Dashboard {
private String variable;
public String getVariable() {
return variable;
}
public void setVariable(String variable) {
this.variable = variable;
}
}
DashboardController.java
package com.tutorialspoint;
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 org.springframework.ui.ModelMap;
#Controller
public class DashboardController {
#RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView dashboard() {
return new ModelAndView("dashboard", "dashboardModel", new Dashboard());
}
#RequestMapping(value = "/dashboard", method = RequestMethod.POST)
public String addVariable(#ModelAttribute("SpringWeb") Dashboard dashboard,
ModelMap model) {
model.addAttribute("variable", dashboard.getVariable());
return "dashboard";
}
}
Thanks for your time.
I think the problem is here:
<form:form modelAttribute="loginModel" method="POST" action="/HelloWeb/dashboard">
^^^^^^^^^^
and here:
#RequestMapping(value = "/loggedIn", method = RequestMethod.POST) //never actually used
public String loggedIn(#ModelAttribute("Login") Login login, ModelMap model) {
^^^^^
The modelAttribute value on form:form element and the #ModelAttribute argument should be the same.
I mean:
#RequestMapping(value = "/loggedIn", method = RequestMethod.POST) //never actually used
public String loggedIn(#ModelAttribute("loginModel") Login login, ModelMap model) {
^^^^^^^^^^
Edit:
Also, the form part should be like this:
<form:form modelAttribute="dashboardModel" method="POST" action="/loggedIn.htm">
<table>
<tr>
<td>Name</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>

Categories

Resources