简体   繁体   中英

How to use @Inject in Spring MVC Controller?

I am working with Spring MVC controller. I have one of my controller as DataController .

I am thinking to add HttpServletRequest as injectable at the top of DataController class using @Inject .

@Controller
public class DataController {

    @Inject
    HttpServletRequest request;

    // .. some code here

    @RequestMapping(value = "process", method = RequestMethod.GET)
    public @ResponseBody
    DataResponse processTask(@RequestParam("workflow") final String workflow) {

        String ipAddress = request.getRemoteAddr();
        System.out.println(ipAddress);

}

So my question is - Is this the right way to use @Inject ? I have never used @Inject before so trying to learn whether the way I am doing it is right or not? Since everytime, who is making call to processTask method, I need to grab its ipAddress whoever is calling that processTask method.

In terms of acquiring HttpServletRequest : semantically speaking, it is definitely wrong.

Reason : HttpServletRequest is an object that is created only when users send requests and is destroyed once the requested user action is completed. You simply can store it that way (from syntax angle) but you shouldn't (from semantic angle). You need to realize that the way how web application works is not exactly same as a desktop application (and don't observe them from the same angle).

Suggestion :

@RequestMapping(value = "process", method = RequestMethod.GET)
public @ResponseBody
DataResponse processTask(@RequestParam("workflow") final String workflow, HttpServletRequest request) {...}

In this way you will get the corresponding request each time the processTask method is called. (HttpServletRequest object is injected by @RequestMapping .)

(If you would like to preserve something through out a session, consider use a bean that is

Suggestion :
@Inject private UserService userService;
(assume we have a class registered called UserService .)

You cannot "inject" the HttpServletRequest the only way to use it as far as I know is to added as a method member. Like this:

@Controller
public class DataController {



    // .. some code here

    @RequestMapping(value = "process", method = RequestMethod.GET)
    public @ResponseBody
    DataResponse processTask(@RequestParam("workflow") final String workflow,HttpServletRequest request) {

        String ipAddress = request.getRemoteAddr();
        System.out.println(ipAddress);

}

look also at Spring MVC @AutoWired response not working

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