简体   繁体   English

从Java调用Controller方法

[英]Call Controller method from Java

I would like to invoke a Controller's method via a Java class, so I can return a specific view. 我想通过Java类调用Controller的方法,所以我可以返回一个特定的视图。 In this case I have a short list of IDs; 在这种情况下,我有一个简短的ID列表; if the current user's ID is not in that list, redirect to a view invalidUser. 如果当前用户的ID不在该列表中,则重定向到视图invalidUser。

I can do it on the client-side with either Ajax or a button: onclick="location.href='/invalidUser' 我可以使用Ajax或按钮在客户端执行此操作: onclick="location.href='/invalidUser'

But I am not clear on how I can call the ViewsController's invalidUser() method from a Java class. 但我不清楚如何从Java类调用ViewsController的invalidUser()方法。

How can I do that with Java in the invalidUserRedirect() method? 如何在invalidUserRedirect()方法中使用Java? I was thinking to get the base URL from the HttpServletRequest as shown here: Get Root/Base Url In Spring MVC and then make an http call to baseUrl + "/invalidUser" but that does not seem like the right approach. 我想从HttpServletRequest获取基本URL,如下所示: 在Spring MVC中获取Root / Base Url ,然后对baseUrl +“/ invalidUser”进行http调用,但这似乎不是正确的方法。

AuthService: AuthService:

@Service
public class AuthService {

  public void invalidUserRedirect(HttpServletRequest request) {
    // Make call to invalidUser() in ViewsController
  }
}

Views Controller: 视图控制器:

@Controller
public class ViewsController {
  @RequestMapping(value = "/invalidUser", method = {RequestMethod.GET})
  public String invalidUser() {
    return "invalid";
  }

} }

Controller classes are called from your browser. 从您的浏览器调用控制器类。 You shouldn't call a Controller method from your service class. 您不应该从服务类调用Controller方法。 Your controller method should call invoke your service class 您的控制器方法应该调用您的服务类

Controller class generally used for redirecting flow of application based on your business logic. Controller类通常用于根据业务逻辑重定向应用程序流。 Most of all the method in controller are marked with @RequestMapping annotation, even though you are able to call the controller method from the service, it will not able to fulfill the purpose as the return type of Controller is resulting specific view. 控制器中的大部分方法都标有@RequestMapping注释,即使您能够从服务调用控制器方法,它也无法实现目的,因为Controller的返回类型是特定的视图。 You have to write implementation of AuthenticationFailureHandler to achieve the functionality. 您必须编写AuthenticationFailureHandler的实现来实现该功能。 This is easily achievable by spring security 这可以通过弹簧安全性轻松实现

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

@Component
public class MyAuthenticationFailureHandler  implements AuthenticationFailureHandler{

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
    AuthenticationException exception) throws IOException, ServletException {
    request.setAttribute("param", "invaliduser");
    response.sendRedirect("/domain/?error");
} }

Call this class in the Security class 在Security类中调用此类

@Autowired
 MyAuthenticationFailureHandler failureHandler;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
  http.formLogin()
                .loginPage(LOGIN_URL)
                .failureUrl(LOGIN_URL + "?error").permitAll()
                .authenticationDetailsSource(authDetailsSource)
                .successHandler(successHandler)
                .failureHandler(failureHandler);
      }

The controller must determine which services to invoke based on user requests. 控制器必须根据用户请求确定要调用的服务。
The service does not determine the controller. 该服务不确定控制器。
I think it is not good practice. 我认为这不是好习惯。
Your Controller should be like this: 您的控制器应该是这样的:

@Controller
public class ViewsController {

    @Autowired
    private UserValidator userValidator;

    @RequestMapping(value = "/testUser", method = { RequestMethod.GET })
    public String testUser(UserInfo userInfo) {
        //call service
        boolean isValidUser = userValidator.test(userInfo);
        if(isValidUser)
            return "validUserPage";
        else
            return "invalid";
    }
}

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

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