How to develop Rest Web Service using @RestController - Spring Framework

in #utopian-io7 years ago (edited)

SourceHere

What Will I Learn?

In this tutorial, we will learn about how we can develop Rest web API or Services using @RestController annotation in Spring framework and how you can call the web services using ARC Client

  • Rest Web services
  • Get JSON data from Rest web Services using ARC or Web Browser

Requirements

  • Eclipse IDE (Juno or above)
  • JDK 1.7 or above
  • Tomcat Server 7 or above
  • Spring and jackson jar files
  • Web Browser Chrome or Firefox

Difficulty

  • Basic

Tutorial Contents

  • Application Configuration wit Spring Framework

Now we configure the web application with sping framework to creating @restController

  1. configuring web.xml file
    First of all paste all jar files into lib folder
    Here we configure web.xml file to run application application
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    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_2_5.xsd">
  <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/config/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
  </servlet>  
  <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
        <welcome-file></welcome-file>
  </welcome-file-list>  
</web-app>

Screenshot (103).png

  1. configuring spring-servlet.xml
    Basic configuration of databse, view resolver and sessionfactory
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/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">
<context:property-placeholder location="classpath:resources/database.properties" />
    <context:component-scan base-package="com.blog" />
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>
    ```
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="annotatedClasses">
        <list>
            <value>com.blog.model.Users</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>             
        </props>
    </property>
</bean>

</beans>

Screenshot (104).png

  • Creating RestController
    Here we create RestControler java file and write code for populating list and converlist from ArrayList to json and this controler return json object string
package com.blog.restwebservice;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.blog.bean.QuestionsBean;
import beans.ConvertDateFormat;
import beans.ListToJsonObject;
import beans.Sudent;
import com.blog.model.Questions;
import com.blog.service.QuestionsService;

@RestController
@RequestMapping("/yayayaa")
public class RestWebServiceController {
    @Autowired(required=false)
    private QuestionsService questionsService;  
    ListToJsonObject listtojson = new ListToJsonObject();
    ConvertDateFormat fmt = new ConvertDateFormat();    
    @RequestMapping(method = RequestMethod.GET)
    public @ResponseBody String listQuestionsss() throws JsonGenerationException, JsonMappingException, IOException, ParseException {                       
        List<Sudent> list = listofStudents();   
        String json = new ObjectMapper().writeValueAsString(list);
        return json;
    }       
    List<Sudent> list = new ArrayList<Sudent>();
    public List<Sudent> listofStudents()
    {
        list.add(new Sudent(1,20,"Rahul","Whatever","rahul@gmail.com"));
        list.add(new Sudent(2,21,"Ramesh","Whatever","ramesh@gmail.com"));
        list.add(new Sudent(3,22,"Shyam","Whatever","shyam@gmail.com"));
        list.add(new Sudent(4,23,"Ram","Whatever","ram@gmail.com"));
        list.add(new Sudent(5,24,"Krishna","Whatever","krishna@gmail.com"));
        list.add(new Sudent(6,25,"Jacop","Whatever","jacop@gmail.com"));        
        return list;
    }
}

Screenshot (106).png

Result

  • Lets run the project using tomcat server call the controller using ARC Client
    Screenshot (108).png

  • run on web browser
    Screenshot (107).png

  • parse retuned JSON data with json parser
    Screenshot (109).png

It's Done !
Congratulations ! we successfully developed Rest Web Service.

Thank You !

Share from the core of my heart



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Great work. Make a complete tutorial

Thank you ! 2 hours to complete the work and half hour to write tutorial

Your contribution cannot be approved because it does not follow the Utopian Rules.