Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone explain how does @RequestMapping and @RequestBody works?

I have some doubts regarding how does @RequestMapping and @RequestBody actually woks.I have a code which is as follows:

@Controller
public class CoreController {
@Autowired
LoggerExtension log;
@Autowired
DoService doService;
    @RequestMapping(value="/method.do")
public @ResponseBody String getActionResponse(HttpServletRequest request,HttpServletResponse response){         
    String action = request.getParameter("action");     
    String gender = request.getParameter("gender");
    String language = request.getParameter("language");
            if("getLanguage".equalsIgnoreCase(action)){
            returnResponse = doService.getUserLanguage(msisdn);
           }
     }
        return returnResponse;
       }

I want to know how does the above code works? Please help me to clear this concepts...

like image 709
Mr. Singthoi Avatar asked Nov 21 '12 07:11

Mr. Singthoi


1 Answers

The Spring documentation explains it very well, for @RequestMapping

You use the @RequestMapping annotation to map URLs such as /appointments onto an entire class or a particular handler method.

In your specific case, @RequestMapping(value="/method.do") means that a http request (in any method) to the URI /method.do (e.g. http://myserver.com/app/method.do) will be handled by the annotated method getActionResponse(HttpServletRequest,HttpServletResponse) and Spring will bind the parameters automatically.

As for @ResponseBody it says:

This annotation can be put on a method and indicates that the return type should be written straight to the HTTP response body

In your specific case, this means that the returned string of the method annotated will be written to the response output stream or the writter like if you were calling something like this:

String result = getActionResponse(request, response)
response.getWriter().print( result ); //Suppose result is "en_US" or something

See ServletResponse#getWriter() or ServletResponse#getOutputStream()

like image 150
ElderMael Avatar answered Oct 18 '22 09:10

ElderMael