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: http://maven-repository.com/artifact/co.ntier/spring-mvc-archetype/1.0.2\
     
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"
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
        <property name="messageConverters">
            <list>
                <ref bean="jacksonMessageConverter" />
            </list>
        </property>
    </bean>

    <bean id="jacksonMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>


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


Step 3: In controller class :



    @RequestMapping(value="/test", method = RequestMethod.GET)
    @ResponseBody
    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 })
  @ResponseBody
    public ErrorResponse handleException(Exception ex,
            HttpServletRequest request, HttpServletResponse response) {
             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setMessage(ex.getMessage());
        return errorResponse;
    }


Output:

{"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 : http://waheedtechblog.blogspot.in/2012/08/spring-mvc.html

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

Step 1 : Create a class 


@Controller
public class HelloWorld {
 
    @RequestMapping("/hello")
    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 -->
    <!-- ========================== -->

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

<!-- This loads the root webapp Spring context -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:beans.xml</param-value>
    </context-param>
   
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

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="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task-3.0.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-2.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        ">

    <!-- ========================== -->
    <!-- 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" />

 </beans>

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 : https://github.com/abdulwaheed18/SpringMVC-Hibernate-Integration

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

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

Mapping Requests
•By path
–@RequestMapping(“path”)
•By HTTP method
–@RequestMapping(“path”,method=RequestMethod.GET)
–POST,PUT,DELETE,OPTIONS and TRACE are also supported
•By presence of query parameter
–@RequestMapping(“path”,method=RequestMethod.GET,params=“foo”)
–Negation also supported: params={“foo”,”!bar”}
•By presence of request header
–@RequestMapping(“path”,header=“content-type=text/*”)
–Negation also supported

For more details : Click Here

For tutorial: http://waheedtechblog.blogspot.in/2012/08/spring-mvc-tutorial.html
 



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...