简体   繁体   中英

Best way to use spring for Web and mobile application

I am new to web development. I am planning to create a web service which is going to act as a back end for both web site and mobile application. I want to know if it is possible to use same method to return data in different type.

For example: If i use http://somewebsite/getdetails.jsp should give me and modelView return type and http://somewebsite/getdetails.json should give the model in json format.

I don't want to create two different controller to handle this.

If there is any other better way also please share your comments.

I am open for alternative solutions too

Spring 4.0 / Spring Boot enables you to achieve this quite easily. I am currently developing web-service (API) for mobile and backend for browser based clients and I just simply split API for mobile under URL @RequestMapping("/api"). In addition, Spring allows you to easily implement RESTful url based application. I recommend you to have two different controllers for API and Web MVC because it ensures complete separation between two different logics. Eg

Would you really like to implement something like following?

@SuppressWarnings("unchecked")
    public Map<Object, Object> test(@RequestParam(value="mobileyes") boolean mobile){

    if(mobile){
        Map<Object, Object> m = new HashMap<Object, Object>();
        m.put("test", "test")
        return m;
    } else {
        ModelAndView mv = new  ModelAndView();
        mv.addObject("test", "test");
        mv.setViewName("test");
        return (Map<Object, Object>) mv;
    }

    }

Above example might work, but ugly and will certainly cause maintenance disaster in near future.

This is my overall structure of Spring MVC using Spring Boot :

Ordinary URL accessed by desktop based and mobile based browsers

These controllers use @Controller annotation because it doesn't automatically enables @ResponseBody

www.mybusinesscard.com.au/ -> Index


//Displaying all businesscards

www.mybusinesscard.com.au/businesscards -> view all


//For saving from form

www.mybusinesscard.com.au/businesscard/save -> save a card

Following controller examples are for mobile API:

Following controllers use @RestController annotation to automatically enable requirements necessary for WebServices. Eg: @ResponseBody

www.mybusinesscard.com.au/api -> Index


//Displaying all businesscards

www.mybusinesscard.com.au/api/businesscards -> view all


//For saving from form

www.mybusinesscard.com.au/api/businesscard/save -> save a card

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM