How to pass onchange value from form:select into controller - spring

I am using Spring MVC for developing the Java Web Application.
In my current scenario, i am stuck in one situation.
In my current project, I have a dropdown and i need to pass the selected value on onChange to controller for processing the result.
For showing dropdown i am using form:select (Spring Form).
Can you please suggest me how to pass selected value to controller on OnChange
<body>
<form:form method="post" modelAttribute="ad" action="/save">
<form:select cssClass="select" cssStyle="width:100%;margin-left:10%;"
path="work_type" items="${allworktype}" itemValue="id"
itemLabel="work_type" />
</form:form>
#Controller
public class WebController {
#Autowired
public AdminBuildingRepo adminBuildingRepo;
#ModelAttribute("allworktype")
public List<AdminBuilding> getblocks(Model model){
return adminBuildingRepo.findAll();
}
#GetMapping("/")
public String home(Model model) {
AdminBuilding ad= new AdminBuilding();
model.addAttribute("ad", ad);
return "index";
}
#RequestMapping(value = "/save", method = RequestMethod.GET)
public String transferForDevice( Model model) throws Exception {
System.out.println("*********");
//so now I can use "user" from #ModelAttribute
return "redirect:/admin";
}
}
Please help me how to pass value to controller on selection.

function formSubmit(){
$('form#myForm').attr({action: 'save'});
$('form#myForm').attr({modelAttribute: 'ad'});
$('form#myForm').attr({method: 'post'});
$('form#myForm').submit();
}
declare form with id myForm
call this function on select onchange

Related

How to bind input elements to an arraylist element in Spring MVC?

How to bind input elements to an arraylist element in Spring MVC?
The view model:
public class AssigneesViewModel {
private int evaluatorId;
private int evaluatedId;
private String evaluatorName;
private String evalueatedName;
//getters and setters
}
The model attribute:
public class AssignEvaluationForm{
private ArrayList<AssigneesViewModel> options;
public ArrayList<AssigneesViewModel> getOptions() {
return options;
}
public void setOptions(ArrayList<AssigneesViewModel> options) {
this.options = options;
}
}
Controller
#RequestMapping(value="addAssignment", method = RequestMethod.GET)
public String addAssignment(Model model){
model.addAttribute("addAssignment", new AssignEvaluationForm());
return "addAssignment";
}
Then in the jsp i have 4 hidden inputs which represent the fields for the evaluatedId, evaluatorId, evaluatorName, evaluatedName -> options[0].
How i am going to write the jsp code to map those inputs with an element of the arrayList?
Update:
<form:form commandName="addAssignment" modelAttribute="addAssignment" id="addAssignment" method="POST">
//..........
<c:forEach items="${addAssignment.options}" var="option" varStatus="vs">
<div id="assigneesOptions" >
<form:input path="addAssignment.options[${vs.index}].evaluatedId" value="1"></form:input>
</div>
</c:forEach>
//..............
</form:form>
With this update i get the following error:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'options[]' available as request attribute
<form:input path="addAssignment.options[${vs.index}].evaluatedId" value="1"></form:input>
Instead of this addAssignment.options[${vs.index}].evaluatedId
Use this -> option.evaluatedId
Or you might reach value with arraylist get -> ${addAssignment.options.get(vs.index).evaluatedId} , try to turn out that ${} jstl's call curly brackets. BTW i'm not sure this last example work on path="" attribute.

Returning multiple view from spring controller

I want to return multiple views(jsp) from one controller. i.e. one view below another
#RequestMapping(method = RequestMethod.GET, value = "register")
public String addUser(Model model) {
// on some condition
if(){
//add "user/login" above or below "user/edit"
}
model.addAttribute(new User());
return "user/edit";
}
i want to do this on controller not on jsp
it can be possible or i have to use tiles for it
You can only return one view. If you do not want to use a templating library then you need to set some model attribute and then use that to conditionally render some additional HTML.
CONTROLLER
#RequestMapping(method = RequestMethod.GET, value = "register")
public String addUser(Model model) {
if(x){
model.addAttribute("showAdditionalFields", true);
}
model.addAttribute(new User());
return "user/edit";
}
JSP
<c:if test="${showAdditionalFields}">
<!-- include here -->
</c:if>

How to view data in Jsp when added in a model using spring mvc

I have the following flows for an application when a submit button is clicked:
1)The viewActivity method is called from ActivityController.java
ActivityController.java
#ActionMapping(params = "ActivityController=showActivity")
public void viewActivity(#RequestParam Integer index, ActionResponse response, Model model, #ModelAttribute Header header,
....
model.addAttribute("recoveryForm", new RecoveryForm(detailsResult.getDetails()));
response.setRenderParameter("ServiceController", "showService");
}
2) Then showRecovery method is called from serviceConroller as show below:
ServiceController.JAVA
#RenderMapping(params = "ServiceController=showService")
public String showRecovery(#ModelAttribute recoveryForm form, #ModelAttribute header header) {
.....
return service;
}
Then my service.jsp is displayed
Basically i have to display the value of a variable which is detailName found in DetailsResult.getDetails() object which i have added to my model as
it can be seen in viewActivity method found in ActivityController.java showed ealier.
I know when we add model.addAttribute it should be able to be displayed on this jsp using the following tag :
<form:input path="..." />
But in this case it is added to as a constructor argument as shown below:
model.addAttribute("recoveryForm", new RecoveryForm(detailsResult.getDetails()));
I have the following variable on my RecoveryForm:
public class RecoveryForm implements Serializable {
private CDetails Cdlaim;
private Action addAction;
private String addRemark;
private String remarks;
public RecoveryForm(CDetails Cdlaim) {
...
}
...
}
However i don't have the detailsResult in my RecoveryForm.
Any idea how i can get a value which is in DetailsResult.getDetails() in my service.jsp?
I believe you are looking at this the wrong way. The value of DetailsResult.getDetails() is obviously stored in RecoveryForm as a property somehow. So, I'm going to assume your RecoveryForm looks something like:
public class RecoveryForm {
private String details;
public RecoveryForm(String details) {
this.details = details;
}
public String getDetails() {
return details;
}
}
When you bind to a form in your jsp, you need to nest your <form:input ...> tag in a <form:form ...> tag:
<form:form commandName="recoveryForm" ...>
<form:input path="details" ... />
</form:form>
The commandName is key to telling the form the model object from which you will be pulling form values. In this case you are getting the details property from the RecoveryForm instance named recoveryForm. Make sense?

jsr-303 validation in spring mvc application doesn't validate

I'm having some trouble setting up validation for a form in spring.
The bean I would like to validate look like this:
public class RegistrationForm extends ProjectXUser {
#NotEmpty
private String password2;
#NotBlank
#AssertTrue
private Boolean agreedToConditions;
...
ProjectXUser inherits from BaseUser which has some more properties which are also annotated.
My controller looks like this:
#Controller
public class RegistrationController {
private static final String REGISTRATION_JSP = "registration";
#ModelAttribute("registrationForm")
public RegistrationForm getRegistrationForm() {
return new RegistrationForm();
}
#RequestMapping(value = { "/registratie/jaar", "registratie/proef" }, method = RequestMethod.GET)
public String year() {
return "registration";
}
#RequestMapping(value = { "/registratie/jaar", "registratie/proef" }, method = RequestMethod.POST)
public ModelAndView register(#Valid RegistrationForm registrationForm, BindingResult result) {
if (result.hasErrors()) {
return new ModelAndView(REGISTRATION_JSP);
} else {
return new ModelAndView("redirect:/registratie/success");
}
}
}
My spring configuration file contains:
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<mvc:annotation-driven />
I've read in the spring documentation that if a jsr-303 validator is present in the class path spring will detect it automatically and use it. So i've added hibernate-validator to my pom.
But when I debug my controller I can see the registrationForm contains the values I've filled in. But results always has 0 errors. Even if I enter some explicit wrong input in my form fields.
You need to return the result in the ModelAndView in the case where there are errors. All you are returning is an empty mav.
See: http://forum.springsource.org/showthread.php?117436-Spring-MVC-3-and-returning-validation-errors-to-page-from-Valid&highlight=bindingresult for an example.
If this bit of your code is firing and redirecting back to your registration page
if (result.hasErrors()) {
return new ModelAndView(REGISTRATION_JSP);
}
Then your JSR-303 validation is being picked up. You need to display your errors on your JSP page like this
<form:errors path="password2" cssClass="error" />
where cssClass="error" is the CSS you want to display the error with. It's automatically put into a <div> for you.

I am confused about how to use #SessionAttributes

I am trying to understand architecture of Spring MVC. However, I am completely confused by behavior of #SessionAttributes.
Please look at SampleController below , it is handling post method by SuperForm class. In fact, just field of SuperForm class is only binding as I expected.
However, After I put #SessionAttributes in Controller, handling method is binding as SubAForm. Can anybody explain me what happened in this binding.
-------------------------------------------------------
#Controller
#SessionAttributes("form")
#RequestMapping(value = "/sample")
public class SampleController {
#RequestMapping(method = RequestMethod.GET)
public String getCreateForm(Model model) {
model.addAttribute("form", new SubAForm());
return "sample/input";
}
#RequestMapping(method = RequestMethod.POST)
public String register(#ModelAttribute("form") SuperForm form, Model model) {
return "sample/input";
}
}
-------------------------------------------------------
public class SuperForm {
private Long superId;
public Long getSuperId() {
return superId;
}
public void setSuperId(Long superId) {
this.superId = superId;
}
}
-------------------------------------------------------
public class SubAForm extends SuperForm {
private Long subAId;
public Long getSubAId() {
return subAId;
}
public void setSubAId(Long subAId) {
this.subAId = subAId;
}
}
-------------------------------------------------------
<form:form modelAttribute="form" method="post">
<fieldset>
<legend>SUPER FIELD</legend>
<p>
SUPER ID:<form:input path="superId" />
</p>
</fieldset>
<fieldset>
<legend>SUB A FIELD</legend>
<p>
SUB A ID:<form:input path="subAId" />
</p>
</fieldset>
<p>
<input type="submit" value="register" />
</p>
</form:form>
When processing POST request, Spring does the following:
Without #SessionAttributes: Spring instantiates a new instance of SuperForm (type is inferred from the signature of register()), populates its properties by values from the form fields and passes it to the register() method.
With #SessionAttributes: Spring obtains an instance of model attribute from the session (where it was placed when processing GET due to presence of #SessionAttributes), updates its properties by values from the from fields and passes it to the register() method.
That is, with #SessionAttributes , register() gets the same instance of the model attribute object that was placed into the Model by getCreateForm().
Adding on to what #axtavt said: Suppose, in getCreateForm you are putting some values for a drop-down (list or map), or you are putting some values in form that you want in register method but you don't want them to show in form (not even in hidden fields). Now suppose that an error occurred in register method and you need to show the form again. To populate drop down values and other values that you would need in next post, you would have to repopulate them in form. The #SessionAttribute helps here as #axtavt very well described above.
#Controller
#SessionAttributes("test")
public class Controller{
Customer customer;
public Controller() {
super();
customer = new Customer();
}
#ModelAttribute("test")
public Customer getCustomer() {
customer.setName("Savac");
return customer;
}
#RequestMapping({"/index"})
public ModelAndView showMainPage (#ModelAttribute("test") Customer customer, ModelMap model, method = RequestMethod.GET) {
//in the view you set the name
return new ModelAndView("index");
}
#RequestMapping(value = "customer/{customerID}", method = RequestMethod.GET)
public ModelAndView viewAdvice(#PathVariable("customerID") int customerID, #ModelAttribute("test") Customer customer, ModelMap model) {
customer.setName("AnotherName");
model.addAttribute("test", customer);
return new ModelAndView("customer");
}
}
According to Spring reference documentation #ModelAttribute annotated method argument is resolved as follows:
Retrieve from model object if it is present (normally added via #ModelAttribute annotated methods)
Retrieve from HTTP session by using #SessionAttributes.
Create using URI path variable that matches the #ModelAttribute name through a converter
Create using default constructor and add it to Model.
A handler class can be annotated with #SessionAttributes with a list of names as its arguments. This is to instruct Spring to persist (in session) those data items present in the model data which match the names specified in #SessionAttributes annotation.
Thus in the SampleController, the post method's #ModelAttribute argument is resolved with #SessionAttributes field due to the resolution method mentioned above.

Resources