Spring RequestMapping with ConstraintViolation

      Click here to attend Spring Framework 4.x and certification course with a discount

package nl.kameroom.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import nl.kameroom.contactservice.ContactInfo;
import nl.kameroom.contactservice.ContactService;
import nl.kameroom.util.LocaleMessageSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
public class ContactController {

private ContactService contactService;
private LocaleMessageSource messageSource;
private Validator validator;

public void setLoginService(ContactService cs) {
contactService = cs;

public void setValidator(Validator v) {
validator = v;

public void setLocaleMessageSource(LocaleMessageSource ms) {
messageSource = ms;

@RequestMapping(value="/contactInfoAJAX.k", method=RequestMethod.POST)
public @ResponseBody String[] sendForm(
@RequestParam("subject") String subject,
@RequestParam("content") String content,
@RequestParam("email") String email,
@RequestParam("category") String category,
@RequestParam("mq") String mq, ModelMap model, HttpServletRequest request) throws Exception {

ContactInfo ci = new ContactInfo();

Set<ConstraintViolation<ContactInfo>> constraintViolations = validator.validate(ci);

String[] messages = new String[constraintViolations.size()];
ArrayList<String> mList = new ArrayList<String>();

for (int i = 0; i < constraintViolations.toArray().length; i++) {
ConstraintViolation constraintViolation = (ConstraintViolation)constraintViolations.toArray()[i];
for (int i = 0; i < mList.size(); i++) {
messages[i] = messageSource.getMessage(mList.get(i).substring(1), request);

//validation error occurred
if(messages.length > 0) {
return messages;

boolean r = contactService.insertContactInfo(ci);
return new String [] {};
return new String [] {"srvError"};

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s