我在弄清楚如何在Tomcat上运行的Java Web应用程序中出现特定条件后创建重定向到浏览器的问题。 我相信一定有一个简单的解决方案,但我的Java技能非常有限。
这是我正在使用的特定代码(从鳄梨酱身份验证直通复制):
if (req.getParameter("username") == null {
LOG.error("username is required");
throw new GuacamoleServerException("username is required");
}
我想用重定向回索引页面替换该异常。 在PHP中,我可以简单地这样做:
header("Location: https://site.domain.com/",TRUE,302);
不过,Java不会轻易放过我。 我能找到的最好的直接模拟是这样的:
response.sendRedirect("https://site.domain.com/");
但是,编译失败:
[ERROR] /home/dev/guacamole-client-0.9.9/extensions/guacamole-auth-passthrough/src/main/java/com/github/edouardswiac/guacamole/ext/PassthroughAuthProvider.java:[31,6] error: cannot find symbol
我发现了许多其他Java重定向的例子(包括这个其他的stackoverflow线程),但几乎所有的例子似乎都实现了单独的方法来实现重定向。 正如我所说,我的 java 技能是非常基本的,我不知道如何实际实现这样的东西,以便在 if 条件中使用/调用。
任何人都可以提供一些关于如何在上述条件下正确实现这一点的指示吗? 在这一点上,我几乎完全没有想法,非常感谢任何指导。 谢谢。
我建议在异常的捕获块中写response.sendRedirect()
。例如:
HttpServletResponse response = credentials.getResponse();
try{
if (req.getParameter("username") == null {
LOG.error("username is required");
throw new GuacamoleServerException("username is required");
}
catch(GuacamoleServerException e){
response.sendRedirect("https://site.domain.com/");
}
附言前提是您正在使用 Java Servlet。