Saunders Evoichland99

  • Home
  • Sitemap
Home  ›  How to Read Values of Setattribute in Jsp Using Jstl

How to Read Values of Setattribute in Jsp Using Jstl

Written By Taylor Faing1939 Thursday, March 3, 2022 Add Comment Edit
  • Web log
  • About
  • Contact

Refactoring JSP Scriptlets using JSTL and MVC Architecture

Overview

The use of scriptlets in JSP pages is considered bad practise, and their employ has been discouraged by Oracle/Dominicus for over a decade.

The JSP Standard Tag Library (JSTL) was introduced equally a manner for JSP pages to get the data they need without embedding Coffee code.  It contains a standardized tag set which ways more than maintainable code and separation of concerns betwixt application layers.

In this article, we'll discuss the disadvantages of scriptlets and explore how we can use both JSTL and MVC architecture to improve our code.

The code examples in this article were tested using Tomcat viii.5 equally the server runtime.   This version confirms to the following specs: Servlet 3.i, JSP 2.3, and EL 3.0.

Life with Scriptlets

Scriptlets (<% ... %>) along with expressions (<%= %>) and declarations (<%! %>) are dissimilar means of inserting Java lawmaking in a JSP page.

Suppose we need to brandish a list of products from a database.  We could write a JSP page like this:

                  <%@ page import = "java.util.List, coffee.sql.*, com.codebyamir.demo.Product" %>  <%   Class.forName("com.mysql.jdbc.Driver");   Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "dbuser", "dbpass");  %>  <%!   public List<Product> getProducts(Connexion conn) throws SQLException {          List<Production> products = new ArrayList<>();          String sql = "SELECT id, name FROM product";     PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);     ResultSet resultSet = stmt.executeQuery();      while (resultSet.adjacent()) {       Product product = new Product(resultSet.getInt("id"), resultSet.getString("proper name");       products.add(product);     }      return products;   } %>  <!DOCTYPE html> <html>  <torso>   <ul class="product-listing">    <%     for (Product product : getProducts(conn)) {       out.print("<li>" + product.getName() + "</li>");     }   %>    </ul> </trunk>  </html>                

What's wrong with this?

A JSP folio should merely exist concerned with the view layer.   This page violates that principle.

It performs the following deportment:

  • Obtains a database connection
  • Issues a SQL query
  • Populates a listing with product objects
  • Displays the list of product names

Only the last action belongs in the view layer.

The code on the page is also non re-usable.  The getProducts() method exists hither and is not available to other pages.

Disadvantages of Scriptlets

We covered a few of these in the previous section.

  • Hard to Reuse:  We can't reuse code in scriptlets
  • Difficult to Test: Scriptlets are non unit-testable
  • Hard to Debug: An exception thrown past a scriptlet results in a blank page
  • Difficult to Maintain: More than fourth dimension and effort is required to maintain scriptlets

JSP Expression Language (EL)

JSP Expression Language (EL) provides access to data attributes and parameters using a unproblematic syntax:

${expression}                

EL can but be used to read values.  It does not back up writing values.  Information technology is "null friendly" meaning that if a given attribute or expression is goose egg, no exception is thrown.   It treats goose egg as 0 in math expressions and false in boolean expressions.

EL is enabled past default if information technology is supported by the application server.

Implicit Objects

EL defines a set of implicit objects we can use to become information.  Here are some of the commonly used objects:

Proper noun Description
pageContext The page context provides admission to servletContext, session, request, and response.
pageScope Maps page-scoped variable names to their values
requestScope Maps request-scoped variable names to their values
sessionScope Maps session-scoped variable names to their values
applicationScope Maps application-scoped variable names to their values
param Maps a request parameter proper noun to a single value
header Maps a asking header name to a unmarried value
cookie Maps a cookie name to a single cookie

We'll encounter how to use these later in the article.

JSP Standard Tag Library (JSTL)

There are 5 tag libraries in JSTL:

jstl.png

  • Cadre:Tags essential to any spider web application. Examples include looping, expression evaluation, and basic input and output.
  • Formatting:Tags used to parse information. Some of these tags will parse data, such as dates, differently based on the current locale.
  • Functions:Tags used for drove length and string manipulation.
  • XML:Tags that tin can exist used to admission XML elements.
  • SQL:Tags used to access relational databases.  These tags should not be used for production applications.  They are intended for prototyping.

Nosotros'll review some of the tags in the Core library.  The other libraries are exterior the telescopic of this commodity.

Installation

Tomcat doesn't come with JSTL so we'll demand to add together some JARs to our projection first.

Transmission

Download the post-obit JARs and add together them to WEB-INF/lib

                  <dependency>     <groupId>javax.servlet.jsp.jstl</groupId>     <artifactId>javax.servlet.jsp.jstl-api</artifactId>     <version>ane.2.ane</version> </dependency> <dependency>     <groupId>org.glassfish.web</groupId>     <artifactId>javax.servlet.jsp.jstl</artifactId>     <version>1.2.1</version>     <exclusions>          <!-- jstl-api was adding selvlet-api ii.5 and jsp-api-->         <exclusion>             <artifactId>jstl-api</artifactId>             <groupId>javax.servlet.jsp.jstl</groupId>         </exclusion>     </exclusions> </dependency>                

Tag Library URI

A tag library is identified by its URI.

When we want to employ a tag library in a JSP folio, we must import it using the URI and bind it to a prefix:

                  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/cadre" %>                

The prefix is capricious, simply the convention is to use "c" for core.

Mutual Core Tags

prepare tag

The ready tag allows the states to ready the value of an attribute in whatsoever scope.   If not specified, page scope is the default.

                  <c:set scope="request" var="name" value="Amir" /> <c:set var="city" value="Pittsburgh" />                

out tag

The out tag allows the states to print the value of an aspect stored in whatsoever scope.

                  My name is : <c:out value="${name}"/>                

EL will return the first non-zip value establish after searching page, request, session and application scopes (in that order).

if tag

The if tag allows the states to create conditional expressions.   At that place is no else clause so two conditionals are needed if we want to accept action on true and simulated atmospheric condition.

                  <c:set up var="age" value="xxx"/> <c:if examination="${age >= eighteen}">  <c:out value="You are eligible"/> </c:if> <c:if test="${age < 18}">  <c:out value="You are not eligible"/> </c:if>                

forEach tag

The foreach tag is used to loop over a drove.

We can employ the cookie implicit object to get a map of all the cookies bachelor to the current folio. The keys incorporate the cookie proper name ("JSESSIONID") and the values comprisejavax.servlet.Cookie objects.

Nosotros can utilize the forEach tag to iterate over the map and display each cookie name and value usingc:out

                  <h1>Bachelor Cookies</h3> <ul>   <c:forEach var="cookies" items="${cookie}">     <li>     <c:out value="${cookies.primal}"/>:      Cookie=<c:out value="${cookies.value}"/>,      	value=<c:out value="${cookies.value.value}"/>     </li>   </c:forEach> </ul>                

Life with JSTL and MVC

Let's refactor our previous lawmaking example and see how nosotros tin can improve information technology with JSTL and MVC.

Lawmaking

Model

We'll use the existing Product course every bit the model

                  package com.codebyamir.demo;   public grade Product {     individual int id;   private String name;      public Production(int id, String name) {     this.id = id;     this.name = name;   }      public int getId() {     render id;   }      public void setId(int id) {     this.id = id;   }      public String getName() {       return proper name;     }      public void setName(String proper name) {       this.proper noun = proper name;     }   }                

Repository

Outset, nosotros create a ProductRepository form to handle retrieval of the product list from the database.

                  package com.codebyamir.demo;  import java.sql.Connexion; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger;  public class ProductRepository {    private Connection conn;   private PreparedStatement argument;   individual ResultSet resultSet; 	   private Logger logger = Logger.getLogger(ProductRepository.class.getName());        public List<Product> list() {     Listing<Product> products = new ArrayList<>(); 		     try {       Class.forName("com.mysql.jdbc.Driver");       conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "dbuser", "dbpass");        String sql = "SELECT id, proper name FROM product";       statement = conn.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);       resultSet = statement.executeQuery();        while (resultSet.next()) {         Product product = new Product(resultSet.getInt("id"), resultSet.getString("proper name"));         products.add together(product);       }	         } catch (Exception ex) {       logger.severe(ex.getMessage());     } 	 	return products;   } }                

Service

Next, we create a ProductService class.   This layer typically contains business organisation logic and calls the repository layer.

                  package com.codebyamir.demo;  import java.util.List;  public class ProductService {    private ProductRepository productRepository = new ProductRepository(); 	   public Listing<Production> list() {     render productRepository.listing();   } }                

Controller

Side by side, we'll create a ProductServlet to handle incoming requests and telephone call the service to fetch the listing of products.

                  package com.codebyamir.demo;  import java.io.IOException; import java.util.List;  import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;  @WebServlet("/products") public grade ProductServlet extends HttpServlet { 	private static final long serialVersionUID = 1L;         	individual ProductService productService = new ProductService(); 	 	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 		List<Production> products = productService.list(); 		 		request.setAttribute("products", products); 		request.getRequestDispatcher("/products.jsp").frontwards(request, response); 	} }                

View

Finally, we create a products.jsp file that contains our JSTL code.

                  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/cadre" %>  <!DOCTYPE html> <html>  <body>    <ul class="product-list">     <c:forEach var="product" items="${products}">        <li>${product.proper name}</li>          </c:forEach>    </ul>  </body> </html>                

Considering nosotros added the request attribute in our servlet, the list of products is automatically available to usa when we reference the EL expression ${products} on line 10.

Disabling Scriptlets

Once nosotros've eliminated scriptlets from our project, information technology's a good idea to disable scriptlets at the web awarding level.  This will foreclose anyone from coming along and re-introducing scriptlets in the future.

This tin be configured in the web.xml file:

                  <jsp-config>   <jsp-property-group>     <url-design>*.jsp</url-design>      <scripting-invalid>true</scripting-invalid>   </jsp-property-group> </jsp-config>                

Any folio that contains scriptlet lawmaking will now render an HTTP 500 error:

HTTP Condition [500] – [Internal Server Mistake]                  Type                  Exception Report                  Message                  /scriptlets.jsp (line: [viii], column: [2]) Scripting elements ( &lt;%!, &lt;jsp:annunciation, &lt;%=, &lt;jsp:expression, &lt;%, &lt;jsp:scriptlet ) are disallowed here.                  Description                  The server encountered an unexpected status that prevented information technology from fulfilling the request.                

Why aren't my EL expressions getting evaluated?

In that location are a number of reasons this could happen:

  • Application server in question doesn't back up JSP 2.0.

  • The spider web.xml is not declared every bit Servlet 2.4 or higher.  Check this link for examples of spider web deployment descriptors.

  • The folio is configured to ignore EL expressions:

<%@ page isELIgnored="true" %>
  • The web.xml is configured to ignore EL expressions:

<el-ignored>true</el-ignored>

saundersevoichland99.blogspot.com

Source: https://www.codebyamir.com/blog/refactoring-jsp-scriptlets-using-jstl-and-mvc-architecture

Share this post

0 Response to "How to Read Values of Setattribute in Jsp Using Jstl"

Post a Comment

Newer Post Older Post Home
Subscribe to: Post Comments (Atom)

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel

Popular Post

  • Arbitrary Sample Sizes Are Simple and Easy to Apply
    Sample size definition The sample size is a term used in market research for defining the number...
  • KHS India at Brau Beviale – Focus on a major role in Southeast Asia
    Partho Ghose, executive vice president and board member of KHS ...
  • Can You Stratify a Continuous Variable
    3.5 - Bias, Confounding and Ef...



banner



Copyright - Saunders Evoichland99