jsp:在Java中转发而不使用JSP标签?
是否有一个纯 Java 相当于
例如,我当前有一个类似这样的 JSP 页面:
<%
String errorMessage = SomeClass.getInstance().doSomething();
if (errorMessage != null) {
session.setAttribute("error", errorMessage);
%>
<jsp:forward page="error.jsp" />
<%
} else {
String url = response.encodeRedirectURL("index.jsp");
response.sendRedirect(url);
}
%>
必须打破 <% ... %> 使用 jsp:forward 的块很丑陋,并且由于缩进等原因而使其难以阅读。
那么,我可以在Java代码中进行转发而不使用JSP标签吗?
像这样的东西将是理想的:
<%
String errorMessage = SomeClass.getInstance().doSomething();
if (errorMessage != null) {
session.setAttribute("error", errorMessage);
someObject.forward("error.jsp");
} else {
String url = response.encodeRedirectURL("index.jsp");
response.sendRedirect(url);
}
%>
Is there a pure-Java equivalent to <jsp:forward page="..." /> that I can use within a <% ... %> block?
For example, I currently have a JSP page something like this:
<%
String errorMessage = SomeClass.getInstance().doSomething();
if (errorMessage != null) {
session.setAttribute("error", errorMessage);
%>
<jsp:forward page="error.jsp" />
<%
} else {
String url = response.encodeRedirectURL("index.jsp");
response.sendRedirect(url);
}
%>
Having to break the <% ... %> block to use the jsp:forward is ugly and makes it harder to read due to indentation, among other things.
So, can I do the forward in the Java code without use the JSP tag?
Something like this would be ideal:
<%
String errorMessage = SomeClass.getInstance().doSomething();
if (errorMessage != null) {
session.setAttribute("error", errorMessage);
someObject.forward("error.jsp");
} else {
String url = response.encodeRedirectURL("index.jsp");
response.sendRedirect(url);
}
%>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在寻找的
someObject
是 pageContext。该对象在 JSP 中隐式定义,因此您可以像这样使用它:
The
someObject
you are looking for is pageContext.This object is implicitly defined in JSP, so you can use it like this:
如果可以的话,您确实应该尝试避免 scriplet,并且在您的情况下,您正在做的很多事情都可以用 JSTL 代码替换。 以下示例的替换更加清晰,IMO:
理想情况下,您可以修改 error.jsp,以便甚至不需要在会话中设置错误消息,但我不想对您的设计进行太多更改。
You really should try and avoid scriplets if you can, and in your case, a lot of what you are doing can be replaced with JSTL code. The following replacement for your example is much cleaner, IMO:
Ideally, you'd modify error.jsp so that the error message doesn't even need to be set in the session, but I didn't want to change your design too much.
一个简单的方法:
更好的方法:
从 servlet 调用 doSomething()。
在 web.xml 中设置错误页面
A simple approach:
Better approach:
Invoke the doSomething() from a servlet.
Set your error page in web.xml