Sunday, September 13, 2015

Create a custom validation in Spring MVC4

There are few simple steps to create your custom validation :

1- Create a new package (ex. com.yourcompany.view)
2- Create a new annotation like in the screenshot below




3- Add the following annotation to your annotation interface as in the code below

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;


@Documented
@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 {};
}


4- Define another class called PhoneConstraintValidator in the same package and the below code

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PhoneConstraintValidator implements ConstraintValidator<Phone, String> {

    @Override
    public void initialize(Phone phone) {
       
    }


    @Override
    public boolean isValid(String phoneField, ConstraintValidatorContext cxt) {
        if (phoneField == null){
            return false;
        }

        return phoneField.matches("[0-9()-]*");
    }

}



5- Add the annotation to your bean.

Easy !!! Yeah :)


 

Wednesday, July 8, 2015

Rest & Angular - Spring MVC4

To implement Rest & Angular client in MVC4, you need to :

1- Create the rest controller 

@RestController
public class ReleasesReportController {

    @RequestMapping("/releases")
    public List<Release> getReleases(){
        List<Release> releases=new ArrayList<Release>();
       
        Release release1 =new Release();
        release1.setName("Strong bad");
       
        Release release2 =new Release();
        release2.setName("Back to the feature");
       
        Release release3 =new Release();
        release3.setName("Trogdor");
       
        releases.add(release1);
        releases.add(release2);
        releases.add(release3);
       
        return releases;
       
    }
}

2- Add JSON mapping to the WebAppInitializer class 

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        WebApplicationContext context = getContext();
        servletContext.addListener(new ContextLoaderListener(context));
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("*.html");
        dispatcher.addMapping("*.pdf");
        dispatcher.addMapping("*.json");

    }


3- Bind it to the front end 


<html ng-app>

<head>
<title> Hello Releases Tracker</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js" > </script>
<script type="text/javascript" src="releases.js"></script>
</head>

<body>
    <div ng-controller="Releases">
        I have {{releases.length}} releases !
       
        <ul class="releases-container">
            <li ng-repeat="release in releases">
            {{release.name}}
             </li>
       
        </ul>
    </div>

</body>

</html>


4- Create the angular file (releases.js) under src/main/webapp folder

function Releases($scope, $http){
  
    $http.get('http://localhost:8080/ReleaseTracker/releases.json').
        success(function(data){
        $scope.releases=data;
    });
  
}

Custom validation example - Spring MVC 4


To build a custom validation example you need to:

1-Create an Interface
2-Create a class that implements ConstraintValidator
3-Use the  custom validation in the Bean


 Step 1: 

@Documented
@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 {};
}


Step 2:

public class PhoneConstraintValidator implements ConstraintValidator<Phone, String> {

    @Override
    public void initialize(Phone phone) {
       
     }

    @Override
    public boolean isValid(String phoneField, ConstraintValidatorContext cxt) {
        if (phoneField == null){
            return false;
        }
        return phoneField.matches("[0-9()-]*");
    }

}


Step 3: 

@NotEmpty @Phone
    private String phoneNumber;

Tuesday, July 7, 2015

Famous Exceptions in Spring MVC 4

java.lang.UnsupportedOperationException: Cannot change HTTP accept header
 
 
The DispatcherServlet  looks for a bean with the name localeResolver.
If this isn't detected it will use the default, 
which is a AcceptHeaderLocaleResovler
 
 @Bean
 public MessageSource messageSource(){
  
  ResourceBundleMessageSource messageSource=new 
                ResourceBundleMessageSource();
  messageSource.setBasename("messages");
  return messageSource;
  
 }
 
 @Bean
 public LocaleResolver localeResolver(){
  SessionLocaleResolver resolver =new SessionLocaleResolver();
  resolver.setDefaultLocale(Locale.ENGLISH);
  return resolver;
 }
 
 @Override
 public void addInterceptors(InterceptorRegistry registry)
 {
  LocaleChangeInterceptor changeInterceptor=new 
                LocaleChangeInterceptor();
  changeInterceptor.setParamName("language");
  registry.addInterceptor(changeInterceptor);
 } 

Monday, July 6, 2015

Spring - MVC4 - web.xml file sample

<web-app id="WebApp_ID" version="3.0"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

 <display-name>Archetype Created Web Application</display-name>

 <servlet>
   <servlet-name>springDispatcherServlet</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  
   <init-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>com.saifmasadeh.WebConfig</param-value>
   </init-param>
  
   <init-param>
       <param-name>contextClass</param-name>
       <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
   </init-param>
  
   <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
   <servlet-name>springDispatcherServlet</servlet-name>
   <url-pattern>*.html</url-pattern>
 </servlet-mapping>

</web-app>