{"id":3195,"date":"2017-03-31T11:40:20","date_gmt":"2017-03-31T06:10:20","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=3195"},"modified":"2017-03-31T11:40:20","modified_gmt":"2017-03-31T06:10:20","slug":"avoid-java-code-jsp-files","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/avoid-java-code-jsp-files\/","title":{"rendered":"JAVA &#8211; How to avoid Java code in JSP files?"},"content":{"rendered":"<ul>\n<li>The use of scriptlets (those <% %> things) in JSP is indeed highly discouraged since the birth of taglibs (like JSTL) and EL (Expression Language, those ${} things) over a decade ago.<\/li>\n<\/ul>\n<h4 id=\"the-major-disadvantages-of-scriptlets-are\"><span style=\"color: #800000;\">The major disadvantages of scriptlets are:<\/span><\/h4>\n<ol>\n<li>Reusability: we can\u2019t reuse scriptlets.<\/li>\n<li>Replaceability: we can\u2019t make scriptlets abstract.<\/li>\n<li>OO-ability: we can\u2019t make use of inheritance\/composition.<\/li>\n<li>Debuggability: if scriptlet throws an exception halfway, we get a blank page.<\/li>\n<li>Testability: scriptlets are not unit-testable.<\/li>\n<li>Maintainability: per saldo more time is needed to maintain mingled\/cluttered\/duplicated code logic.<\/li>\n<\/ol>\n<ul>\n<li>Oracle itself also recommends in the JSP coding conventions to avoid use of scriptlets whenever the same functionality is possible by (tag) classes.<\/li>\n<li>From JSP 1.2 Specification, it is highly recommended that the JSP Standard Tag Library (JSTL) be used in your web application to help reduce the need for JSP scriptlets in your pages. Pages that use JSTL are, in general, easier to read and maintain.<\/li>\n<li>Avoid JSP scriptlets whenever tag libraries provide equivalent functionality. This makes pages easier to read and maintain, helps to separate business logic from presentation logic, and will make your pages easier to evolve into JSP 2.0-style pages (JSP 2.0 Specification supports but deemphasizes the use of scriptlets).<\/li>\n<li>the model-view-controller (MVC) design pattern to reduce coupling between the presentation tier from the business logic, JSP scriptlets should not be used for writing business logic. Rather, JSP scriptlets are used if necessary to transform data (also called \u201cvalue objects\u201d) returned from processing the client\u2019s requests into a proper client-ready format. Even then, this would be better done with a front controller servlet or a custom tag.<\/li>\n<li>How to replace scriptlets entirely depends on the sole purpose of the code\/logic. More than often this code is to be placed in a fullworthy Java class:<\/li>\n<li>If you want to invoke the same Java code on every request, less-or-more regardless of the requested page, e.g. checking if an user is logged in, then implement a filter and write code accordingly in doFilter() method.<\/li>\n<\/ul>\n<p><strong>E.g.:<\/strong><\/p>\n[pastacode lang=\u201djava\u201d manual=\u201dpublic%20void%20doFilter(ServletRequest%20request%2C%20ServletResponse%20response%2C%20FilterChain%20chain)%20throws%20ServletException%2C%20IOException%20%7B%0A%20%20%20%20if%20(((HttpServletRequest)%20request).getSession().getAttribute(%22user%22)%20%3D%3D%20null)%20%7B%0A%20%20%20%20%20%20%20%20((HttpServletResponse)%20response).sendRedirect(%22login%22)%3B%20%2F%2F%20Not%20logged%20in%2C%20redirect%20to%20login%20page.%0A%20%20%20%20%7D%20else%20%7B%0A%20%20%20%20%20%20%20%20chain.doFilter(request%2C%20response)%3B%20%2F%2F%20Logged%20in%2C%20just%20continue%20request.%0A%20%20%20%20%7D%0A%7D\u201d message=\u201dJava Code\u201d highlight=\u201d\u201d provider=\u201dmanual\u201d\/]\n<ul>\n<li>When mapped on an appropriate <url-pattern> covering the JSP pages of interest, then we don\u2019t need to copypaste the same piece of code over all JSP pages.<\/li>\n<li>If you want to invoke some Java code to preprocess a request, e.g. preloading some list from a database to display in some table, if necessary based on some query parameters, then implement a servlet and write code accordingly in doGet() method.<\/li>\n<\/ul>\n<p><strong>E.g.:<\/strong><\/p>\n[pastacode lang=\u201djava\u201d manual=\u201dprotected%20void%20doGet(HttpServletRequest%20request%2C%20HttpServletResponse%20response)%20throws%20ServletException%2C%20IOException%20%7B%0A%20%20%20%20try%20%7B%0A%20%20%20%20%20%20%20%20List%3CProduct%3E%20products%20%3D%20productService.list()%3B%20%2F%2F%20Obtain%20all%20products.%0A%20%20%20%20%20%20%20%20request.setAttribute(%22products%22%2C%20products)%3B%20%2F%2F%20Store%20products%20in%20request%20scope.%0A%20%20%20%20%20%20%20%20request.getRequestDispatcher(%22%2FWEB-INF%2Fproducts.jsp%22).forward(request%2C%20response)%3B%20%2F%2F%20Forward%20to%20JSP%20page%20to%20display%20them%20in%20a%20HTML%20table.%0A%20%20%20%20%7D%20catch%20(SQLException%20e)%20%7B%0A%20%20%20%20%20%20%20%20throw%20new%20ServletException(%22Retrieving%20products%20failed!%22%2C%20e)%3B%0A%20%20%20%20%7D%0A%7D\u201d message=\u201dJava Code\u201d highlight=\u201d\u201d provider=\u201dmanual\u201d\/]\n[ad type=\u201dbanner\u201d]\n<ul>\n<li>This way dealing with exceptions is easier.<\/li>\n<li>The DB is not accessed in the midst of JSP rendering, but far before the JSP is been displayed.<\/li>\n<li>There is a possibility to change the response whenever the DB access throws an exception.<\/li>\n<li>In the above example, the default error 500 page will be displayed which you can anyway customize by an <error-page> in web.xml.<\/li>\n<li>If you want to invoke some Java code to preprocess a request, e.g. preloading some list from a database to display in some table, if necessary based on some query parameters, then implement a servlet and write code accordingly in doGet() method.<\/li>\n<\/ul>\n[pastacode lang=\u201djava\u201d manual=\u201dE.g.%3A%0A%0Aprotected%20void%20doGet(HttpServletRequest%20request%2C%20HttpServletResponse%20response)%20throws%20ServletException%2C%20IOException%20%7B%0A%20%20%20%20try%20%7B%0A%20%20%20%20%20%20%20%20List%3CProduct%3E%20products%20%3D%20productService.list()%3B%20%2F%2F%20Obtain%20all%20products.%0A%20%20%20%20%20%20%20%20request.setAttribute(%22products%22%2C%20products)%3B%20%2F%2F%20Store%20products%20in%20request%20scope.%0A%20%20%20%20%20%20%20%20request.getRequestDispatcher(%22%2FWEB-INF%2Fproducts.jsp%22).forward(request%2C%20response)%3B%20%2F%2F%20Forward%20to%20JSP%20page%20to%20display%20them%20in%20a%20HTML%20table.%0A%20%20%20%20%7D%20catch%20(SQLException%20e)%20%7B%0A%20%20%20%20%20%20%20%20throw%20new%20ServletException(%22Retrieving%20products%20failed!%22%2C%20e)%3B%0A%20%20%20%20%7D%0A%7D\u201d message=\u201dJava Code\u201d highlight=\u201d\u201d provider=\u201dmanual\u201d\/]\n<ul>\n<li>This way dealing with exceptions is easier.<\/li>\n<li>The DB is not accessed in the midst of JSP rendering, but far before the JSP is been displayed.<\/li>\n<li>There is a possibility to change the response whenever the DB access throws an exception.<\/li>\n<li>In the above example, the default error 500 page will be displayed which you can anyway customize by an <error-page> in web.xml.<\/li>\n<li>If you want to invoke some Java code to postprocess a request, e.g. processing a form submit, then implement a servlet and write code accordingly in doPost() method.<\/li>\n<\/ul>\n<p>E.g.:<\/p>\n[pastacode lang=\u201djava\u201d manual=\u201dprotected%20void%20doPost(HttpServletRequest%20request%2C%20HttpServletResponse%20response)%20throws%20ServletException%2C%20IOException%20%7B%0A%20%20%20%20String%20username%20%3D%20request.getParameter(%22username%22)%3B%0A%20%20%20%20String%20password%20%3D%20request.getParameter(%22password%22)%3B%0A%20%20%20%20User%20user%20%3D%20userService.find(username%2C%20password)%3B%0A%0A%20%20%20%20if%20(user%20!%3D%20null)%20%7B%0A%20%20%20%20%20%20%20%20request.getSession().setAttribute(%22user%22%2C%20user)%3B%20%2F%2F%20Login%20user.%0A%20%20%20%20%20%20%20%20response.sendRedirect(%22home%22)%3B%20%2F%2F%20Redirect%20to%20home%20page.%0A%20%20%20%20%7D%20else%20%7B%0A%20%20%20%20%20%20%20%20request.setAttribute(%22message%22%2C%20%22Unknown%20username%2Fpassword.%20Please%20retry.%22)%3B%20%2F%2F%20Store%20error%20message%20in%20request%20scope.%0A%20%20%20%20%20%20%20%20request.getRequestDispatcher(%22%2FWEB-INF%2Flogin.jsp%22).forward(request%2C%20response)%3B%20%2F%2F%20Forward%20to%20JSP%20page%20to%20redisplay%20login%20form%20with%20error.%0A%20%20%20%20%7D%0A%7D\u201d message=\u201dJava Code\u201d highlight=\u201d\u201d provider=\u201dmanual\u201d\/]\n[ad type=\u201dbanner\u201d]\n<ul>\n<li>This way dealing with different result page destinations is easier: redisplaying the form with validation errors in case of an error (in this particular example you can redisplay it using ${message} in EL), or just taking to the desired target page in case of success.<\/li>\n<li>If you want to invoke some Java code to control the execution plan and\/or the destination of the request and the response, then implement a servlet according the MVC\u2019s Front Controller Pattern.<\/li>\n<\/ul>\n<p>E.g.:<\/p>\n[pastacode lang=\u201djava\u201d manual=\u201dprotected%20void%20service(HttpServletRequest%20request%2C%20HttpServletResponse%20response)%20throws%20ServletException%2C%20IOException%20%7B%0A%20%20%20%20try%20%7B%0A%20%20%20%20%20%20%20%20Action%20action%20%3D%20ActionFactory.getAction(request)%3B%0A%20%20%20%20%20%20%20%20String%20view%20%3D%20action.execute(request%2C%20response)%3B%0A%0A%20%20%20%20%20%20%20%20if%20(view.equals(request.getPathInfo().substring(1))%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20request.getRequestDispatcher(%22%2FWEB-INF%2F%22%20%2B%20view%20%2B%20%22.jsp%22).forward(request%2C%20response)%3B%0A%20%20%20%20%20%20%20%20%7D%20else%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20response.sendRedirect(view)%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%7D%20catch%20(Exception%20e)%20%7B%0A%20%20%20%20%20%20%20%20throw%20new%20ServletException(%22Executing%20action%20failed.%22%2C%20e)%3B%0A%20%20%20%20%7D%0A%7D\u201d message=\u201dJava Code\u201d highlight=\u201d\u201d provider=\u201dmanual\u201d\/]\n<p>Or just adopt a MVC framework like JSF, Spring MVC, Wicket, etc so that you end up with just a JSP\/Facelets page and a Javabean class without the need for a custom servlet.<\/p>\n<ul>\n<li>If you want to invoke some Java code to control the flow inside a JSP page, then you need to grab an (existing) flow control taglib like JSTL core.<\/li>\n<\/ul>\n<p>E.g. displaying List<Product> in a table:<\/p>\n[pastacode lang=\u201djava\u201d manual=\u201d%3C%25%40%20taglib%20uri%3D%22http%3A%2F%2Fjava.sun.com%2Fjsp%2Fjstl%2Fcore%22%20prefix%3D%22c%22%20%25%3E%0A\u2026%0A%3Ctable%3E%0A%20%20%20%20%3Cc%3AforEach%20items%3D%22%24%7Bproducts%7D%22%20var%3D%22product%22%3E%0A%20%20%20%20%20%20%20%20%3Ctr%3E%0A%20%20%20%20%20%20%20%20%20%20%20%20%3Ctd%3E%24%7Bproduct.name%7D%3C%2Ftd%3E%0A%20%20%20%20%20%20%20%20%20%20%20%20%3Ctd%3E%24%7Bproduct.description%7D%3C%2Ftd%3E%0A%20%20%20%20%20%20%20%20%20%20%20%20%3Ctd%3E%24%7Bproduct.price%7D%3C%2Ftd%3E%0A%20%20%20%20%20%20%20%20%3C%2Ftr%3E%0A%20%20%20%20%3C%2Fc%3AforEach%3E%0A%3C%2Ftable%3E\u201d message=\u201dJava Code\u201d highlight=\u201d\u201d provider=\u201dmanual\u201d\/]\n<p>With XML-style tags which fits nicely among all that HTML, the code is better readable than a bunch of scriptlets with various opening and closing braces. An easy aid is to configure our web application to throw an exception whenever scriptlets are still been used by adding the following piece<\/p>\n<h4 id=\"web-xml\"><span style=\"color: #800080;\">web.xml:<\/span><\/h4>\n[pastacode lang=\u201djava\u201d manual=\u201d%3Cjsp-config%3E%0A%20%20%20%20%3Cjsp-property-group%3E%0A%20%20%20%20%20%20%20%20%3Curl-pattern%3E*.jsp%3C%2Furl-pattern%3E%0A%20%20%20%20%20%20%20%20%3Cscripting-invalid%3Etrue%3C%2Fscripting-invalid%3E%0A%20%20%20%20%3C%2Fjsp-property-group%3E%0A%3C%2Fjsp-config%3E\u201d message=\u201dJava Code\u201d highlight=\u201d\u201d provider=\u201dmanual\u201d\/]\n<ul>\n<li>In Facelets, the successor of JSP, which is part of the Java EE provided MVC framework JSF, it is already not possible to use scriptlets. This way you\u2019re automatically forced to do things \u201cthe right way\u201d.<\/li>\n<li>If you want to invoke some Java code to access and display \u201cbackend\u201d data inside a JSP page, then you need to use EL (Expression Language), those ${} things.<\/li>\n<\/ul>\n<p>E.g. redisplaying submitted input values:<\/p>\n[pastacode lang=\u201djava\u201d manual=\u201d%3Cinput%20type%3D%22text%22%20name%3D%22foo%22%20value%3D%22%24%7Bparam.foo%7D%22%20%2F%3E%0A%0AThe%20%24%7Bparam.foo%7D%20displays%20the%20outcome%20of%20request.getParameter(%22foo%22).\u201d message=\u201dJava Code\u201d highlight=\u201d\u201d provider=\u201dmanual\u201d\/]\n[ad type=\u201dbanner\u201d]\n<ul>\n<li>If you want to invoke some utility Java code directly in the JSP page (typically public static methods), then you need to define them as EL functions. There\u2019s a standard functions taglib in JSTL, but you can also easily create functions yourself.<\/li>\n<li>An example how JSTL fn:escapeXml is useful to prevent XSS attacks.<\/li>\n<\/ul>\n[pastacode lang=\u201djava\u201d manual=\u201d%3C%25%40%20taglib%20uri%3D%22http%3A%2F%2Fjava.sun.com%2Fjsp%2Fjstl%2Ffunctions%22%20prefix%3D%22fn%22%20%25%3E%0A\u2026%0A%3Cinput%20type%3D%22text%22%20name%3D%22foo%22%20value%3D%22%24%7Bfn%3AescapeXml(param.foo)%7D%22%20%2F%3E\u201d message=\u201dJava Code\u201d highlight=\u201d\u201d provider=\u201dmanual\u201d\/]\n<ul>\n<li>Note that the XSS sensitivity is in no way specifically related to Java\/JSP\/JSTL\/EL\/whatever, this problem needs to be taken into account in every webapplication we develop.<\/li>\n<li>The problem of scriptlets is that it provides no way of builtin preventions, at least not using the standard Java API.<\/li>\n<li>JSP\u2019s successor Facelets has already implicit HTML escaping, so don\u2019t consider XSS holes in Facelets.<\/li>\n<\/ul>\n<p>JSTL offers tags for conditionals, loops, sets, gets, etc. For example:<\/p>\n[pastacode lang=\u201djava\u201d manual=\u201d%3Cc%3Aif%20test%3D%22%24%7BsomeAttribute%20%3D%3D%20\u2019something\u2019%7D%22%3E%0A%20%20%20\u2026%0A%3C%2Fc%3Aif%3E\u201d message=\u201dJava Code\u201d highlight=\u201d\u201d provider=\u201dmanual\u201d\/]\n<ul>\n<li>JSTL works with request attributes \u2013 they are most often set in the request by a Servlet, which forwards to the JSP.<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>The use of scriptlets (those things) in JSP is indeed highly discouraged since the birth of taglibs (like JSTL) and EL (Expression Language, those ${} things) over a decade ago. The major disadvantages of scriptlets are: Reusability: we can\u2019t reuse scriptlets. Replaceability: we can\u2019t make scriptlets abstract. OO-ability: we can\u2019t make use of inheritance\/composition. Debuggability: [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2139],"tags":[5991,5994,5996,5995,5986,5990,5985,5992,5984,5993,5989,5987,5988],"class_list":["post-3195","post","type-post","status-publish","format-standard","hentry","category-java","tag-a-javabean-or-bean-is-a-java-class-that","tag-avoid-java-code-in-jsp-files","tag-code-conventions-for-the-javaserver-pages-technology-version","tag-how-to-avoid-java-code-in-jsp-files","tag-how-to-call-a-java-program-from-jsp","tag-how-to-write-jsp-code-in-java-class","tag-java-code-in-jsp-example","tag-java-code-inside-jsp-page","tag-java-in-jsp-example","tag-jsp-best-practices","tag-jsp-scriptlet-example","tag-jstl-can-help-to-avoid-validation","tag-serializing-java-objects-help-us-to"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/3195","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=3195"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/3195\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=3195"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=3195"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=3195"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}