how to show fetched values from database in spring <form:input>? - java

I need to show the fetched values from database which are stored in an arraylist using spring form:input tag. However i found that the 'value' attribute isn't supported. Please help!

I guess you are expecting something like this.
//Assumes you have the following in your class
public class Students{
private String name;
private List<String> Departments;
/* getters/setters */
}
In the HTML would be.
<form:input path="departments[0]" />
<form:input path="departments[1]" />
For more details about click http://www.javacodegeeks.com/2013/07/spring-mvc-form-handling-vol-5-select-option-options-tags.html

Please first retrieve the list from the datebase and set the list on the model attribute in the controller see the example set the
#Controller
public class UserController {
#RequestMapping(method = RequestMethod.GET)
public String userHome(Model model, EventBean event, UserService userService,ImageBean image)
{
List<Event> events = userService.viewNews(); //retrieve the list from datebase
model.addAttribute("event", event); //add bean object
model.addAttribute("events", events); //add list in model attribute
return "home";
}
}
your jsp page
<form:form modelAttribute="event"> <!--set the model attribute here -->
<form:input path="news" value="${events.get(0).news}" />
</form:form>

This is my code,please have a look and say what i might be doing wrong,
JAVA
public ModelAndView userEditProfile(#ModelAttribute("userDetails") UserFormbean registration,BindingResult result,HttpServletRequest request){
ModelAndView mav=null;
HttpSession httpSession=null;
List userProfileList=new ArrayList();
httpSession=request.getSession();
if (httpSession != null) {
UserFormbean formbean=(UserFormbean)httpSession.getAttribute("UserRegistrationFormBean");
userProfileList= userRegistrationService.getUserProfileInfo(formbean);
mav=new ModelAndView("EditProfile");
mav.addObject("userProfileInfoList", userProfileList);
}
return mav;
}
JSP::
-----
<c:if test="${not empty userProfileInfoList}">
<c:forEach var="temp" items="${userProfileInfoList}">
<div>
<form:label path="userRegistration.email"><spring:message code="label.email"/></form:label>
<form:input path ="userRegistration.email" value="${temp.get(0).UserRegistration.email}"/>
<form:errors path="userRegistration.email"/>
</div>
<div>
<form:label path="userRegistration.firstName"><spring:message code="label.firstname"/></form:label>
<form:input path ="userRegistration.firstName" value="${temp.get(0).UserRegistration.firstName}"/>
<form:errors path="userRegistration.firstName"/>
</div>
<div>
<form:label path="userRegistration.lastName"><spring:message code="label.lastname"/></form:label>
<form:input path ="userRegistration.lastName" value="${temp.get(0).UserRegistration.lastName}"/>
<form:errors path="userRegistration.lastName"/>
</div>
</c:forEach>
</c:if>

Related

Spring Boot Forms; hiding the path value and showing placeholder

I am having a small issue with Spring Boot forms displaying the information of the path value instead of the placeholder once you get to the editProfile.jsp. I want the input field to look like this;
Edit Profile Page instead of this Wrong Edit Profile. I do not want my users to have to click, select and delete the auto completed value. I want it to show the placeholder only and allow them to overwrite what is shown with ease.
This is the editProfile.jsp
<%--#elvariable id="editProfile" type=""--%>
<form:form method="POST" modelAttribute="editProfile">
<div class="MyForm form-group">
<h1>Edit Profile</h1>
<form:input type="email" class="MyInput" id="email" path="email" placeholder="${editProfile.email}" />
<form:button type="submit" class="from-control">Submit</form:button>
</div>
<div>
<img src="images/reg1.png" alt="picture">
</div>
</form:form>
</body>
</html>
This is the code specified in the Controller
#RequestMapping(value = "edit/{email}", method = RequestMethod.GET)
public String getEditUserData(#PathVariable("email") String email, Model model) {
AccountEntity accountInstance = accountRepo.findByEmail(email);
model.addAttribute("editProfile", accountInstance);
return "editProfile";
}
#RequestMapping(value = "edit/{email}", method = RequestMethod.POST)
public String enterEditUserData(#ModelAttribute("login") AccountEntity accountForm, #PathVariable("email") String email, Model model ) {
AccountEntity accountInstance = accountRepo.findByEmail(email);
accountInstance.setEmail(accountForm.getEmail());
accountRepo.save(accountInstance);
return "redirect:/login";
}
I have figured it out; You have to add a model of a new Entity, so the path variable does not fill in with the instance of the specific path value. Here is the new code, and compare it to the one I sent above.
#RequestMapping(value = "edit/{email}", method = RequestMethod.GET)
public String getEditUserData(#PathVariable("email") String email, Model model) {
AccountEntity accountInstance = accountRepo.findByEmail(email);
model.addAttribute("editProfile2", new AccountEntity());
model.addAttribute("editProfile1", accountInstance);
return "editProfile";
}
<%--#elvariable id="editProfile" type=""--%>
<%--#elvariable id="editProfile2" type=""--%>
<form:form method="POST" modelAttribute="editProfile2">
<div class="grid form-group">
<h1>Edit Profile</h1>
<form:input type="email" class="MyInput" id="email" path="email" placeholder='${editProfile1.email}' />
<form:button type="submit" class="from-control">Submit</form:button>
</div>

How to send data from jsp to controller in spring using form

How to send data from jsp to controller in spring using form ?
<form:form action="${searchUrl}" method="post">
<div class="form-group">
<label class="control-label"> search by ID </label>
<br>
<input type="text" id="ticketId" placeholder=" Enter ticket ID ">
</div>
</form:form>
Could not able to get ticketId using this method
You need to declare name attribute (name="ticketId") and access the same on the controller. Like below.
JSP:
<input type="text" name="ticketId" id="ticketId" placeholder=" Enter ticket ID">
Controller:
#RequestParam(value = "ticketId", required = false) String ticketId
I hope it is helpful to you, for me it is working fine.
If you want to use spring forms, make sure to follow the below steps :
Step:1.In the spring controller, you should return the bean object like below to respected JSP.
Class User {
private String ticketId;
// setter & getter
}
#RequestMapping(value = "/test", method = RequestMethod.GET)
public String init(Model model) {
model.addAttribute("msg", "Please Enter Your Login Details");
model.addAttribute("loginBean", new User());
return "login";
}
Step:2 add a model attribute and add taglib in the JSP page.
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<form:form action="${searchUrl}" method="post"
modelAttribute="loginBean">
<div class="form-group">
<label class="control-label"> search by ID </label>
<br>
<form:input type="text" id="ticketId" path = "ticketId"
placeholder=" Enter ticket ID " />
</div>
</form:form>
Step : 3
#RequestMapping(value = "/test", method = RequestMethod.Post)
public String init(Model model,
#ModelAttribute("user") User user,BindingResult
result) {
sout("user"+user);
return "home";
}

using search functionality in thymeleaf with request parameters

I have a page where I get a list of entries. Now, I want to be able to search from those list.
my current url for retrieving list is this /show/products. I want to add a search form in this page so that I can search with request parameter.
Yes, I can use ajax but I have to do it with request parameters.
So if I search for a product name, then - /show/products?name=someName
<form ui-jp="parsley" th:action="#{/show/products(name=${pName})}" th:object="${pName}" method="get">
<div class="row m-b">
<div class="col-sm-6">
Search by Name:
<input id="filter" type="text" th:field="*{pName}" class="form-control input-sm w-auto inline m-r"/>
<button class="md-btn md-fab m-b-sm indigo">
<i class="material-icons md-24"></i>
</button>
</div>
</div>
</form>
And this is what I tried in controller:
#GetMapping("/show/products")
public String getProduct(Model model,
#RequestParam(required = false) String name,
#ModelAttribute String pName) {
List<Product> products = this.productService.getAllProducts(name)
model.addAttribute("products", products);
return "show_product";
}
I am getting this error:
Neither BindingResult nor plain target object for bean name 'pName' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:897)
You are trying to use variable pName (Model attribute) as a form object.
In your view you are passing a model attribute to form like this th:object="${pName}" but instead you need to pass a form object.
A form object is not a class but rather a simple java object (POJO). You can think of form object as your form but on server side.
Before you can use form object in your view, you need to create it and add it to the Model.
you will define it like this
public class MyFormObject{
private String pName;
public String getPName(){
return pName;
}
public void setPName(String pName){
this.pName = pName;
}
}
now your controller method will become
#GetMapping("/show/products")
public String getProduct(Model model,
#ModelAttribute("myFormObject") MyFormObject myFormObject,
BindingResult result) {
List<Product> products = this.productService.getAllProducts(myFormObject.getPName());
model.addAttribute("products", products);
return "show_product";
}
Then you can pass the form object to your form like this
<form ui-jp="parsley" th:action="#{/show/products}" th:object="${myFormObject}" method="get">
<div class="row m-b">
<div class="col-sm-6">
Search by Name: <input id="filter" type="text" th:field="*{pName}" class="form-control input-sm w-auto inline m-r"/>
<button class="md-btn md-fab m-b-sm indigo"><i class="material-icons md-24"></i></button>
</div>
</div>
</form>
You need to read the documentation, all these are explained there in detail.

how to show validation error in jsp in spring mvc

I want to show validation error in my jsp page.
My object is:
public class MyObjectDTO{ #valid private TextDTO text1; #valid private TextDTO text2 }
public class TextDTO{ #NotBlank private String code;#NotBlank private String label;}
My controller:
#RequestMapping(value = "/create", method = RequestMethod.POST)
public String creationProjet(#Valid #ModelAttribute MyObjectDTO obj, BindingResult result,
Model model) {
if (result.hasErrors()) {
model.addAttribute("hasErrors", true);
return "create";
} else {
....
return "redirect:/list";
}
}
my jsp
<div class="col-md-6 form-group ${requestScope['org.springframework.validation.BindingResult.obj'].hasFieldErrors('text1') ? 'has-error' : ''}">
<label class="col-lg-3 control-label">my label</label>
<div class="col-lg-5">
<form:select class="form-control" name="type" path="text1.code" id="selectType">
<option value="">---------</option>
<c:forEach items="${types }" var="type">
<form:option value="${type.id }">
<c:out value=" ${type.code}"></c:out>
</form:option>
</c:forEach>
</form:select>
<form:errors path="text1.code" class="has-error error"></form:errors>
</div>
</div>
My controller redirects to the page create but the errors are not showing. In debug mode there is one error that indicates text1.code cannot be a blank.
In your Jsp page add following line
<div class="col-md-6 form-group ${requestScope['org.springframework.validation.BindingResult.obj'].hasFieldErrors('text1') ? 'hasErrors' : ''}">
or use hasFieldErrors() instead
<div class="col-md-6 form-group ${requestScope['org.springframework.validation.BindingResult.obj'].hasFieldErrors()}">
And About addAttributes("hasErrors",true), use addFlashAttribute() which is store in flashmap and Object (In your case Error Message will be alive when you navigate to create page or redirect between two controller.) Look at this for more
In your controller Add RedirectAttributes Object like this
#RequestMapping(value = "/create", method = RequestMethod.POST)
public String creationProjet(#Valid #ModelAttribute MyObjectDTO obj,
BindingResult result,
RedirectAttributes redirectAtt,
Model model) {
if (result.hasErrors()) {
redirectAtt.addFlashAttribute("hasErrors","ur message");//instead of true you can write your own message
return "create";
} else {
....
}
return "redirect:/list";
}
}
If you write your own message instead of true
<c:if test="${not empty hasErrors">
<p>${hasErrors}</p>
</c:if>
only you missing is put part to model map.You are putting only flag. But you need to put result.
if(result.hasErrors()){
mm.addAttribute("errors", result);
return "create";
}

Binding problems using Spring MVC

I am using Spring MVC 3.1 to develop a Java web app. I have a JSP that has two paired radio buttons, an entry field, and a dropdown select box. I need these values to be available to my mapped controller, via a model class' fields.
The security and URL mapping works fine, as I've seen in debugger before. The issue is that when I tried to get the JSP data values populating my model, I get an error:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'cccForm' available as request attribute
Here is part of my JSP:
<c:url var="cccUrl" value="/registers/default/ccPreauth/authorize" />
<div class="mainWrapper">
<form:form id="cccForm" action="${cccUrl}" method="post" modelAttribute="cccForm">
...
<table>
<tbody>
<tr>
<th>Select an option.</th>
</tr>
<tr>
<td>
<div class="field-input">
<form:radiobutton id="paymentOption" path="paymentOption" value="authorizeCC" />
Collect Credit Card Information
</div>
<div class="field-input">
Authorization Amount $
<form:input path="authAmount" maxlength="10" size="10" class="extendWidth"/>
<span class="instructions">
<spring:message code="label.authorization.note" />
</span>
</div>
<div class="field-input">
<form:radiobutton id="paymentOption" path="paymentOption" value="cancelAuth" />
Choose a Reason and Cancel Credit Card Collection
</div>
<div class="field-input right">
<form:select id="selectedReason" path="selectedReason" >
<c:forEach items="${reasonList}" var="reason">
<option value=${reason.reasonText}>${reason.reasonText}</option>
<br />
</c:forEach>
</form:select>
</div></td>
</tr>
</tbody>
</table>
</div>
<div class="right">
<button class="btnBlue" id="submitButton" type="submit">
Here is part of my controller:
#Controller
#RequestMapping(value = "/registers/default/ccPreauth")
#SessionAttributes(ControllerConstants.DEFAULT_REGISTER_ATTR_NM)
public class CCCaptureController {
...
#RequestMapping(value="/authorize" )
public ModelAndView authorize(
final Authentication auth,
final #ModelAttribute("ccCapturePaymentRequest") CCCapturePaymentForm ccCapturePaymentRequest,
final BindingResult result,
final HttpServletResponse response) {
final ModelAndView mav = new ModelAndView(CC_PREAUTH_PAYMENT_VIEW);
return mav;
}
and finally, here is my model class:
public class CCCapturePaymentForm implements Serializable {
private static final long serialVersionUID = 6839171190322687142L;
#NumberFormat(style = Style.CURRENCY)
private BigDecimal authAmount;
private String selectedReason;
private String paymentOption;
public BigDecimal getAuthAmount() {
return authAmount;
}
public void setAuthAmount(BigDecimal authAmount) {
this.authAmount = authAmount;
}
public String getSelectedReason() {
return selectedReason;
}
public void setSelectedReason(String selectedReason) {
this.selectedReason = selectedReason;
}
public String getPaymentOption() {
return paymentOption;
}
public void setPaymentOption(String paymentOption) {
this.paymentOption = paymentOption;
}
}
Can anyone tell me what I need to get this to work correctly? Please don't stop at just the reason for the exception above - please verify and correct my code as I am on a tight schedule as usual and have little experience with Spring MVC. Thanks!
You have this in your form:
modelAttribute="cccForm"
So you should have this in your controller:
#ModelAttribute("cccForm") CCCapturePaymentForm ccCapturePaymentRequest
That's how you bind the form backing object with the model attribute.
I found the answer for those Spring MVC newbies...
I had to set the "cccForm" to a new instance of my next page's form inside the controller search method (that then tries to being up the page that was getting the error).
In a nutshell: I had to set the empty backing bean value in the preceding controller method so that the follow-on method and JSP page have it to work with.
Hope this helps someone else avoid my mistake.
Mark

Categories

Resources