我是Java EE的新手,我知道类似以下三行内容
<%= x+1 %> <%= request.getParameter("name") %> <%! counter++; %>
这是一种古老的编码方式,在JSP版本2中,存在一种避免在JSP文件中使用Java代码的方法。有人可以告诉我替代的JSP 2行吗,这种技术叫什么?
自从2001年 标签库(例如JSTL)和EL(表达语言,那些东西)的诞生以来,在JSP中确实不建议使用 scriptlet (这些<% %>东西)。
<% %>
scriptlet 的主要缺点是:
Sun Oracle本身也建议在JSP编码约定中避免使用(标记)类可能具有相同功能的 scriptlet 。以下是一些相关的引用:
从JSP 1.2规范开始,强烈建议在您的Web应用程序中使用JSP标准标记库(JSTL),以帮助 减少 页面中 对JSP scriptlet的需求 。通常,使用JSTL的页面更易于阅读和维护。 … 只要有可能,只要标签库提供等效功能,就 避免使用JSP scriptlet。这使页面更易于阅读和维护,有助于将业务逻辑与表示逻辑分离,并使您的页面更易于演化为JSP 2.0样式的页面(JSP 2.0规范支持但不强调脚本的使用)。 … 本着采用模型视图控制器(MVC)设计模式以减少表示层与业务逻辑之间的耦合的精神, 不应使用JSP脚本 编写业务逻辑。相反,如果有必要,可以使用JSP scriptlet将处理客户端请求所返回的数据(也称为“值对象”)转换为适当的客户端就绪格式。即使这样,最好还是使用前端控制器servlet或自定义标签来完成。
从JSP 1.2规范开始,强烈建议在您的Web应用程序中使用JSP标准标记库(JSTL),以帮助 减少 页面中 对JSP scriptlet的需求 。通常,使用JSTL的页面更易于阅读和维护。
…
只要有可能,只要标签库提供等效功能,就 避免使用JSP scriptlet。这使页面更易于阅读和维护,有助于将业务逻辑与表示逻辑分离,并使您的页面更易于演化为JSP 2.0样式的页面(JSP 2.0规范支持但不强调脚本的使用)。
本着采用模型视图控制器(MVC)设计模式以减少表示层与业务逻辑之间的耦合的精神, 不应使用JSP脚本 编写业务逻辑。相反,如果有必要,可以使用JSP scriptlet将处理客户端请求所返回的数据(也称为“值对象”)转换为适当的客户端就绪格式。即使这样,最好还是使用前端控制器servlet或自定义标签来完成。
如何 完全替换 scriptlet 取决于代码/逻辑的唯一目的。这段代码比以往更多地被放置在完全值得的Java类中:
doFilter()
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { if (((HttpServletRequest) request).getSession().getAttribute("user") == null) { ((HttpServletResponse) response).sendRedirect("login"); // Not logged in, redirect to login page. } else { chain.doFilter(request, response); // Logged in, just continue request. } }
当映射到适当的<url-pattern>覆盖感兴趣的JSP页面时,则无需在整个JSP页面上复制粘贴同一段代码。
<url-pattern>
doGet()
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { List<Product> products = productService.list(); // Obtain all products. request.setAttribute("products", products); // Store products in request scope. request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response); // Forward to JSP page to display them in a HTML table. } catch (SQLException e) { throw new ServletException("Retrieving products failed!", e); } }
这种处理异常的方法比较容易。在JSP渲染过程中,不能访问DB,但是要在显示JSP之前就可以访问DB。每当数据库访问引发异常时,您仍然可以更改响应。在上面的示例中,将显示默认错误500页面,您可以通过<error- page>in对其进行自定义web.xml。
<error- page>
web.xml
doPost()
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); User user = userService.find(username, password); if (user != null) { request.getSession().setAttribute("user", user); // Login user. response.sendRedirect("home"); // Redirect to home page. } else { request.setAttribute("message", "Unknown username/password. Please retry."); // Store error message in request scope. request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to JSP page to redisplay login form with error. } }
通过这种方式处理不同的结果页面的目的地更容易:重新显示在一个错误的情况下验证错误的形式(在这个特殊的例子,你可以使用重新显示${message}在EL),或只是把到所需的目标页面在成功的情况下。
${message}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Action action = ActionFactory.getAction(request); String view = action.execute(request, response); if (view.equals(request.getPathInfo().substring(1)) { request.getRequestDispatcher("/WEB-INF/" + view + ".jsp").forward(request, response); } else { response.sendRedirect(view); } } catch (Exception e) { throw new ServletException("Executing action failed.", e); } }
或只是采用MVC框架如JSF,SpringMVC,这样您最终只需要一个JSP/ Facelets页面和一个JavaBean类,而无需自定义servlet。
List<Product>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> ... <table> <c:forEach items="${products}" var="product"> <tr> <td>${product.name}</td> <td>${product.description}</td> <td>${product.price}</td> </tr> </c:forEach> </table>
使用XML样式的标签非常适合所有HTML,与一堆带有各种开合和结束大括号的scriptlet( “此结束大括号到底在哪里?”)相比,该代码具有更好的可读性(因而更易于维护)。一个简单的帮助是将Web应用程序配置为在仍然使用 _scriptlet_的情况下抛出异常,方法是将以下内容添加到web.xml:
<jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <scripting-invalid>true</scripting-invalid> </jsp-property-group> </jsp-config>
在Facelets的,JSP的继任者,它是JavaEE的一部分提供的MVC框架JSF,它已经 不 能够使用_小脚本_ 。这样,您将自动被迫以“正确的方式”做事。
${}
<input type="text" name="foo" value="${param.foo}" />
该${param.foo}显示器的结果request.getParameter("foo")。
${param.foo}
request.getParameter("foo")
public static
fn:escapeXml
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> ... <input type="text" name="foo" value="${fn:escapeXml(param.foo)}" />
请注意,XSS敏感性与Java / JSP / JSTL / EL /无关,无论如何,在您开发的 每个 Web应用程序中 都 必须考虑到此问题。 scriptlet 的问题在于,它无法提供内置的预防措施,至少没有使用标准的Java API。JSP的继任者Facelets已经具有隐式HTML转义,因此您不必担心Facelets中的XSS漏洞。