Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Workshop 3

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

Getting a submitted form value using a controller

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.

1. Create a Dynamic Web Project


2. Add all Spring lib jars and apache commons logging jar file both in Java Build Path and
Deployment Assembly
3. Create a folder named lab3.controller inside Java Resources/src folder and create a class
named MyController and keep the following lines of code over there

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:

8. Create xml file named DispatcherServlet-servlet.xml in the same directory where


web.xml resides and make sure it 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.

Setting a forms default values using a model


object
When a form is accessed for the first time, then we can set default values inside its controller.
For that we need to follow, following steps:

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:

<form:textarea path="description" />

Note: There should be a model class containing a field whose name should be "description" and
corresponding getters and setters

6
Using text

Tag:

<form:input path="personaddress" />

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

Using hidden fields

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

Using select field

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;
}

Using radio buttons

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;
}

And form should have following codes:

<form:form method="POST" action="/MVCFormDemo/addRecord"


modelAttribute="defaultVals" commandName="command">

form validation using annotations


If there exists a text field and you want to validate its input, then you need to keep following
lines of code just after your text field
<form:errors path="personame" cssClass="error"></form:errors>
Similalry, within head element, there should be following css tag:
<style>
.error {
color: #ff0000;
}
</style>
Moreover, in a model class, just before variable declaration, you should mention following codes
in order for annotation to work
@NotEmpty(message = "Person Name cannot be null")
String personame;

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}";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};


}

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()-]*");
}

Note: both of the above classes should be on the same package.

Customize validation messages


Validation messages can be customized by keeping such messages inside a file called
messages.properties instead of directly mentioning them along with annotation[ by assigning as
value to message variable]. For this, create a folder named resources inside src and create a file
named messages.properties and keep following lines of code inside it:

Phone.command.persontelno=Your Phone Number is Not A Valid One

Moreover, inside your application context file[DispatcherServlet-servlet.xml] keep the following


lines of code inside <beans> </beans> tag,
<bean class="org.springframework.context.support.ResourceBundleMessageSource"
id="messageSource">
<property name="basename" value="resources/messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>

In registration.jsp, you have to put below codes just after telephone number field in order for
custom validation message to appear:

<form:errors path="persontelno" cssClass="error"></form:errors>

11

You might also like