简体   繁体   English

控制器库直接访问HttpServletRequest

[英]Controller library direct access to HttpServletRequest

I have numerous controllers in my application that extend a central controller class. 我的应用程序中有许多控制器可以扩展中央控制器类。 Currently, in every controller function, I have to pass the request into this function in order for my function to grab the current username. 目前,在每个控制器函数中,我必须将请求传递给此函数,以便我的函数获取当前用户名。 Is it possible for this controller class to get the request on it's own without requiring it as an extra parameter? 这个控制器类是否可以自己获取请求而不需要它作为额外的参数?

public class Controller {
    protected String environment;

    public Controller () {

    }

    public ModelAndView prepareModel (HttpServletRequest request, ModelAndView model) {
        contentDao.clearExpiredLocks();

        model.addObject("currentUser", contentDao.findUser(request.getRemoteUser()));

        //define current environment
        this.environment = (request.getRequestURL().indexOf("localhost") > 0) ? "dev" : "uat";
        model.addObject("environment", this.environment);

You can use something like this: 你可以使用这样的东西:

public abstract class AbstractController {

    protected HttpServletRequest req

    protected AbstractController(HttpServletRequest req) {
        this.req  = req
    }
}

public class ConcreteController extends AbstractController {

    protected ConcreteController(String name) {
        super(name);
    }

    private void getUserName(){
        this.req.getRemoteUser();
    }    
}

That's just one quick tip, I believe that there are more possibilities how to do that. 这只是一个快速提示,我相信如何做到这一点有更多的可能性。

You can get the current HttpServletRequest as follows: 您可以按如下方式获取当前的HttpServletRequest

HttpServletRequest request = (HttpServletRequest) RequestContextHolder
    .currentRequestAttributes()
    .resolveReference(RequestAttributes.REFERENCE_REQUEST); 

You can use this code in a method of your controller, or use it to expose request as a request-scoped bean and inject the corresponding scoped proxy as a field of your controller. 您可以在控制器的方法中使用此代码,或使用它将请求公开为请求范围的bean,并将相应的作用域代理注入控制器的字段。

In my case, What I did is : I get user MainController.getLoginPerson() and use all user's info in all controllers. 在我的例子中,我做的是:我获得用户MainController.getLoginPerson()并在所有控制器中使用所有用户的信息。 All controllers extends to MainController. 所有控制器都扩展到MainController。 Here is method MainController.getLoginPerson(): 这是方法MainController.getLoginPerson():

MainController.getLoginPerson() {
    // calls to authentication service method
    authenticationService.getLoginPerson();
}

authenticationService.getLoginPerson() {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            return (UserPrincipalImpl) auth.getPrincipal();
        } else {
            return null;
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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