I am having a jsp page from which i have to pass the control to the next page.
And i am using Multiaction Controller for that but its giving me an error 404.
My JSP File is
<form id="form1" name="form1" method="post" action="registerSuccessControl.htm" commandName="register" >
<strong> <label> <label> <label>
<div align="center">Registeration</div>
</label></strong> <label></label>
<h1> </h1>
<p>
First Name <input type="text" name="textfield" accesskey="1"
tabindex="1" /> <label>
Last Name</label> <strong> <input type="text"
name="textfield3" />
</strong>
</p>
and this is my Controller
#RequestMapping("/registerSuccessControl.htm")
public ModelAndView registerSuccessControl(#ModelAttribute("register") Register register,BindingResult brResult,HttpServletRequest request,HttpServletResponse response) throws Exception {
System.out.println("RegisterSuccesssControl called");
//logger.debug("Registration Page Accessed at "+new Date());
System.out.println("I am In registerSuccess");
RegistrationValidator uValidator=new RegistrationValidator();
uValidator.validate(register,brResult);
HashMap<String, BindingResult> resultMap = new HashMap<String, BindingResult>();
if(brResult.hasErrors()){
resultMap.put("errors", errors);
return new ModelAndView("Register",resultMap);
}
else
return new ModelAndView("Firm");
}
I have other request handled in same controller and its working fine, but its not working for this link.
Related
I want to design a quick registration page which is placed at the footer when I submit the field, It is showing some error "Request method POST not supported". Someone, please help me to come out of this error.
I have modified the attribute of the form commandName as modelAttribute, but still, the error exists.
This is jsp front end.
<%# tag body-content="empty" trimDirectiveWhitespaces="true"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:url value="/setSubscribe" var="subscribe"></c:url>
<form:form action="${subscribe}" method="post" modelAttribute="subscribeForm">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<label class="form-check-label radio-inline">
<input type="radio" class="form-check-input" value="gender" name="gender" value="Male"/> Male
</label>
<label class="form-check-label radio-inline">
<input type="radio" class="form-check-input" value="gender" name="gender" value="Female"/> Female
</label>
<br></br>
<div class="row">
<div class="col-sm-3">
<input class="form-control" name="firstName" placeholder="First Name"></input>
</div>
<div class="col-sm-3">
<input class="form-control" name="lastName" placeholder="Last Name"></input>
</div>
<div class="col-sm-3">
<input class="form-control" name="email" placeholder="Your Email Address"></input>
</div>
<div class="col-sm-3">
<button type="submit" class="btn btn-primary">SUBSCRIBE</button>
</div>
</div>
</form:form>
Here is my controller.
#RequestMapping(value = "/setSubscribe", method = RequestMethod.POST)
private String doSubscribe(#ModelAttribute("subscribeForm") final SubscribeForm form)
{
final RegisterData registerData = new RegisterData();
registerData.setFirstName(form.getFirstName());
registerData.setLastName(form.getLastName());
registerData.setSex(form.getGender());
registerData.setLogin(form.getEmail());
final CerCustomerFacadeImpl customerFacadeImpl = new CerCustomerFacadeImpl();
try
{
customerFacadeImpl.newCerRegister(registerData, true);
}
catch (final Exception e)
{
e.printStackTrace();
}
return "";
}
It should have to behave according to the business which has been mentioned in the controller.
Write your controller method with #ResponseBody annotation and consumes property of #RequestMapping annotation, as following:
#RequestMapping(value = "/setSubscribe", method = RequestMethod.POST, consumes = "application/json")
#ResponseBody
private String doSubscribe(#ModelAttribute("subscribeForm") final SubscribeForm form)
{
return "";
}
I get the below error in my spring4 + thymeleaf3 application when I try to show validation errors in my form template.
Neither BindingResult nor plain target object for bean name '#fields' available as request attribute
My form is as below.
<form th:action="#{/user/save}" method="post" th:object="${user}">
<ul th:if="${#fields.hasErrors()}">
<li th:each="err : ${#fields.errors('*')}" th:text="${err}"></li>
</ul>
<div>
<label>Name</label>
<div>
<input type="text" th:field="*{firstName}" placeholder="First Name">
<input type="text" th:field="*{lastName}" placeholder="Last Name">
<div th:if="${#fields.hasErrors('firstName')}" th:errors="${#fields.errors('firstName')}"></div>
<div th:if="${#fields.hasErrors('lastName')}" th:errors="${#fields.errors('lastName')}"></div>
</div>
</div>...
The form is rendered well for the following get request mapping.
#GetMapping("/create")
public String create(ModelMap model) {
model.put("user", new User());
return VIEW_DIR.concat("form");
}
But it gives the above error when the form is submitted with some invalid fields to the following method.
#PostMapping("/save")
public String save(#Valid User user, BindingResult bindingResult, ModelMap model) {
if(bindingResult.hasErrors()) {
return VIEW_DIR.concat("form");
}
userService.save(user);
return "redirect:list";
}
Can you please show me where the error is.
You are setting wrong values for th:errors inside your form element div. th:errors should contain field name. Update your form with this:
<div>
<input type="text" th:field="*{firstName}" placeholder="First Name">
<input type="text" th:field="*{lastName}" placeholder="Last Name">
<div th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}"></div>
<div th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}"></div>
</div>
I have controller class with following request mapping method.
appStart() method is responsible for redirecting user to login.html and
logout() is responsible for invalidating session and redirecting user
back to login.jsp
if I remove #ModelAttribute from their parameter then these two methods are throwing exception, is there any hack to get these methods working without modelattribute?
controller methods.
#RequestMapping(value="/",method=RequestMethod.GET)
public String appStart(#ModelAttribute("tempAdmin") Admin tempAdmin) {
return "login.jsp";
}
#RequestMapping(method = RequestMethod.POST,name="doLogin")
public ModelAndView doLogin(#ModelAttribute("tempAdmin") Admin tempAdmin, HttpServletRequest request) {
ModelAndView mvc = new ModelAndView();
/*
Buisness logic
*/
mvc.setViewName("home.jsp");
return mvc;
}
#RequestMapping("doLogout")
public String logout(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if(session != null){
session.invalidate();
}
return "login.jsp";
}
login.jsp
<form:form action="doLogin" modelAttribute="tempAdmin" cssClass="form-horizontal">
<div class="form-group">
<label for="username" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<form:input cssClass="form-control" path="adminId" placeholder="username" />
</div>
</div>
<div class="form-group">
<label for="passwd" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<form:password path="password" cssClass="form-control" id="passwd" placeholder="password" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</div>
</form:form>
stacktrace.
Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'tempAdmin' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
I will tell you how to change your controller, to avoid binding result problem. Try this :
#RequestMapping(method = RequestMethod.POST,name="doLogin")
public String doLogin(#ModelAttribute("tempAdmin") Admin tempAdmin, HttpServletRequest request,Model model) {
model.addAttribute("tempadmin",new Admin());
// business logic
return "home";
}
Try this out, and if you have any other classes, then add the model.addAttribute for that as well. Can you post your JSP too?
When I put the code inside the form:form tag on view cadastro.jsp:
<div class="form-group">
<label for="nome" class="col-sm-2 control-label"> name Project: </ label>
<div class="col-sm-10">
<input for="nome" class="form-control" />
<form:errors path="nome" />
</div>
</div>
Its works
but when i put
<div class="form-group">
<label for="nome" class="col-sm-2 control-label"> Nome do Projeto: </ label>
<div class="col-sm-10">
<form:input cssClass="form-control" path="nome" />
<form:errors path="nome" />
</div>
</div>
not work because the form: input tag
Error:
HTTP Status 500 - An exception occurred processing JSP page /WEB-INF/view/cadastro.jsp at line 34
ProjetroController
#RequestMapping(value = "/novoProjeto", method = RequestMethod.POST)
public String adicionarProjeto(#Valid #ModelAttribute("projeto") Projeto projeto, BindingResult result) {
if(result.hasErrors()) {
return("cadastro");
}
projeto.setStatus("NOVO");
this.pc.salvar(projeto);
return "redirect:/listar";
}
I think you need to add a <form:form> tag around your form, as follows:
<form:form>
<div class="form-group">
<label for="nome" class="col-sm-2 control-label"> Nome do Projeto: </ label>
<div class="col-sm-10">
<form:input cssClass="form-control" path="nome" />
<form:errors path="nome" />
</div>
</div>
</form:form>
In Spring official documentation, it states that:
All the other tags in this library are nested tags of the form tag.
you have to import spring form taglib inorder to use elemnets of spring form like:
add this in top of your jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
then, you can use like:
<form:form id="myForm" method="post" action="/someAction" modelAttribute="formBean">
<form:label path="name"/>
<form:input path="name"/>
<form:form>
and you have add modelAttribute/command object in controller like:
#RequestMapping(value="/someUrl", method=RequestMethod.GET)
public String showForm(Model model){
model.addAttribute("formBean", new FormBean());
return "someViewName";
}
and FormBean class looks like:
public class FormBean {
private String name;
public FormBean(){} //default constructor
//getter and setter for name
}
these are my controllers:
#RequestMapping(value="/requestBooking", method = RequestMethod.GET)
#ModelAttribute("booking")
public ModelAndView requestBooking(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ModelAndView view = new ModelAndView("requestBooking");
OAuthAuthenticationToken token = (OAuthAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
if(token.getUserProfile().getAttributes().get("email").toString().matches(".*#nisum.com")==false){
SecurityContextHolder.clearContext();
return new ModelAndView("redirect:/j_spring_security_logout?redirectTo=/rejected");
}
VacationBooking booking=new VacationBooking();
String email=token.getUserProfile().getAttributes().get("email").toString();
User user=userImp.getUserByMail(email);
booking.setUser(user); //setting user
System.out.println(booking.getBookingId() + " - " + booking.getUser().getUserId());
view.addObject("booking", booking);
view.addObject("user", token.getUserProfile().getAttributes().get("email"));
return view;
}
#RequestMapping(value="/requestBooking/process", method=RequestMethod.POST)
public ModelAndView addBooking(#ModelAttribute("booking") VacationBooking booking , BindingResult result) {
/* val.validate(booking, result);*/
/* if(result.hasErrors()){
System.out.println("Error!!!!");
ModelAndView modelAndView = new ModelAndView("requestBooking");
return modelAndView;
}else{ */
SimpleMailMessage email2 = new SimpleMailMessage();
SimpleMailMessage emailPm = new SimpleMailMessage();
emailPm.setTo(booking.getUser().getMail()); //error here null value
email2.setTo(booking.getUser().getManager().getMail()); //error here, null value
email2.setSubject("Vacation Request");
emailPm.setSubject("Vacation Request");
emailPm.setText("<h3>Vacation Request<h3>\nThe employee has requested Vacation days between for leave. \n \n Please take action to approve or reject this request. \n \n To review, approve or reject the request, log into SaS, click Vacation Booking and click in Pending Approval link. \n \nNOTE: This is an Automated E-mail generated from the SaS mail process. Please do not reply to this E-mail. Vacation days Request Pending Approval");
email2.setText("<h3>Vacation Request<h3>\nYour vacation days request has been routed to your manager for approval. \n \nNote: If these dates should change, it is your responsibility to notify the appropriate people or withdraw your request in case you won't take those days.\n \nTo review, withdraw or modify your request, log into SaS, click Vacation Booking and check the current status or your Request. \n \nNOTE: This is an Automated E-mail generated from the SaS mail process. Please do not reply to this E-mail. Vacation days Request Routed for Approval");
mailSender.send(email2);
mailSender.send(emailPm);
System.out.println(booking.getFromDate());
bookingService.saveVacationBooking(booking);
ModelAndView modelAndView = new ModelAndView("myBookings");
String message = "the vacation booking was added!";
modelAndView.addObject("message", message);
return modelAndView;
}
and this is my view:
<!doctype html>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html class="no-js" lang="en">
<head>
<title>Vacation booking</title>
<link href="/vacation/resources/bootstrap-3.0.3/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<!--Booking Form-->
<body>
<jsp:include page="../../templates/PageHeader.jsp" />
<form:form method="POST" style="width:800px;" commandName="booking" action="${pageContext.request.contextPath}/requestBooking/process" class="form-horizontal">
<div class="container">
<div class="row">
<div clas="col-md-12"><h4>Vacation Booking Form</h4></div>
<hr>
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">From:</label>
<div class="col-sm-6">
<form:input type="date" path="fromDate" class="form-control"></form:input>
<form:hidden path="user.userId" class="form-control"/>
<form:hidden path="bookingId" class="form-control"/>
<!--<input type="date" class="form-control"/> -->
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">To:</label>
<div class="col-sm-6">
<form:input type="date" path="toDate" class="form-control"></form:input>
<!-- <input type="date" class="form-control"/> -->
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Comments:</label>
<div class="col-sm-6">
<form:textarea path="comments" rows="4" class="form-control" placeholder="Fill this field if you have any comments related to your request"/>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-sm-6">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</div>
</form:form>
<jsp:include page="../../templates/PageFooter.jsp" />
<script src="/vacation/resources/js/jquery-2.0.3.min.js" type="text/javascript"></script>
<script src="/vacation/resources/bootstrap-3.0.3/js/bootstrap.min.js" type="text/javascript"></script>
</body>
</html>
When I try to do booking.getUser().getMail() I get null. It is like my "booking" object is null in my post method. Any idea of how I can get my booking with the user object inside in my post controller, so I can call the getUser() method?