簡體   English   中英

從Java調用Controller方法

[英]Call Controller method from Java

我想通過Java類調用Controller的方法,所以我可以返回一個特定的視圖。 在這種情況下,我有一個簡短的ID列表; 如果當前用戶的ID不在該列表中,則重定向到視圖invalidUser。

我可以使用Ajax或按鈕在客戶端執行此操作: onclick="location.href='/invalidUser'

但我不清楚如何從Java類調用ViewsController的invalidUser()方法。

如何在invalidUserRedirect()方法中使用Java? 我想從HttpServletRequest獲取基本URL,如下所示: 在Spring MVC中獲取Root / Base Url ,然后對baseUrl +“/ invalidUser”進行http調用,但這似乎不是正確的方法。

AuthService:

@Service
public class AuthService {

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

視圖控制器:

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

}

從您的瀏覽器調用控制器類。 您不應該從服務類調用Controller方法。 您的控制器方法應該調用您的服務類

Controller類通常用於根據業務邏輯重定向應用程序流。 控制器中的大部分方法都標有@RequestMapping注釋,即使您能夠從服務調用控制器方法,它也無法實現目的,因為Controller的返回類型是特定的視圖。 您必須編寫AuthenticationFailureHandler的實現來實現該功能。 這可以通過彈簧安全性輕松實現

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");
} }

在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);
      }

控制器必須根據用戶請求確定要調用的服務。
該服務不確定控制器。
我認為這不是好習慣。
您的控制器應該是這樣的:

@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