Can Not Find the Tag Library Descriptor for "Http://java.sun.com/jsp/jstl/core"

In this Java tutorial, we're going to help you understand the process of coding a basic Coffee web application that manages a drove of books with the basic feature: list, insert, update, delete (or CURD operations - Create, Update, Read and Delete). The application looks something similar this:

Book Store Application home page

You volition learn to how to build this awarding using the following technologies:

  • Java Servlets and Java Server Pages (JSP)
  • JSP Standard Tag Library (JSTL)
  • Java Database Connectivity (JDBC)
  • MySQL database
  • Apache Tomcat Server

We use Eclipse IDE with Maven to develop the project.

1. Creating MySQL Database

For simplicity, nosotros have but one tabular array. Execute the following MySQL script to create a database named Bookstore and a tabular array named Volume :

CREATE DATABASE 'Bookstore'; USE Bookstore;  CREATE TABLE `book` (   `book_id` int(11) Non NULL AUTO_INCREMENT,   `title` varchar(128) Non Cypher,   `author` varchar(45) NOT Cypher,   `price` bladder Not NULL,   PRIMARY KEY (`book_id`),   UNIQUE Central `book_id_UNIQUE` (`book_id`),   UNIQUE KEY `title_UNIQUE` (`championship`) ) ENGINE=InnoDB AUTO_INCREMENT=eleven DEFAULT CHARSET=latin1

The table volume has structure like this:

book tabe structure

You can use either MySQL Command Line Customer or MySQL Workbench tool to create the database.

2. Creating Eclipse Project with Maven

In Eclipse IDE, click File > New > Dynamic Web Project to create a new Java dynamic web project. Name the project as Bookstore:

New dynamic web project

Call up to cull Target runtime as Apache Tomcat v8.0 and Dynamic web module version every bit three.i (this is the Coffee servlet version).

Click Terminate. So convert this project to a Maven project past right click on the projection, select Configure > Convert to Maven Projection, every bit shown below:

Convert to Maven project

Y'all need to enter information to create Maven POM file, such as group ID, antiquity ID, etc. Then add the post-obit dependencies to the pom.xml file:

<dependencies> 	<dependency> 		<groupId>javax.servlet</groupId> 		<artifactId>javax.servlet-api</artifactId> 		<version>3.1.0</version> 		<scope>provided</scope> 	</dependency> 	<dependency> 		<groupId>javax.servlet.jsp</groupId> 		<artifactId>javax.servlet.jsp-api</artifactId> 		<version>2.iii.1</version> 		<scope>provided</scope> 	</dependency> 	<dependency> 		<groupId>jstl</groupId> 		<artifactId>jstl</artifactId> 		<version>ane.2</version> 	</dependency> 	<dependency> 		<groupId>mysql</groupId> 		<artifactId>mysql-connector-java</artifactId> 		<version>v.1.30</version> 	</dependency> </dependencies>        

As yous tin can see, the dependencies here are for Servlet, JSP, JSTL and MySQL connector Coffee (a JDBC commuter for MySQL).

And remember to create a Coffee package for the project, here we apply the package name cyberspace.codejava.javaee.bookstore .

3. Writing Model Form

Next, create a Java form named Book.coffee to model a book entity in the database with the following code:

bundle net.codejava.javaee.bookstore;  /**  * Book.java  * This is a model class represents a book entity  * @author www.codejava.net  *  */ public form Book { 	protected int id; 	protected Cord title; 	protected String writer; 	protected float price;  	public Book() { 	}  	public Book(int id) { 		this.id = id; 	}  	public Book(int id, String championship, Cord writer, bladder price) { 		this(title, author, price); 		this.id = id; 	} 	 	public Book(String title, Cord author, float price) { 		this.championship = championship; 		this.author = author; 		this.price = price; 	}  	public int getId() { 		return id; 	}  	public void setId(int id) { 		this.id = id; 	}  	public String getTitle() { 		return championship; 	}  	public void setTitle(String title) { 		this.title = title; 	}  	public String getAuthor() { 		return author; 	}  	public void setAuthor(String writer) { 		this.author = author; 	}  	public float getPrice() { 		return price; 	}  	public void setPrice(float price) { 		this.price = price; 	} }

Every bit you tin can see, this class has 4 fields according to four columns in the tabular array book in database: id, title, author and price.

4. Coding DAO class

Adjacent, we need to implement a Information Access Layer (DAO) class that provides CRUD (Create, Read, Update, Delete) operations for the table volume in database. Here'southward the full source code of the BookDAO class:

package internet.codejava.javaee.bookstore;  import coffee.sql.Connexion; import java.sql.DriverManager; import coffee.sql.PreparedStatement; import coffee.sql.ResultSet; import coffee.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List;  /**  * AbstractDAO.coffee  * This DAO class provides CRUD database operations for the table volume  * in the database.  * @author www.codejava.net  *  */ public class BookDAO { 	individual String jdbcURL; 	individual String jdbcUsername; 	private String jdbcPassword; 	individual Connection jdbcConnection; 	 	public BookDAO(String jdbcURL, Cord jdbcUsername, String jdbcPassword) { 		this.jdbcURL = jdbcURL; 		this.jdbcUsername = jdbcUsername; 		this.jdbcPassword = jdbcPassword; 	} 	 	protected void connect() throws SQLException { 		if (jdbcConnection == null || jdbcConnection.isClosed()) { 			endeavor { 				Class.forName("com.mysql.jdbc.Driver"); 			} catch (ClassNotFoundException eastward) { 				throw new SQLException(e); 			} 			jdbcConnection = DriverManager.getConnection( 										jdbcURL, jdbcUsername, jdbcPassword); 		} 	} 	 	protected void disconnect() throws SQLException { 		if (jdbcConnection != null && !jdbcConnection.isClosed()) { 			jdbcConnection.shut(); 		} 	} 	 	public boolean insertBook(Volume book) throws SQLException { 		String sql = "INSERT INTO volume (championship, author, price) VALUES (?, ?, ?)"; 		connect(); 		 		PreparedStatement argument = jdbcConnection.prepareStatement(sql); 		argument.setString(1, book.getTitle()); 		statement.setString(2, book.getAuthor()); 		statement.setFloat(3, book.getPrice()); 		 		boolean rowInserted = statement.executeUpdate() > 0; 		statement.shut(); 		disconnect(); 		return rowInserted; 	} 	 	public List<Book> listAllBooks() throws SQLException { 		List<Book> listBook = new ArrayList<>(); 		 		String sql = "SELECT * FROM book"; 		 		connect(); 		 		Statement statement = jdbcConnection.createStatement(); 		ResultSet resultSet = statement.executeQuery(sql); 		 		while (resultSet.adjacent()) { 			int id = resultSet.getInt("book_id"); 			String championship = resultSet.getString("championship"); 			String writer = resultSet.getString("author"); 			float cost = resultSet.getFloat("toll"); 			 			Book book = new Volume(id, title, author, toll); 			listBook.add(book); 		} 		 		resultSet.shut(); 		statement.close(); 		 		disconnect(); 		 		render listBook; 	} 	 	public boolean deleteBook(Book book) throws SQLException { 		Cord sql = "DELETE FROM volume where book_id = ?"; 		 		connect(); 		 		PreparedStatement statement = jdbcConnection.prepareStatement(sql); 		argument.setInt(1, book.getId()); 		 		boolean rowDeleted = argument.executeUpdate() > 0; 		statement.close(); 		disconnect(); 		render rowDeleted;		 	} 	 	public boolean updateBook(Volume book) throws SQLException { 		String sql = "UPDATE book SET title = ?, author = ?, price = ?"; 		sql += " WHERE book_id = ?"; 		connect(); 		 		PreparedStatement statement = jdbcConnection.prepareStatement(sql); 		statement.setString(one, book.getTitle()); 		argument.setString(two, book.getAuthor()); 		statement.setFloat(three, book.getPrice()); 		statement.setInt(4, book.getId()); 		 		boolean rowUpdated = statement.executeUpdate() > 0; 		statement.close(); 		disconnect(); 		return rowUpdated;		 	} 	 	public Book getBook(int id) throws SQLException { 		Book book = null; 		String sql = "SELECT * FROM volume WHERE book_id = ?"; 		 		connect(); 		 		PreparedStatement statement = jdbcConnection.prepareStatement(sql); 		statement.setInt(1, id); 		 		ResultSet resultSet = statement.executeQuery(); 		 		if (resultSet.next()) { 			String title = resultSet.getString("title"); 			Cord author = resultSet.getString("author"); 			float toll = resultSet.getFloat("price"); 			 			book = new Book(id, championship, author, toll); 		} 		 		resultSet.close(); 		statement.close(); 		 		return book; 	} }

As yous can run into, the JDBC connexion data is injected to this course via its constructor. And the following methods are for Grime operations:

  • Create: insertBook(Book) - this inserts a new row into the table book.
  • Read: listAllBooks() - this retrieves all rows; and getBook(id) - returns a specific row based on the main key value (ID).
  • Update: updateBook(Book) - this updates an existing row in the database.
  • Delete: deleteBook(Book) - this removes an existing row in the database based on the primary key value (ID).

For detailed instructions on CRUD operations with JDBC, see JDBC Tutorial: SQL Insert, Select, Update, and Delete Examples.

5. Writing Book List JSP Folio

Next, create a JSP folio for displaying all books from the database. The following is code of the BookList.jsp page under the WebContent directory in the projection:

<%@ page language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8"%> <%@ taglib uri="http://coffee.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> 	<title>Books Store Application</title> </head> <body> 	<centre> 		<h1>Books Direction</h1>         <h2>         	<a href="/new">Add New Book</a>         	&nbsp;&nbsp;&nbsp;         	<a href="/listing">Listing All Books</a>         	         </h2> 	</center>     <div align="centre">         <tabular array border="i" cellpadding="5">             <explanation><h2>List of Books</h2></caption>             <tr>                 <th>ID</thursday>                 <th>Title</th>                 <thursday>Author</th>                 <th>Price</th>                 <th>Deportment</th>             </tr>             <c:forEach var="book" items="${listBook}">                 <tr>                     <td><c:out value="${volume.id}" /></td>                     <td><c:out value="${book.championship}" /></td>                     <td><c:out value="${book.author}" /></td>                     <td><c:out value="${book.price}" /></td>                     <td>                     	<a href="/edit?id=<c:out value='${book.id}' />">Edit</a>                     	&nbsp;&nbsp;&nbsp;&nbsp;                     	<a href="/delete?id=<c:out value='${book.id}' />">Delete</a>                    	                     </td>                 </tr>             </c:forEach>         </table>     </div>	 </torso> </html>

In this JSP folio, we use JSTL to display records of the tabular array volume from database. The listBook object volition be passed from a servlet which we will create later.

On running, this folio looks something like this:

Book Store Application home page

Every bit you tin see, on this page we take two hyperlinks at the elevation menu for creating a new book (Add New Book) and showing all books (Listing All Books). In addition, for each individual volume there are 2 links for editing (Edit) and deleting (Delete).

vi. Writing Book Grade JSP Folio

Next, we create a JSP folio for creating a new book called BookForm.jsp . Hither'due south its full source code:

<%@ page language="java" contentType="text/html; charset=UTF-eight"     pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> 	<championship>Books Store Application</championship> </head> <trunk> 	<center> 		<h1>Books Management</h1>         <h2>         	<a href="/new">Add New Volume</a>         	&nbsp;&nbsp;&nbsp;         	<a href="/list">List All Books</a>         	         </h2> 	</center>     <div align="middle"> 		<c:if examination="${volume != zip}"> 			<grade action="update" method="post">         </c:if>         <c:if test="${book == null}"> 			<grade activity="insert" method="post">         </c:if>         <table edge="1" cellpadding="5">             <caption>             	<h2>             		<c:if test="${book != null}">             			Edit Volume             		</c:if>             		<c:if examination="${book == zero}">             			Add New Book             		</c:if>             	</h2>             </explanation>         		<c:if test="${book != null}">         			<input type="hidden" proper noun="id" value="<c:out value='${book.id}' />" />         		</c:if>                         <tr>                 <th>Title: </th>                 <td>                 	<input type="text" name="championship" size="45"                 			value="<c:out value='${book.title}' />"                 		/>                 </td>             </tr>             <tr>                 <th>Author: </th>                 <td>                 	<input type="text" name="author" size="45"                 			value="<c:out value='${book.writer}' />"                 	/>                 </td>             </tr>             <tr>                 <th>Price: </th>                 <td>                 	<input type="text" proper noun="price" size="5"                 			value="<c:out value='${book.price}' />"                 	/>                 </td>             </tr>             <tr>             	<td colspan="2" align="center">             		<input type="submit" value="Save" />             	</td>             </tr>         </table>         </form>     </div>	 </body> </html>

This folio will be served for both creating a new and editing an existing volume. In editing manner, the servlet will laissez passer a Book object to the request and nosotros use the JSTL'southward <c:if> tag to determine whether this object is bachelor or not. If available (not null) the course is in editing mode, otherwise it is in creating mode.

On running, this folio shows new grade like this:

Add New Book

And on editing mode:

Edit Book

We'll see how to connect the DAO class with the JSP pages based on user's requests in the next department: creating the servlet class.

vii. Coding Controller Servlet Class

At present, the most hard simply interesting part is implement a Java Servlet that acts equally a page controller to handle all requests from the client. Let's look at the code commencement:

bundle net.codejava.javaee.bookstore;  import coffee.io.IOException; import java.sql.SQLException; import java.util.List;  import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;  /**  * ControllerServlet.coffee  * This servlet acts as a folio controller for the application, handling all  * requests from the user.  * @author www.codejava.net  */ public class ControllerServlet extends HttpServlet { 	individual static last long serialVersionUID = 1L; 	private BookDAO bookDAO;  	public void init() { 		Cord jdbcURL = getServletContext().getInitParameter("jdbcURL"); 		String jdbcUsername = getServletContext().getInitParameter("jdbcUsername"); 		String jdbcPassword = getServletContext().getInitParameter("jdbcPassword");  		bookDAO = new BookDAO(jdbcURL, jdbcUsername, jdbcPassword);  	}  	protected void doPost(HttpServletRequest request, HttpServletResponse response) 			throws ServletException, IOException { 		doGet(request, response); 	}  	protected void doGet(HttpServletRequest request, HttpServletResponse response) 			throws ServletException, IOException { 		Cord action = request.getServletPath();  		try { 			switch (action) { 			case "/new": 				showNewForm(request, response); 				intermission; 			case "/insert": 				insertBook(request, response); 				suspension; 			case "/delete": 				deleteBook(request, response); 				suspension; 			example "/edit": 				showEditForm(asking, response); 				break; 			example "/update": 				updateBook(asking, response); 				pause; 			default: 				listBook(request, response); 				suspension; 			} 		} take hold of (SQLException ex) { 			throw new ServletException(ex); 		} 	}  	private void listBook(HttpServletRequest request, HttpServletResponse response) 			throws SQLException, IOException, ServletException { 		List<Volume> listBook = bookDAO.listAllBooks(); 		asking.setAttribute("listBook", listBook); 		RequestDispatcher dispatcher = request.getRequestDispatcher("BookList.jsp"); 		dispatcher.forward(asking, response); 	}  	private void showNewForm(HttpServletRequest request, HttpServletResponse response) 			throws ServletException, IOException { 		RequestDispatcher dispatcher = asking.getRequestDispatcher("BookForm.jsp"); 		dispatcher.forwards(request, response); 	}  	private void showEditForm(HttpServletRequest request, HttpServletResponse response) 			throws SQLException, ServletException, IOException { 		int id = Integer.parseInt(request.getParameter("id")); 		Book existingBook = bookDAO.getBook(id); 		RequestDispatcher dispatcher = asking.getRequestDispatcher("BookForm.jsp"); 		request.setAttribute("book", existingBook); 		dispatcher.forward(request, response);  	}  	individual void insertBook(HttpServletRequest request, HttpServletResponse response)  			throws SQLException, IOException { 		String title = request.getParameter("title"); 		Cord author = request.getParameter("author"); 		float price = Float.parseFloat(request.getParameter("price"));  		Book newBook = new Book(championship, author, price); 		bookDAO.insertBook(newBook); 		response.sendRedirect("list"); 	}  	individual void updateBook(HttpServletRequest request, HttpServletResponse response)  			throws SQLException, IOException { 		int id = Integer.parseInt(request.getParameter("id")); 		String title = request.getParameter("title"); 		String writer = request.getParameter("author"); 		float price = Float.parseFloat(asking.getParameter("price"));  		Book volume = new Book(id, title, author, price); 		bookDAO.updateBook(book); 		response.sendRedirect("list"); 	}  	private void deleteBook(HttpServletRequest request, HttpServletResponse response)  			throws SQLException, IOException { 		int id = Integer.parseInt(asking.getParameter("id"));  		Book book = new Book(id); 		bookDAO.deleteBook(book); 		response.sendRedirect("list");  	} }

Outset, look at the init() method which instantiates an case of the BookDAO class when the servlet is instantiated for the first time. The JDBC connection information will be read from Servlet's context parameters. This method is invoked just ane time during life cycle of the servlet and then it's reasonable to put the DAO instantiation lawmaking here:

public void init() { 	String jdbcURL = getServletContext().getInitParameter("jdbcURL"); 	String jdbcUsername = getServletContext().getInitParameter("jdbcUsername"); 	String jdbcPassword = getServletContext().getInitParameter("jdbcPassword");  	bookDAO = new BookDAO(jdbcURL, jdbcUsername, jdbcPassword);  }

Next, nosotros can see this servlet handles both Become and POST requests every bit the doPost() method invokes the doGet() which handles all the request:

protected void doGet(HttpServletRequest request, HttpServletResponse response) 		throws ServletException, IOException { 	String action = asking.getServletPath();  	try { 		switch (action) { 		case "/new": 			showNewForm(request, response); 			interruption; 		example "/insert": 			insertBook(asking, response); 			interruption; 		case "/delete": 			deleteBook(request, response); 			break; 		case "/edit": 			showEditForm(asking, response); 			break; 		example "/update": 			updateBook(request, response); 			break; 		default: 			listBook(request, response); 			intermission; 		} 	} take hold of (SQLException ex) { 		throw new ServletException(ex); 	} }

Based on the request URL (starts with /edit, /list, /new, etc) the servlet calls the respective methods. Here nosotros examine one method for example:

private void listBook(HttpServletRequest asking, HttpServletResponse response) 		throws SQLException, IOException, ServletException { 	List<Volume> listBook = bookDAO.listAllBooks(); 	request.setAttribute("listBook", listBook); 	RequestDispatcher dispatcher = request.getRequestDispatcher("BookList.jsp"); 	dispatcher.forward(request, response); }

This method uses the DAO grade to retrieve all books from the database, then forward to the BookList.jsp page for displaying the effect. Similar logic is implemented for the rest methods.

I recommend you to read this famous Servlet and JSP book to primary Java servlet and JSP.

8. Configuring Spider web.xml

To brand the ControllerServlet intercepts all requests, we take to configure its mapping in the web deployment descriptor spider web.xml file. Open the spider web.xml file nether WebContent\WEB-INF directory and update it with the following code:

<?xml version="1.0" encoding="UTF-8"?> <spider web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 	xmlns="http://xmlns.jcp.org/xml/ns/javaee" 	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee  		http://xmlns.jcp.org/xml/ns/javaee/spider web-app_3_1.xsd" 	id="WebApp_ID" version="3.1"> 	<display-proper name>Books Management Spider web Awarding</brandish-proper noun>  	<context-param> 		<param-name>jdbcURL</param-name> 		<param-value>jdbc:mysql://localhost:3306/bookstore</param-value> 	</context-param>  	<context-param> 		<param-proper noun>jdbcUsername</param-name> 		<param-value>root</param-value> 	</context-param>  	<context-param> 		<param-name>jdbcPassword</param-name> 		<param-value>[email protected]</param-value> 	</context-param>  	<servlet> 		<servlet-name>ControllerServlet</servlet-name> 		<servlet-form>net.codejava.javaee.bookstore.ControllerServlet</servlet-form> 	</servlet>  	<servlet-mapping> 		<servlet-proper noun>ControllerServlet</servlet-name> 		<url-blueprint>/</url-blueprint> 	</servlet-mapping>  	<error-page> 		<exception-type>java.lang.Exception</exception-type> 		<location>/Error.jsp</location> 	</error-page> </web-app>

 Every bit you tin can meet, the <context-param> elements specify JDBC connection information (URL, username and password) for the DAO grade.

The <servlet> and <servlet-mapping> elements declare and specify URL mapping for the ControllerServlet course. The URL pattern / means this is the default servlet to handle all requests.

The <mistake> folio elements specify error treatment page for all kind of exceptions ( java.lang.Exception ) which may occur during the life of the awarding.

For details nigh fault treatment in Java web application, read this tutorial.

9. Writing Error JSP folio

Here'southward the lawmaking of the Error.jsp page which simply shows the exception message:

<%@ page language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8" isErrorPage="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  	"http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <championship>Error</title> </head> <body> 	<eye> 		<h1>Fault</h1> 		<h2><%=exception.getMessage() %><br/> </h2> 	</center>	 </body> </html>

It looks something like this when an mistake occurs:

Error page

10. Deploying and Testing the Application

And so far nosotros have completed the code of the project. It's fourth dimension to deploy and test the awarding to see how it works. Follow this tutorial in case you don't know how to add Apache Tomcat server in Eclipse.

Type the following URL in your spider web browser to access the Bookstore application:

http://localhost:8080/Bookstore

Showtime time, the list is empty because at that place hasn't any books yet:

Empty List

Click on the hyperlink Add New Book to begin calculation a new book:

Add New Book

Enter book information (title, writer and toll) and click Save. The application saves the volume and shows the listing, every bit shown beneath:

Newly Added Book

In this list, yous can click on the Edit and Delete hyperlinks to edit and delete a specific book.

That's how a uncomplicated Java web application with Serlvet, JSP, JDBC and MySQL is built. Nosotros promise yous notice this tutorial helpful and you can download the whole project under the Attachments section below.

If yous want to have a full video training, I recommend you to take my course on Udemy Coffee Servlet, JSP and Hide: Build a Consummate Website.

Related Tutorials:

  • Java Servlet and JSP for beginners
  • JDBC Create, Retrieve, Update and Delete (Grime) Tutorial
  • How to list database records in JSP
  • Handling Error for Java web applications

Other Java Servlet Tutorials:

  • Coffee Servlet Quick Start for beginners (XML)
  • Java Servlet for beginners (annotations)
  • Handling HTML course data with Coffee Servlet
  • Java File Download Servlet Example
  • Upload file to servlet without using HTML class
  • How to apply Cookies in Coffee web application
  • How to use Session in Java web application

Nearly the Author:

Nam Ha Minh is certified Coffee programmer (SCJP and SCWCD). He started programming with Java in the time of Java ane.four and has been falling in dear with Java since and then. Make friend with him on Facebook and sentry his Java videos yous YouTube.

Add annotate

haleywens1974.blogspot.com

Source: https://www.codejava.net/coding/jsp-servlet-jdbc-mysql-create-read-update-delete-crud-example

0 Response to "Can Not Find the Tag Library Descriptor for "Http://java.sun.com/jsp/jstl/core""

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel