您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何避免JSP文件中的Java代码?

如何避免JSP文件中的Java代码?

自从2001年 标签(例如JSTL)和EL(表达语言,那些东西)的诞生以来,在JSP中确实不建议使用scriptlet (这些<% %>东西)。

scriptlet 的主要缺点是:

Sun Oracle本身也建议在JSP编码约定中避免使用(标记)类可能具有相同功能scriptlet 。以下是一些相关的引用:

从JSP 1.2规范开始,强烈建议在您的Web应用程序中使用JSP标准标记库(JSTL),以帮助 页面中 。通常,使用JSTL的页面更易于阅读和维护。

只要有可能,只要标签库提供等效功能,就 。这使页面更易于阅读和维护,有助于将业务逻辑与表示逻辑分离,并使您的页面更易于演化为JSP 2.0样式的页面(JSP 2.0规范支持但不强调脚本的使用)。

本着采用模型视图控制器(MVC)设计模式以减少表示层与业务逻辑之间的耦合的精神, 编写业务逻辑。相反,如果有必要,可以使用JSP scriptlet将处理客户端请求所返回的数据(也称为“值对象”)转换为适当的客户端就绪格式。即使这样,最好还是使用前端控制器servlet或自定义标签来完成。

        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页面上复制粘贴同一段代码

        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

        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),或只是把到所需的目标页面在成功的情况下。

        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。

        <%@ 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")

        <%@ 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漏洞。

java 2022/1/1 18:14:52 有449人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶