Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Thursday, October 17, 2013

How to create Spring MVC project using Maven and Eclipse

This blog will show you how quickly you can  create a Spring MVC project and get it up and running, using the Maven archetype called spring-mvc-archetype.

Note: First You should verify that the Maven Integration for FTP is already installed in your eclipse, If not first installed and then create a new project.

Steps :
  • In Eclipse IDE, Goto  File > New > Project
  • Select Maven > Maven Project and click Next.
  • Make sure you don’t check the option Create a simple project (skip archetype selection), and click Next. In the next screen,
  • Select Catalog as All Catalogs, Archetype as spring-mvc into the Filter  and select maven-archetype-webapp in the artifact list as shown below :


In case, If you don't see the above artifact in your Archtype then Click on "Add Archetype" and Add :
    • Archetype Group Id: co.ntier
    • Archetype Artifact Id: spring-mvc-archetype
    • Archetype Version: 1.0.2
    • Repository URL:\
Click Next and Enter Group Id (e.g. Test), Artifact Id (e.g. Test), Version (e.g. 1.0) and Package (com.waheed.test), as shown below :

Click Finish.Finally you have a project structure looks like below:                         


Wednesday, January 2, 2013

How ExceptionHandler return JSON in spring MVC

I am working on one project where client/server response is in JSON format. It is easy to send object in JSON format but what if some exception occured and you want to send the Exception also in JSON format ?
After n number of trial. I finally able to do the above task

Step 1 : Add following annotation "AnnotationMethodHandlerExceptionResolver" in your <CONTROLLER>-servlet.xml file.

<!-- JSON format support for Exception -->
    <bean id="methodHandlerExceptionResolver"
        <property name="messageConverters">
                <ref bean="jacksonMessageConverter" />

    <bean id="jacksonMessageConverter"

Step 2: Make sure you have added jackson jars into your classpath.

Step 3: In controller class :

    @RequestMapping(value="/test", method = RequestMethod.GET)
    public String toTest() throws MxlServiceException {

   try {
      int i = 10/0; // it will throw exception which will be caught by handleException(...)
  }catch (Exception e) {
    throw e;
             return "hello";

then catch them both by writing an exception handler that looks like this:

@ExceptionHandler({ Exception.class })
    public ErrorResponse handleException(Exception ex,
            HttpServletRequest request, HttpServletResponse response) {
        ErrorResponse errorResponse = new ErrorResponse();
        return errorResponse;


{"message": "your_message"}

Feel free to comment :)

Wednesday, August 29, 2012

Spring MVC tutorial

Before Starting, I believe you must have basic idea about JAVA, SPRING and Spring MVC.

For Spring MVC :

In this tutorial , I will just tell you what are the basic thing that you need to start MVC.

Step 1 : Create a class 

public class HelloWorld {
    public String helloWorld() {
         return = "Hello World, Spring 3.0!";

1 . The class HelloWorld  has the annotation @Controller and @RequestMapping("/hello"). When Spring scans this class, it will recognize this bean as being a Controller bean for processing requests. 2 .The @RequestMapping annotation tells Spring that this Controller should process all requests beginning with /hello in the URL path.

Step 2. Mapping Spring MVC in WEB.xml

The entry point of Spring 3.0 MVC is the DispatcherServlet. DispatcherServlet is a normal servlet class which implements HttpServlet base class. Thus we need to configure it in web.xml.

<!-- ========================== -->
    <!-- Spring MVC: Core -->
    <!-- ========================== -->


<!-- This loads the root webapp Spring context -->


Note that I have mapped /rest/* url pattern with example DispatcherServlet. Thus any url with /rest/* pattern will call Spring MVC Front controller.

                  The REST call would be http://ip:port/rest/hello

If your controller class has some dependency which you have defined in your spring context file.Then you have to load it in <context-param>.(red line).
Once the DispatcherServlet is initialized, it will looks for a file name [servlet-name]-servlet.xml in WEB-INF folder of web application. I have created the file named spring-servlet.xml

3 . Spring Configuration file

Create a file spring-servlet.xml in WEB-INF folder and copy following content into it.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    xmlns:xsi="" xmlns:task=""
    xmlns:tx="" xmlns:context=""
    xmlns:mvc="" xmlns:util=""

    <!-- ========================== -->
    <!-- Spring MVC: Core -->
    <!-- ========================== -->

    <context:annotation-config />
    <mvc:annotation-driven />
    <mvc:default-servlet-handler />

    <!-- class name of the controller or If you have package use component-scan -->
    <bean class="com.waheed.spring.hibernate.HelloWorld" />


The highlighted red line allow Spring to load the components from class. This will load our HelloWorld class.

Congratulation..!!! You are done here...

Download source code :

Spring MVC

Spring MVC helps in building flexible and loosely coupled web applications. The Model-view-controller design pattern helps in seperating the business logic, presentation logic and navigation logic. Models are responsible for encapsulating the application data. The Views render response to the user with the help of the model object . Controllers are responsible for receiving the request from the user and calling the back-end services.

When a request is sent to the Spring MVC Framework the following sequence of events happen.
  • The DispatcherServlet first receives the request.
  • The DispatcherServlet consults the HandlerMapping and invokes the Controller associated with the request.
  • The Controller process the request by calling the appropriate service methods and returns a ModeAndView object to the DispatcherServlet. The ModeAndView object contains the model data and the view name.
  • The DispatcherServlet sends the view name to a ViewResolver to find the actual View to invoke.
  • Now the DispatcherServlet will pass the model object to the View to render the result.
  • The View with the help of the model data will render the result back to the user.

The new Servlet
•DispatcherServlet requests are mapped to @Controller methods
–@RequestMapping annotation used to define mapping rules
–Method parameters used to obtain request input
–Method return values used to generate responses
•Simplest possible @Controller

public class HelloController {
    public @ResponseBody String hello() {
        return “Hello World”;

Mapping Requests
•By path
•By HTTP method
–POST,PUT,DELETE,OPTIONS and TRACE are also supported
•By presence of query parameter
–Negation also supported: params={“foo”,”!bar”}
•By presence of request header
–Negation also supported

For more details : Click Here

For tutorial:

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...