Workshop 3
Workshop 3
Workshop 3
method argument
Whenever we fill any data into form controls e.g. textfield, then such data can be accessed in
controller [ a method within controller] and data again can be passed to view for display. Let us
Develop a program for this to work.
4. Create sampleForm.jsp file and put following lines of code over there:
1
5. Create sample.jsp and put following lines of code over there:
6. Right Click your project and Add Dispatcher Servlet with the name Dispatcher Servlet
into your project.
7. Make Sure your web.xml file has following contents:
2
9. Type following URL to run above code:
http://localhost:8080/MVCFormDemo/sample
Data Entry Form sampleForm.jsp will be displayed and whenever you press SAVE
button sample.jsp page will be displayed.
1. Add following method that sets default values in form in Controller class:
2. Create sampleAutoFillForm.jsp page and put following lines of code inside it:
3
On Typing http://localhost:8080/MVCFormDemo/sample, you will see a form auto filled
with values as shown below:
4
Saving form data in an object automatically
1. Add following methods in Controller class:
2. Create a jsp file called registration.jsp and add following lines of code inside it:
3. Type: http://localhost:8080/MVCFormDemo/register and Press SUBMIT button.
4. Data value entered inside the form control are binded to person object with the name
"myperson".
5
Using textarea, text, password, hidden fields, select field,
checkbox, radio buttons
Using textarea
Tag:
Note: There should be a model class containing a field whose name should be "description" and
corresponding getters and setters
6
Using text
Tag:
Note: There should be a model class containing a field whose name should be "personaddress"
and corresponding getters and setters
Using password
Tag:
<form:password path="password"/>
Note: There should be a model class containing a field whose name should be "password" and
corresponding getters and setters
Tag:
<form:hidden path="hiddenf"/>
Note: There should be a model class containing a field whose name should be "hiddenf" and
corresponding getters and setters
Tag:
<form:select path="country" items="${countries}"></form:select>
Note: There should be a model class containing a string field whose name should be "country"
and corresponding getters and setters.
Similarly, there should be following code in Controller class for populating select field values:
7
@ModelAttribute("countries")
public Map<String,String> countries()
{
Map<String,String> m=new HashMap<String,String>();
m.put("np", "Nepal");
m.put("in", "India");
m.put("pak", "Pakistan");
return m;
}
Using checkbox
Tag:
<form:checkboxes path="languages" items="${langses}" />
Note: There should be a model class containing a string field whose name should be "languages"
and corresponding getters and setters.
Similarly, there should be following code in Controller class for populating select field values:
@ModelAttribute("langses")
public Map<String,String> langs()
{
Map<String,String> m=new HashMap<String,String>();
m.put("np", "Nepal");
m.put("in", "India");
m.put("pak", "Pakistan");
return m;
}
Tag:
<form:radiobuttons path="sex" items="${gender}" />
Note: There should be a model class containing a string field whose name should be "sex" and
corresponding getters and setters.
Similarly, there should be following code in Controller class for populating select field values:
@ModelAttribute("langses")
8
public Map<String,String> langs()
{
Map<String,String> m=new HashMap<String,String>();
m.put("np", "Nepal");
m.put("in", "India");
m.put("pak", "Pakistan");
return m;
}
If you want to set default values: then you should have following codes in the Controller class
@ModelAttribute("defaultVals")
public Person defaultCntries()
{
String dlangs[]={"np","pak"};
Person p=new Person();
p.setCountry("in");
p.setLanguages(dlangs);
p.setSex("f");
return p;
}
9
There should be following codes in your controller class:
@RequestMapping(value="/addRecord",method=RequestMethod.POST)
public String addRecord( @ModelAttribute("command") @Valid Person
person,BindingResult result, ModelMap model)
{
if(result.hasErrors())
{
System.out.println("Inside If");
return "registration";
}
else
{
model.addAttribute("personame",person.getPersoname());
model.addAttribute("personaddress",person.getPersonaddress());
model.addAttribute("persontelno",person.getPersontelno());
System.out.println("Inside Else");
return "success";
}
}
Note: All Above Source codes are from MVCFormDemo App which is located in D:\tapdemo
folder.
Custom annotations
We can also develop our own annotation and apply it to either data field, method or class. Now,
we are going to develop an annotation named @Phone(message="Phone no is not valid") which
we are going to put before String persontelno variable. For this, we need to follow, below steps:
1. Create a package named lab3.annotation within src folder and create an annotation file
named Phone.java and keep following lines of code inside it:
@Constraint(validatedBy = PhoneConstraintValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Phone {
String message() default "{Phone}";
2. Create a class named PhoneConstrintValidator and put following lines of code inside it.
This class contains the validation logic.
public class PhoneConstraintValidator implements ConstraintValidator<Phone,
String>{
@Override
public void initialize(Phone String) { }
10
@Override
public boolean isValid(String phoneField, ConstraintValidatorContext
cxt) {
phoneField=phoneField.trim();
boolean b=phoneField.matches("[0-9()-]*");
System.out.println("Value of Matches="+b+""
+ "\n Value of phoneField="+phoneField);
if(phoneField == null || phoneField.equals("")) {
return false;
}
return phoneField.matches("[0-9()-]*");
}
In registration.jsp, you have to put below codes just after telephone number field in order for
custom validation message to appear:
11