<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JSP &amp; Servlets &#8211; Tech-Freaks.com</title>
	<atom:link href="https://www.tech-freaks.com/java/jsp-servlets/feed" rel="self" type="application/rss+xml" />
	<link>https://www.tech-freaks.com</link>
	<description></description>
	<lastBuildDate>Wed, 02 Jul 2025 23:35:32 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>

<image>
	<url>https://www.tech-freaks.com/wp-content/uploads/2025/07/cropped-tech-freaks-site-icon-512x512-1-32x32.png</url>
	<title>JSP &amp; Servlets &#8211; Tech-Freaks.com</title>
	<link>https://www.tech-freaks.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>RESTful service using Spring MVC and Hibernate</title>
		<link>https://www.tech-freaks.com/java/jsp-servlets/rest-service-spring-hibernate.html</link>
					<comments>https://www.tech-freaks.com/java/jsp-servlets/rest-service-spring-hibernate.html#respond</comments>
		
		<dc:creator><![CDATA[Tech Programmer]]></dc:creator>
		<pubDate>Sat, 11 Jul 2015 16:28:17 +0000</pubDate>
				<category><![CDATA[JSP & Servlets]]></category>
		<guid isPermaLink="false">http://localhost/tfcom_wp/2015/07/11/rest-service-spring-hibernate/</guid>

					<description><![CDATA[Requirement Create a RESTful service using Spring MVC and Hibernate for fetching, adding, updating and deleting product information.  The product [&#8230;]]]></description>
										<content:encoded><![CDATA[		<div class="wpulike wpulike-default " ><div class="wp_ulike_general_class wp_ulike_is_not_liked"><button type="button"
					aria-label="Like Button"
					data-ulike-id="9"
					data-ulike-nonce="6216f36f7c"
					data-ulike-type="post"
					data-ulike-template="wpulike-default"
					data-ulike-display-likers=""
					data-ulike-likers-style="popover"
					class="wp_ulike_btn wp_ulike_put_image wp_post_btn_9"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0"></span>			</div></div>
	<p style="text-align: left;"><strong>Requirement</strong></p>
<p style="text-align: left;">Create a RESTful service using Spring MVC and Hibernate for fetching, adding, updating and deleting product information.  The product information will be persisted in a database table. The service should be available to be consumed by any client like mobile, html, java application etc. using the REST url created.</p>
<p style="text-align: left;"><strong>GitHub Project URL</strong></p>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px;"><strong><span style="font-size: 10pt;"><a style="color: #1b57b1; text-decoration: none; font-weight: normal;" href="https://github.com/tech-freaks/catalog-service" target="_blank" rel="alternate noopener noreferrer">https://github.com/tech-freaks/catalog-service</a></span></strong></p>
<p style="text-align: left;"><strong>Pre-requisites</strong></p>
<ul style="text-align: left;">
<li>MySQL and Tomcat is already installed</li>
<li>Eclipse with JEE support is already installed</li>
<li>Basics about Spring and Hibernate framework</li>
<li>Basics about RESTful service</li>
</ul>
<p><span id="more-9"></span></p>
<p style="text-align: left;"><strong>Analysis and Design</strong></p>
<p style="text-align: left;">We will use a bottom-up approach to design our application. We start from the database layer, then hibernate layer and finally the Spring layer.</p>
<p style="text-align: left;">Database</p>
<p>For implementing this requirement, we create a table PRODUCT. It has basic information about a product like name, description, partnumber, unit price etc. We do not have any more table for fulfilling this requirement. However, if you create a complex application, your product information might be normalized into multiple related tables.</p>
<p style="text-align: left;">Below is the CREATE table statement for creating the PRODUCT table.</p>
<pre class="brush:sql" style="color: #333333; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-align: left; text-indent: 0px; text-transform: none; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px;"> CREATE TABLE IF NOT EXISTS `product` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `partnumber` varchar(50) NOT NULL,
  `description` varchar(1024) NOT NULL,
  `thumbnail_url` varchar(240) DEFAULT NULL,
  `buyable` char(1) NOT NULL DEFAULT 'Y',
  `unitprice` decimal(8,2) NOT NULL,
  PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;</pre>
<p style="text-align: left;">There is two sql script in the github repository root folder create_tables.sql and product_load.sql. As the name suggests, the first sql can be used to create a database and PRODUCT table. The second sql can be run to insert some starter products.</p>
<p style="text-align: left;"><span style="text-decoration: underline;">Hibernate</span></p>
<p style="text-align: left;">Nothing to think about here! We will have a hibernate class Product.java which will be mapped to PRODUCT table. If you would want to reverse engineer the Product.java from the database table, review the steps in the article <a title="Reverse Engineering Hibernate objects using JBoss eclipse plugin" href="jsp-servlets/jboss-reverse-engineer-hibernate.html" target="_blank" rel="alternate noopener noreferrer">Reverse Engineering Hibernate objects using JBoss eclipse plugin</a></p>
<p style="text-align: left;"><span style="text-decoration: underline;">Spring</span></p>
<p style="text-align: left;">We will have a single Controller, which will have different methods for each verb like GET, PUT, POST and DELETE and will act upon Product table data. Following the Spring convention, we will interact with the database using the following layered approach</p>
<p style="text-align: left;">Spring Controller -&gt; Service -&gt; DAO -&gt; Hibernate -&gt; Database</p>
<p style="text-align: left;"><em>Spring Controller:</em><br />
CatalogRestController</p>
<p style="text-align: left;"><em>Service</em>:<br />
ProductService<br />
ProductServiceImpl</p>
<p style="text-align: left;"><em>DAO</em>:<br />
ProductDAO<br />
ProductDAOImpl</p>
<p style="text-align: left;">Furthermore, the Rest controller will have the following methods</p>
<pre class="language-java"><code>@RequestMapping(method = RequestMethod.GET)
public List&lt;Product&gt; getProducts(); - Get all products

@RequestMapping(value = "/{productId}", method = RequestMethod.GET)
public ResponseEntity&lt;?&gt; getProduct(@PathVariable Integer productId) &lt;- Get Products with ProductId

@RequestMapping(method = RequestMethod.POST)
public ResponseEntity&lt;?&gt; add(@RequestBody Product input) &lt;- Insert a product for input received

@RequestMapping(value = "/{productId}", method = RequestMethod.PUT)
public ResponseEntity&lt;?&gt; update(@PathVariable Integer productId,
@RequestBody Product input) &lt;- Update product information for productId

@RequestMapping(value = "/{productId}", method = RequestMethod.DELETE)
public ResponseEntity&lt;?&gt; remove(@PathVariable Integer productId) &lt;- Delete product for the provided productId</code></pre>
<p style="text-align: left;">The above also shows at a high level usage of Spring annotations for specifying different verbs.</p>
<blockquote><p><span style="text-decoration: underline;">Word of caution</span>: This design allows a REST client to insert, delete or update records in database, without any authentication and authorization. For a production application, generally, the only verb which might allow access without authorization is the GET. All the other verbs which modify the database might be authenticated and authorized. Oauth is a commonly used open standard of authorization used to authorize client before they can make changes to the underlying data source.</p></blockquote>
<p style="text-align: left;">We will need to further create XML configuration file for web application, Spring framework and add libraries. We will cover this in environment setup and development sections.</p>
<hr class="system-pagebreak" title="Environment Setup" />
<p style="text-align: left;"><strong>Environment Setup</strong></p>
<ul style="text-align: left;">
<li>Open eclipse and create a &#8220;Dynamic Web Project&#8221; in eclipse with the name &#8220;catalog-service&#8221;.</li>
<li>Click next, then next and finish.</li>
<li>If you are using Maven or Gradle, setup to download libraries for Hibernate 4 or above, Spring 4.1 or above and MySQL drivers. If you are using Spring 4.1, make sure to also include the latest libraries for Jackson FastXML. The conversion of Object to JSON and vice versa is handle by Jackson library and it does not work without the latest libraries.</li>
<li>If you are not using maven or gradle, make sure the following jars are in your WEB-INF/lib folder as provided in the below screenshot</li>
</ul>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px;"><img fetchpriority="high" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/07/dependent_libraries.png" alt="Library Jars" width="404" height="710" /></p>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px;">The source code in the GitHub contains all required libraries.</p>
<p style="text-align: left;"><span style="text-decoration: underline;">Web.xml configuration</span></p>
<p style="text-align: left;">We configure Spring DispatcherServlet, specify the patch to Spring configuration file (if not using default path and file name) and map the request to a URL pattern. For this project, we use *.json mapping. Hence, all the request URL should have .json at the end. Note that, if you perform a partial URL mapping like /product/*, you will have to configuring the ViewResolver, so that it could use the appropriate resolvers for JSON. However, when an extension mapping like .json, no ViewResolver configuration is required.</p>
<pre class="language-markup"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"&gt;
  &lt;display-name&gt;Catalog REST Services&lt;/display-name&gt;
  &lt;welcome-file-list&gt;
    &lt;welcome-file&gt;Login.jsp&lt;/welcome-file&gt;
  &lt;/welcome-file-list&gt;
  &lt;servlet&gt;
    &lt;servlet-name&gt;CatalogServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
    &lt;init-param&gt;
      &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
      &lt;param-value&gt;/WEB-INF/Catalog-Servlet.xml&lt;/param-value&gt;
    &lt;/init-param&gt;
    &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;CatalogServlet&lt;/servlet-name&gt;
    &lt;url-pattern&gt;*.json&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
&lt;/web-app&gt;</code></pre>
<p style="text-align: left;"><span style="text-decoration: underline;">WEB-INF/Catalog-Servlet.xml</span></p>
<p style="text-align: left;">Most of the tags are self-explanatory. Although this is a Spring configuration, it references Hibernate related files and hibernate.cfg.xml. The &#8220;datasource&#8221; needs to be updated with your username, password and dbname. Also, note the configuration for transactionManager. Once this is configured, Spring handles the hibernate transactions and you do not have to manually manage the transaction in your code. Just mark the service method with @Transactional annotation.</p>
<p style="text-align: left;">The ProductDao and ProductService is also declared. We have marked them as @Autowired and hence we do not have to pass the reference for productDao into productService in the XML.</p>
<pre class="language-markup"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd"&gt;

	&lt;mvc:annotation-driven /&gt;
&lt;!-- Configure JDBC Connection - @TODO update url, username and password per your database configuration --&gt;
      &lt;bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
            &lt;property name="driverClassName" value="com.mysql.jdbc.Driver" /&gt;
            &lt;property name="url" value="jdbc:mysql://localhost:3306/tfcom_articles" /&gt;
            &lt;property name="username" value="admin" /&gt;
            &lt;property name="password" value="admin*" /&gt;
      &lt;/bean&gt;
      
    &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt;
    
     &lt;bean id="transactionManager"
            class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt;
        &lt;property name="sessionFactory" ref="sessionFactory"/&gt;
    &lt;/bean&gt;
    
      
    &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt;
    &lt;property name="dataSource"&gt;
                  &lt;ref bean="dataSource" /&gt;
            &lt;/property&gt;
    &lt;property name="configLocation" value="classpath:hibernate.cfg.xml" /&gt;
	&lt;/bean&gt;
	
	&lt;context:component-scan base-package="com.tech_freaks.catalog"/&gt;
	
	&lt;bean id="productDao"
   	class="com.tech_freaks.catalog.dao.ProductDAOImpl"/&gt;
   	
   	&lt;bean id="productService"
   	class="com.tech_freaks.catalog.service.ProductServiceImpl"/&gt;
&lt;/beans&gt;</code></pre>
<pre class="brush:xml" style="color: #333333; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-align: left; text-indent: 0px; text-transform: none; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px;"></pre>
<p style="text-align: left;"><span style="text-decoration: underline;">src/hibernate.cfg.xml</span></p>
<p style="text-align: left;">We have used the XML configuration for hibernate and not annotations. This mainly declares the Product hibernate class and its mapping file Product.hbm.xml.</p>
<p style="text-align: left;">The commented fields in this file will need to be un-commented, if you are reverse engineering the hibernate object as explained in the article <a title="Reverse Engineering Hibernate objects using JBoss eclipse plugin" href="jsp-servlets/jboss-reverse-engineer-hibernate.html" target="_blank" rel="alternate noopener noreferrer">Reverse Engineering Hibernate objects using JBoss eclipse plugin</a></p>
<hr class="system-pagebreak" title="Development" />
<p style="text-align: left;"><strong>Development</strong></p>
<p style="text-align: left;"><span style="text-decoration: underline;">Hibernate Object</span><br />
Product.java &#8211; We reverse engineer this class from the database. It is the model for the application, which is mapped to the database table. It is self-explanatory.</p>
<p style="text-align: left;"><span style="text-decoration: underline;">DAO layer</span></p>
<p style="text-align: left;"><em>AbstractDAO&lt;T&gt;</em> &#8211; This is a generic class which contains common calls to hibernate API. All DAO can extend this class to reuse these pre-implemented class. Note, how the sessionFactory is injected by Spring framework into the DAO layer using @Autowired annotation. The sessionFactory is declared in the Catalog-Servlet.xml file which we defined earlier.</p>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px;">The JavaDoc comments on each of the method, explain the use of the function.</p>
<pre class="language-java"><code>package com.tech_freaks.catalog.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Generic Base class which encapsulates hibernate specific calls which will be available from the 
 * extending DAO which is mapped to the database table.
 * @author Tech Freaks
 *
 * @param &lt;T&gt; - The Hibernate object which it works on
 */
public class AbstractDAO &lt;T&gt; {
	
	@Autowired
    private SessionFactory sessionFactory;
 
	/**
	 * Gets a current session from the hibernate factory
	 * @return
	 */
    protected Session getSession(){
        return sessionFactory.getCurrentSession();
    }
    
    /**
     * Generic method for finding by primary key. 
     * @param id  - Primary key value in integer
     * @param myClass - Type of Class which will be loaded
     * @return T representing instance of the loaded hibernate class instance
     */
    public &lt;T&gt;  T findById(Integer id, Class myClass) {
    	return (T) getSession().load(myClass, id);
    }
 
    /**
     * Inserts record into database
     * @param t - Instance of the Hibernate object which needs to be persisted in the db
     * @return - Key value of the newly inserted record
     */
    public Integer persist(T t) {
       return (Integer) getSession().save(t);
    }
    
    /**
     * Updates the database for provided generic type
     * @param t Generic type for the hibernate object
     */
    public void update(T t) {
    	getSession().update(t);
    	getSession().flush();
    }
     
    /**
     * Deletes the entity from the database for the provided generic type
     * @param t  Generic type for the hibernate object
     */
    public void delete(T t) {
        getSession().delete(t);
        getSession().flush();
    }
}</code></pre>
<p style="text-align: left;"><em>ProductDAOImpl &amp; ProductDAO</em><br />
This is the actual DAO interface and its implementation. It extends the AbstractDAO&lt;Product&gt; and utilizes the methods defined there.</p>
<pre class="language-java"><code>package com.tech_freaks.catalog.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.tech_freaks.catalog.model.Product;

public class ProductDAOImpl extends AbstractDAO&lt;Product&gt; implements ProductDAO {
	
	
	/**
	 * Fetches all the product from the PRODUCT table
	 */
	@Override
	public List&lt;Product&gt; getAllProducts() {
		Session session = getSession();
        List&lt;Product&gt; productList = session.createQuery("from Product").list();
        return productList;
	}
	
	/**
	 * Fetches product based on the primary key productId
	 */
	@Override
	public Product findById(Integer id) {
		return (Product) getSession().get(Product.class, id);
	}
	
	/**
	 * Inserts a new record in the product table.
	 */
	@Override
	public Integer insert(Product product) {
		return persist(product);
	}
	
	/**
	 * Loads the product using the primary key and then removes it from the database.
	 */
	@Override
	public boolean remove(Integer id)  {
		boolean deleted = false;
		Product delProduct = findById(id);
		if(delProduct!=null) {
			delete(delProduct);
			deleted = true;
		} 
		return deleted;
	}
}</code></pre>
<p style="text-align: left;"><em>ProductServiceImpl &amp; ProductService</em></p>
<p style="text-align: left;">The is the Service layer interface and its implementation for the Product manipulation. It internally calls the DAO layer. The Service layer is called from the Controller class. The methods are self-explanatory.</p>
<p style="text-align: left;">The below excerpt from ProductServiceImpl shows @Autowiring annotation on productDAO, which is injected in by the Spring framework. Also, each method is marked with annotation @Transactional. This is the reason, you do not see any code related to transaction management in the DAO layer. Spring manages the transaction code for you.</p>
<pre class="language-java"><code>...
@Autowired
	private ProductDAO productDAO;
	
	@Override
	@Transactional
	public List&lt;Product&gt; listProducts() {
		
		return productDAO.getAllProducts();
	}
...</code></pre>
<p style="text-align: left;"><em>CatalogRestController </em>is the entry point into the code for all REST service verbs. The @RestController annotation eliminates the need to mark each method with @ResponseBody when it returns an Object or a Collection of objects. Now even without @ResponseBody, when an object or collection of object is returned, it is automatically converted into JSON. The class is also marked with @RequestMapping(&#8220;/products&#8221;). This means the REST URL for every verb call will have &#8216;/products&#8217; in it, after the application context name. Now, each method is marked with @RequestMethod. We follow the REST specification by mapping GET to retrieve data, POST for insert data, PUT for update data and DELETE for deleting data.</p>
<p style="text-align: left;">If we look at the method &#8220;add&#8221;, there are certain points worth noticing.</p>
<p style="text-align: left;">First, after every REST call, we return a HttpStatusCode. If the insert is successful, we return CREATED status or 201. If it fails, because the Product object was not populated, it means, the JSON was not well formed. In this case, we return BAD_REQUEST or 400. This helps the client to read the HttpHeader in the response and take appropriate action.</p>
<p style="text-align: left;">Second, after insert, the method create a REST URL to fetching the newly inserted record. This is set in the Location HttpHeader.</p>
<p style="text-align: left;">The private method isValid() is called internally to perform some basic validation before the service layer is invoked.</p>
<p style="text-align: left;">Similarly, all the other method are developed. The complete CatalogRestController code is below.</p>
<pre class="language-java"><code>package com.tech_freaks.catalog.controller;

import java.net.URI;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import com.tech_freaks.catalog.model.Product;
import com.tech_freaks.catalog.service.ProductService;

@RestController
@RequestMapping("/products")
/**
 * Entry point for REST service calls. Different method for handling insert, update, delete and get
 */
public class CatalogRestController {

	protected final Log logger = LogFactory.getLog(getClass());

	@Autowired
	private ProductService productService;

	@RequestMapping(method = RequestMethod.GET)
	public List&lt;Product&gt; getProducts() {
		return productService.listProducts();

	}

	@RequestMapping(value = "/{productId}", method = RequestMethod.DELETE)
	public ResponseEntity&lt;?&gt; remove(@PathVariable Integer productId) {
		boolean deleted = false;
		ResponseEntity&lt;?&gt; response = null;
		try {
			deleted = productService.removeProduct(productId);
		} catch (Exception e) {
			logger.error("Error deleting product from database: "
					+ e.getMessage());
		}
		if (deleted)
			response = new ResponseEntity&lt;&gt;(HttpStatus.OK);
		else
			response = new ResponseEntity&lt;&gt;(HttpStatus.NO_CONTENT);
		return response;
	}

	@RequestMapping(value = "/{productId}", method = RequestMethod.GET)
	public ResponseEntity&lt;?&gt; getProduct(@PathVariable Integer productId) {
		ResponseEntity&lt;Product&gt; response = null;
		Product product = productService.getProduct(productId);
		if (product != null) {
			response = new ResponseEntity&lt;&gt;(product, HttpStatus.OK);
		} else {
			response = new ResponseEntity&lt;&gt;(HttpStatus.NO_CONTENT);
		}
		return response;
	}

	@RequestMapping(value = "/{productId}", method = RequestMethod.PUT)
	public ResponseEntity&lt;?&gt; update(@PathVariable Integer productId,
			@RequestBody Product input) {
		ResponseEntity&lt;?&gt; response = new ResponseEntity&lt;&gt;(HttpStatus.OK);
		logger.info("Product Id to be updated is " + productId);
		logger.info("New Product Name will be " + input.getName());
		try {
			if (productId &gt; 0 &amp;&amp; isValid(input)) {
				input.setProductId(productId);
				productService.updateProduct(input);
				response = new ResponseEntity&lt;&gt;(HttpStatus.OK);
				
			} else {
				response = new ResponseEntity&lt;&gt;(HttpStatus.BAD_REQUEST);
			}
		} catch (HibernateException he) {
			logger.error("Unable to update product in database: "+ he.getMessage());
			response = new ResponseEntity&lt;&gt;(HttpStatus.NO_CONTENT);
		} catch (Exception e) {
			logger.error("Unable to update product in database: "+ e.getMessage());
			response = new ResponseEntity&lt;&gt;(HttpStatus.BAD_REQUEST);
		}
		return response;
	}

	@RequestMapping(method = RequestMethod.POST)
	public ResponseEntity&lt;?&gt; add(@RequestBody Product input) {
		HttpHeaders httpHeaders = new HttpHeaders();
		ResponseEntity&lt;?&gt; response = null;
		if (isValid(input)) {
			logger.info("Product description is " + input.getDescription());
			try {
				Integer productId = productService.createProduct(input);
				URI location = ServletUriComponentsBuilder
						.fromCurrentServletMapping()
						.path("/products/{productId}.json").build()
						.expand(productId).toUri();
				logger.info("Location uri is " + location.toString());
				httpHeaders.setLocation(location);
				response = new ResponseEntity&lt;&gt;(null, httpHeaders,
						HttpStatus.CREATED);
			} catch (Exception e) {
				logger.error("Unable to insert new product in database: "
						+ e.getMessage());

				response = new ResponseEntity&lt;&gt;(null, httpHeaders,
						HttpStatus.UNPROCESSABLE_ENTITY);
			}
		} else {
			response = new ResponseEntity&lt;&gt;(null, httpHeaders,
					HttpStatus.BAD_REQUEST);
		}
		return response;
	}

	/*
	 * Internally used to validate the fields to make sure, all required fields
	 * are present before calling the service layer for insert
	 */
	private boolean isValid(Product product) {
		boolean valid = false;
		if (product != null) {
			if (!StringUtils.isEmpty(product.getName())
					&amp;&amp; !StringUtils.isEmpty(product.getDescription())
					&amp;&amp; !StringUtils.isEmpty(product.getPartnumber())
					&amp;&amp; !StringUtils.isEmpty(product.getName()))
				valid = true;
		}
		return valid;
	}
}</code></pre>
<p style="text-align: left;">At this point, you can download the complete project from GitHub at <a href="https://github.com/tech-freaks/catalog-service" target="_blank" rel="alternate noopener noreferrer">https://github.com/tech-freaks/catalog-service</a></p>
<hr class="system-pagebreak" title="Unit Testing" />
<p style="text-align: left;"><strong>Unit Testing</strong></p>
<p style="text-align: left;">The first part of the unit test, is to figure out the REST URL to invoke. We can figure this out, if we look at the CatalogRestController and web.xml. Remember, web.xml maps *.json to the controller. Hence, for all verbs our URL will end with .json.</p>
<p style="text-align: left;">We used the following information:</p>
<p style="text-align: left;">Tomcat host: http://localhost:8080<br />
Application Context: /catalog-service<br />
CatalogRestController mapping: /products</p>
<p style="text-align: left;">Now, the method getProducts() do not have any value mapping. But, it needs to be a GET call. Hence, for accessing this method, you will use the URL http://localhost:8080/catalog-service/products.json and it needs to be a GET call. You can therefore, just paste the URL in a browser and it will show the JSON with all products.</p>
<p style="text-align: left;">Similarly, if you look at getProduct(), the request mapping has /{productId}. This is equivalent to the primary key, product_id value in the database. Hence, the URL will be http://localhost:8080/catalog-service/products/1.json , where product_id=1. This will be again a GET verb again, as we are fetching information.</p>
<p style="text-align: left;">Now, similarly, we can figure out the remaining URL for calling remove(), update() and add(). The below table provide the remaining URL and verbs.</p>
<table style="margin-left: 0px; margin-right: auto;">
<tbody>
<tr>
<td width="120">Method</td>
<td width="540">URL</td>
<td width="120">Verb</td>
</tr>
<tr>
<td width="120">remove()</td>
<td width="540">http://localhost:8080/catalog-service/products/{productId}.json</td>
<td width="120">DELETE</td>
</tr>
<tr>
<td width="120">update()</td>
<td width="540">http://localhost:8080/catalog-service/products/{productId}.json</td>
<td width="120">PUT</td>
</tr>
<tr>
<td width="120">add()</td>
<td width="540">http://localhost:8080/catalog-service/products.json</td>
<td width="120">POST</td>
</tr>
</tbody>
</table>
<p style="text-align: left;">Where {productId} will be replaced by product_id value in the database.</p>
<p style="text-align: left;">Now, there will be two question:<br />
1. How to invoke DELETE, PUT and POST verb? When we paste the URL in the browser, they all are by default GET requests.<br />
2. How to pass the product information for add() and update()?</p>
<p style="text-align: left;">For # 1, we can download a browser plugin called as Poster (Just search Poster plugin), which is available for Chrome and Firefox. The below screenshot shows, Poster in action for Firefox.</p>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px;"><img decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/07/poster_request_response.png" alt="Poster plugin for Firefox in Action" width="870" height="867" /></p>
<p style="text-align: left;">For # 2, we need to send an input json containing the product information to be insert or updated in the product table. The POST performs and insert, while PUT updates. The json format is exactly as the response received from http://localhost:8080/catalog-service/products/{productId}.json GET verb. However, we have provided an input file by the name POST_PUT_Input.json, which is in the root folder of the project.</p>
<p style="text-align: left;">In Poster plugin, you need to make sure, that to add a Header by the name &#8220;Content-Type&#8221; with value &#8220;application/json&#8221;.</p>
<p style="text-align: left;">For integration testing, we generally run the client code like the mobile application in same network and point to the URLs provided above. However, integration testing is beyond the scope of this article.</p>
<p style="text-align: left;">This completes the workshop for creating a simple product REST service using Spring MVC 4.</p>
<p style="text-align: left;">Happy RESTing!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.tech-freaks.com/java/jsp-servlets/rest-service-spring-hibernate.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Quick Tomcat and Eclipse Integration  Deploying Web apps to Tomcat from within Eclipse</title>
		<link>https://www.tech-freaks.com/java/jsp-servlets/quick-eclipse-tomcat-integration.html</link>
					<comments>https://www.tech-freaks.com/java/jsp-servlets/quick-eclipse-tomcat-integration.html#respond</comments>
		
		<dc:creator><![CDATA[Tech Programmer]]></dc:creator>
		<pubDate>Fri, 26 Jun 2015 19:31:31 +0000</pubDate>
				<category><![CDATA[JSP & Servlets]]></category>
		<guid isPermaLink="false">http://localhost/tfcom_wp/2015/06/26/quick-eclipse-tomcat-integration/</guid>

					<description><![CDATA[Overview When you are working on a web application development using Tomcat server and Eclipse IDE, it could be painful [&#8230;]]]></description>
										<content:encoded><![CDATA[		<div class="wpulike wpulike-default " ><div class="wp_ulike_general_class wp_ulike_is_not_liked"><button type="button"
					aria-label="Like Button"
					data-ulike-id="15"
					data-ulike-nonce="9c55c9b757"
					data-ulike-type="post"
					data-ulike-template="wpulike-default"
					data-ulike-display-likers=""
					data-ulike-likers-style="popover"
					class="wp_ulike_btn wp_ulike_put_image wp_post_btn_15"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0"></span>			</div></div>
	<p style="text-align: left;"><strong><span style="font-size: 12pt;">Overview</span></strong></p>
<p style="text-align: left;">When you are working on a web application development using Tomcat server and Eclipse IDE, it could be painful and inefficient to create a WAR file and deploy to Tomcat after every code change. There are multiple ways to make the development process efficient.</p>
<ol style="text-align: left;">
<li>Create Tomcat Server within Eclipse</li>
<li>Create Ant or other build script to deploy to Tomcat webapps folder</li>
<li>Setup your Eclipse project to be within Tomcat/webapps folder</li>
</ol>
<p style="text-align: left;">The simplest and most convenient is the creating a Tomcat Server within Eclipse. This article walks through the steps to configure Tomcat to run from within Eclipse.</p>
<p style="text-align: left;">This article uses Eclipse Kepler and Tomcat 8, but the process should be similar with other versions too.</p>
<p style="text-align: left;">The article does not walk through JDK, Tomcat and Eclipse installation.</p>
<p style="text-align: left;"><strong><span style="font-size: 12pt;">Steps</span></strong></p>
<ol style="text-align: left;">
<li>Download and install Java JDK 7 or later from Oracle website: <a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html" target="_blank" rel="author noopener noreferrer">http://www.oracle.com/technetwork/java/javase/downloads/index.html</a></li>
<li>Download and install Tomcat 8 from Apache website: <a href="https://tomcat.apache.org/download-80.cgi" target="_blank" rel="alternate noopener noreferrer">https://tomcat.apache.org/download-80.cgi</a></li>
</ol>
<ol style="list-style-type: lower-alpha; text-align: left;" start="4">
<li>Download Eclipse for JEE developer from Eclipse website: <a href="http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/keplersr1" target="_blank" rel="alternate noopener noreferrer">http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/keplersr1</a></li>
<li>Follow the URL <a href="https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler" target="_blank" rel="alternate noopener noreferrer">https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler</a> if you installed JDK 8 and want Eclipse to support JDK 8</li>
<li><strong>Creating Tomcat 8 server in Eclipse</strong></li>
</ol>
<p style="text-align: left;">a. Open Java EE perspective and access the Server tab below. You should see as the below screenshot</p>
<p style="text-align: left;"><img decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/no_server_defined.png" alt="No Server Defined" width="1519" height="817" /></p>
<p style="text-align: left;">b. Click the link to create new Server as highlighted in screen above.</p>
<p style="text-align: left;">c. In the window that opens, click Apache and check for Tomcat 8. If you do not see, Tomcat 8 option perform the steps d to e.</p>
<p style="text-align: left;">d. Go to Help -&gt; Install New Software..</p>
<p style="text-align: left;">e. In the window that opens, enter the URL as &#8211; http://download.eclipse.org/webtools/repository/luna</p>
<p style="text-align: left;"> &gt;&gt; Under the Web Tools Platform (WTP) 3.6.0, select options &#8220;JST Server Adapters&#8221; and &#8220;JST Server Adapters Extensions&#8221;. Click Next and then Accept the license agreement and finish installation.</p>
<p style="text-align: left;"> &gt;&gt; Eclipse will prompt to restart and after restarting, you should be able to Tomcat 8 option</p>
<p style="text-align: left;"> <img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/define_new_server.png" alt="Define a new server" width="932" height="851" /></p>
<p style="text-align: left;">f. Now select Tomcat 8 and click next</p>
<p style="text-align: left;">g. In the next screen, select the location of Tomcat Installation and also JDK, as shown below</p>
<p style="text-align: left;"><img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/specify_tc_install_directory.png" alt="Tomcat and JDK installation path" width="932" height="851" /></p>
<p style="text-align: left;">h. Click next and you should see the option to add your web application. Add a test application, if you have one and click finish.</p>
<p style="text-align: left;">i. You should see the new Tomcat 8 server and displayed in the Server window as shown below</p>
<p style="text-align: left;"><img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/new_tomcat8_server.png" alt="New Tomcat 8 Server" width="1519" height="817" /></p>
<p style="text-align: left;">j. Double click the new Server definition and in the file which opens in Eclipse make the settings as highlighted in the below screen. The selected option uses the Tomcat installation path to work with, instead of create a separate set of files in the user folder. If you do not want Eclipse to work on the installation folder of Tomcat, you might want to select the first option &#8216;Use Workspace Metadata&#8217;.</p>
<p style="text-align: left;"><img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/server_config_update.png" alt="Tomcat Server Configuration" width="1519" height="817" /></p>
<p style="text-align: left;">k. Next right click and Server and click Start. This should start your Tomcat server without any errors, in the Console.</p>
<p style="text-align: left;">l. Verify the Tomcat server by access the URL http://localhost:8080 and you should be able to see Tomcat screen.</p>
<p style="text-align: left;">This concludes the walk-through of configuring Tomcat to be access from within Eclipse IDE. Enjoy developing, deploying and testing on your development environment completely from within Eclipse !</p>
<blockquote>
<p style="text-align: left;">If you notice error while starting Tomcat which says &#8220;Access Denied&#8221;, it means that Eclipse is not having permission to access file in the Tomcat installation folder. You can resolve this by giving required permission to the Tomcat installation folder or by running your Eclipse as Administrator. You can also use the option &#8216;Use Workspace Metadata&#8217;, in step j, if you are unable to resolve the access issue.</p>
</blockquote>
]]></content:encoded>
					
					<wfw:commentRss>https://www.tech-freaks.com/java/jsp-servlets/quick-eclipse-tomcat-integration.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Reverse Engineering Hibernate objects using JBoss eclipse plugin</title>
		<link>https://www.tech-freaks.com/java/jsp-servlets/reverse-engineer-hibernate-objects.html</link>
					<comments>https://www.tech-freaks.com/java/jsp-servlets/reverse-engineer-hibernate-objects.html#respond</comments>
		
		<dc:creator><![CDATA[Tech Programmer]]></dc:creator>
		<pubDate>Wed, 24 Jun 2015 09:09:35 +0000</pubDate>
				<category><![CDATA[JSP & Servlets]]></category>
		<guid isPermaLink="false">http://localhost/tfcom_wp/2015/06/24/reverse-engineer-hibernate-objects/</guid>

					<description><![CDATA[Writing hibernate class and xmls can be a pain, especially, if you have tons of tables in your database. One [&#8230;]]]></description>
										<content:encoded><![CDATA[		<div class="wpulike wpulike-default " ><div class="wp_ulike_general_class wp_ulike_is_not_liked"><button type="button"
					aria-label="Like Button"
					data-ulike-id="29"
					data-ulike-nonce="dddf313405"
					data-ulike-type="post"
					data-ulike-template="wpulike-default"
					data-ulike-display-likers=""
					data-ulike-likers-style="popover"
					class="wp_ulike_btn wp_ulike_put_image wp_post_btn_29"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0"></span>			</div></div>
	<p style="text-align: left;">Writing hibernate class and xmls can be a pain, especially, if you have tons of tables in your database. One way to alleviate the pain is to use a reverse engineering tool, which would generate the xml and java files for hibernate by connecting to database. This article walks through the steps from installing the JBoss Tools Eclipse plugin to generate hibernate java and xml files.</p>
<p><strong><span style="font-size: 12pt;">Pre-requisites </span></strong></p>
<ul>
<li style="text-align: left;">MySQL and Eclipse are installed</li>
<li style="text-align: left;">MySQL has a database with at least one table</li>
<li style="text-align: left;">You have some basic knowledge about hibernate or any other ORM tool</li>
</ul>
<p style="text-align: left;"><strong><span style="font-size: 12pt;">Steps</span></strong></p>
<p style="text-align: left;"><span style="text-decoration: underline;">Installing JBoss Eclipse Tools from marketplace</span></p>
<p>Open Eclipse and follow the menu, Help -&gt; Eclipse Marketplace..</p>
<p style="text-align: left;">Search for &#8216;JBoss&#8217; or &#8216;Hibernate&#8217; and click install on the Jboss Tools</p>
<p><img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/eclipse_marketplace_jboss.png" alt="Eclipse Market Place" width="700" height="921" /></p>
<p>Un-select all options except &#8220;Hibernate Tools&#8221; as shown in the below screenshot</p>
<p><img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/jboss_hibernate_tools.png" alt="JBoss tools install for Eclipse" width="700" height="921" /></p>
<p>Click &#8220;Confirm&#8221; and then &#8220;Finish&#8221;. Accept the license agreement.</p>
<p>Eclipse will prompt to restart</p>
<p style="text-align: left;"><span style="text-decoration: underline;">Creating the hibernate configuration (hibernate.cfg.xml)</span></p>
<p>Once Eclipse has restarted, Open hibernate perspective. Windows -&gt; Open Perspective -&gt; Others</p>
<p><img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/open_hibernate_perspective.png" alt="Open Hibernate Perspective" width="371" height="474" /></p>
<p>The perspective will be empty. Click on the &#8220;Add Configuration&#8221; to start the configuration process, as shown below</p>
<p><img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/hibernate_configurations.png" alt="Hibernate Configurations" width="1519" height="817" /></p>
<p>A window &#8220;Edit Configuration&#8221; will show up, as per the below screen shot. Select the Project by clicking Browse.</p>
<p style="text-align: left;"><img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/hibernate_edit_config.png" alt="Hibernate Edit Configuration" width="700" height="702" /></p>
<p>Next, click &#8220;Setup&#8221; from Configuration File section. This will open another windows as shown below.</p>
<p style="text-align: left;"><img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/create_cfg_xml.png" alt="Create hibernate.cfg.xml" width="868" height="779" /></p>
<p style="text-align: left;">Using this, we will be creating the hibernate.cfg.xml which has the information like the database dialect, database URL, drivers, database type, db user id and db password. Once you click &#8220;Finish&#8221;, this will generate the hibernate.cfg.xml. Then click the &#8220;OK&#8221; in the &#8220;Edit Configuration&#8221; window should be open.</p>
<p style="text-align: left;"><img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/rebuild_config.png" alt="Rebuild Hibernate Config" width="1519" height="855" /></p>
<p>Next, go to the Hibernate Configuration in the Hibernate perspective. Right click the new configuration which you added now and click &#8220;Rebuild Configuration&#8221;. You should now check the section under &#8220;Database&#8221; in the hibernate configuration.  You should see the tables from your database. If the tables are not showing and it shows an error, you should not proceed further and resolve this issue first. Below are some possible reasons for the error</p>
<ul>
<li style="text-align: left;">Database drivers are not in classpath:  <span style="text-decoration: underline;">Resolution</span>: Put the driver jar file in the WEB-INF/lib folder to resolve this.</li>
<li style="text-align: left;">Database service is not started: <span style="text-decoration: underline;">Resolution</span>: Start your database and try connecting again.<br />
One or more information entered in the hibernate.cfg.xml is incorrect. Verify all the information entered in the hibernate.cfg.xml, anything which is incorrect.</li>
<li style="text-align: left;">If you resolved the issue as explained above, you might want to &#8220;Rebuild Configuration&#8221; after resolving the issue.Once you can see the Database tables, you can proceed to the reverse engineering steps provided below.
<p><span style="text-decoration: underline;">Create a new Hibernate Reverse Engineering file</span></p>
<p>From the Hibernate Perspective click &#8220;File&#8221; -&gt; &#8220;New&#8221; -&gt; &#8220;Hibernate Reverse Engineering File (reveng.xml)&#8221;</li>
</ul>
<p style="text-align: left;"><img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/reveng_xml_step1.png" alt="Create the reverse engineering file" width="700" height="671" /><br />
In the Wizard that opens, select the project and click &#8220;Next&#8221;</p>
<p style="text-align: left;"><img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/reveng_xml_step2.png" alt="Reverse Engineering Step 2" width="700" height="671" /></p>
<p>Select the &#8220;Console Configuration&#8221; from the drop down in the next step and click the &#8220;Refresh&#8221; button. The Database Schema section will show your database and tables. Select all the tables and click include. Click the &#8220;Finish&#8221; button to generate hibernate.reveng.xml file.</p>
<blockquote><p>If you are unable to generate the hibernate objects, check that you have included all individual tables instead of the whole database and re-generate the reveng.xml</p></blockquote>
<p style="text-align: left;">Once you have the reverse engineering file generated, you need to do Run -&gt; Hibernate Code Generation -&gt; Hibernate Code Generation Configurationâ‚¬¦</p>
<p><img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/hibernate_code_generation_config.png" alt="Hibernate Code Generation Configuration" width="1519" height="855" /></p>
<p>In the window that opens, create a new configuration and enter details as per the below screenshot and click &#8220;Run&#8221;.</p>
<p style="text-align: left;"><img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/hibernate_code_generation_config_main.png" alt="Hibernate code generation main tab" width="906" height="702" /></p>
<p style="text-align: left;"><img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/hibernate_code_generation_config_exporters.png" alt="Hibernate code generation exporters" width="906" height="702" /></p>
<p>Go back to Java EE perspective and you will see the hibernate xmls and java files generated in the package specified in the Main tab of the configuration before clicking Run.</p>
<p>You might want to modify some of the content in the xml or java files generated as per your needs. However, remember that, if you have to regenerated the hibernate objects, your manual changes might get lost.</p>
<p style="text-align: left;"><img loading="lazy" decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2015/06/add_mapping_cfg.png" alt="Add Mapping to hibernate.cfg.xml" width="1519" height="817" /><br />
One last step you would need to perform, is to add the mapping of the bean in the hibernate.cfg.xml. Below shows a screenshot of adding one mapping.</p>
<p style="text-align: left;">That completes the steps to reverse engineer hibernate objects using JBoss Tools in Eclipse.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.tech-freaks.com/java/jsp-servlets/reverse-engineer-hibernate-objects.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Simple Login Application using Struts 2</title>
		<link>https://www.tech-freaks.com/java/jsp-servlets/struts2-login-application.html</link>
					<comments>https://www.tech-freaks.com/java/jsp-servlets/struts2-login-application.html#respond</comments>
		
		<dc:creator><![CDATA[Tech Programmer]]></dc:creator>
		<pubDate>Thu, 28 May 2015 22:10:38 +0000</pubDate>
				<category><![CDATA[JSP & Servlets]]></category>
		<guid isPermaLink="false">http://localhost/tfcom_wp/2015/05/28/struts2-login-application/</guid>

					<description><![CDATA[Requirement Create a Login page to enter user name and password On submit, validate the user name / password against [&#8230;]]]></description>
										<content:encoded><![CDATA[		<div class="wpulike wpulike-default " ><div class="wp_ulike_general_class wp_ulike_is_not_liked"><button type="button"
					aria-label="Like Button"
					data-ulike-id="30"
					data-ulike-nonce="8d266fd85a"
					data-ulike-type="post"
					data-ulike-template="wpulike-default"
					data-ulike-display-likers=""
					data-ulike-likers-style="popover"
					class="wp_ulike_btn wp_ulike_put_image wp_post_btn_30"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0"></span>			</div></div>
	<p><strong>Requirement</strong></p>
<ul style="text-align: left;">
<li>Create a Login page to enter user name and password</li>
<li>On submit, validate the user name / password against MySQL database</li>
<li>If the authentication is successful, forward to home page showing welcome message along with the user name</li>
<li>If the authentication fails, return back to the login page with appropriate error message</li>
<li>If there is exception / errors during authentication process return back to login page with appropriate error message.</li>
</ul>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px;"><span style="font-size: 12pt;"><strong>Pre-requisites</strong></span></p>
<ul style="text-align: left;">
<li>MySQL and Tomcat is already installed</li>
<li>MySQL is setup with database and tables for use. Refer<span class="Apple-converted-space"> </span><a style="color: #1b57b1; text-decoration: none; font-weight: normal;" href="jsp-servlets/simple-login-application.html" target="_blank" rel="alternate noopener noreferrer">Simple Login Application</a> for details</li>
<li>You have basic knowledge of Java and J2EE web applications</li>
<li>Basic idea about Struts 1 or 2 or at least about MVC design</li>
</ul>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px;"><span style="font-size: 12pt;"><strong>Concepts Covered</strong></span></p>
<ul style="text-align: left;">
<li>IDE set up for Struts 2</li>
<li>Struts2 key components</li>
<li>Difference between struts 1 and struts 2 highlighted</li>
</ul>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-align: left;"><span style="font-size: 12pt;"><strong>Environment Setup</strong></span></p>
<ul style="text-align: left;">
<li>Download Eclipse for Java EE which is all ready to go with JEE features and install it. Download from <a href="https://eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/lunar" rel="alternate noopener" target="_blank">Eclipse for JEE Download</a></li>
<li>Create a &#8220;Dynamic Web Project&#8221; in eclipse with the name Struts2LoginApp.<br />
Click next, then next and finish.</li>
<li>Download latest Struts2 binaries from <a title="Struts 2 Binaries Download" href="https://struts.apache.org/download.cgi" target="_blank" rel="alternate noopener noreferrer">Struts 2 Binaries Download</a>. At the time of writing this article, struts 2.3.24 was used.</li>
<li>Unzip the binaries and copy the following JAR files to the lib directory(&lt;workspace&gt;\Struts2LoginApp\WebContent\WEB-INF\lib) of the newly created project:</li>
</ul>
<p style="padding-left: 30px; text-align: left;">commons-fileupload-1.3.1.jar<br />
commons-io-2.2.jar<br />
commons-lang3-3.2.jar<br />
commons-logging-1.1.3.jar<br />
commons-logging-api-1.1.jar<br />
freemarker-2.3.22.jar<br />
javassist-3.11.0.GA.jar<br />
ognl-3.0.6.jar<br />
struts2-core-2.3.24.jar<br />
xwork-core-2.3.24.jar</p>
<p style="padding-left: 30px; text-align: left;">Since we make connections to MySQL using JDBC, we would also need to put the JAR for the MySQL JDBC driver (mysql-connector-java-5.1.20-bin.jar). You can download the latest version of the jar from<span class="Apple-converted-space"> </span><a style="color: #1b57b1; text-decoration: none; font-weight: normal;" title="MySQL JDBC Driver Download" href="http://dev.mysql.com/downloads/connector/j/" target="_blank" rel="alternate noopener noreferrer">MySQL JDBC Driver Download</a>.</p>
<p style="padding-left: 30px; text-align: left;"><strong>web.xml configuration:</strong><br />
A blank web.xml might have been added to your project under WEB-INF folder. This file is the JSP deployment descriptor. We need to configure the struts 2 controller, which is a servlet filter by the name FilterDispatcher. If you are familiar with Struts1, you will recollect that in the web.xml, we used to make an entry for the ActionServlet which was the controller in struts1.</p>
<pre class="language-markup"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0"&gt;
   
   &lt;display-name&gt;Struts 2 Login App&lt;/display-name&gt;
   &lt;welcome-file-list&gt;
      &lt;welcome-file&gt;Login.jsp&lt;/welcome-file&gt;
   &lt;/welcome-file-list&gt;
   &lt;filter&gt;
      &lt;filter-name&gt;struts2&lt;/filter-name&gt;
      &lt;filter-class&gt;
         org.apache.struts2.dispatcher.FilterDispatcher
      &lt;/filter-class&gt;
   &lt;/filter&gt;

   &lt;filter-mapping&gt;
      &lt;filter-name&gt;struts2&lt;/filter-name&gt;
      &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
   &lt;/filter-mapping&gt;
&lt;/web-app&gt;</code></pre>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-align: left;"><span style="font-size: 12pt;"><strong>Analysis and Design</strong></span></p>
<p style="text-align: left;">If you do not have the database table created or do not have any user in that table, please refer the analysis and design from the article <a href="jsp-servlets/simple-login-application.html" target="_blank" rel="alternate noopener noreferrer">Simple Login Application</a> for details.</p>
<p style="text-align: left;">Taking inspiration from the previous article, we will create similar components for our simple login app using struts 2.</p>
<p style="text-align: left;">So, below are the identified components:</p>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-align: left;"><span style="font-size: 10pt;">Login.jsp</span><br />
<span style="font-size: 10pt;">Home.jsp</span><br />
<span style="font-size: 10pt;">LogonAction.java</span></p>
<p style="padding-left: 30px; text-align: left;">Let us look at each identified component and its role in our application:</p>
<ul style="text-align: left;">
<li>Login.jsp -&gt; It would present the login screen to enter user id and password. It also displays any validation errors and login failure message.</li>
<li>Home.jsp -&gt; Simple JSP which displays a welcome message after successful login</li>
<li>com.tech_freaks.action.LogonAction.java<br />
While we take inspiration from LogonServlet of our previous example, we improve the design to not include any database connectivity code in our Action class. To achieve this, we will refactor all the DB access / calls to a Helper class by the name DBHelper.java. This also helps in modifying the code, if we tomorrow decide to use Entity Beans (EJB) or hibernate to access the database instead of raw JDBC code with minimum impact on our Action class. The LogonAction performs the following tasks.<br />
&#8211; Perform basic empty check on server side before calling the database<br />
&#8211; Call our DB Helper class, with user name and password to check, if the combination exists.</li>
<li>com.tech_freaks.utils.DBHelper.java<br />
It will perform all task related to getting connection to the DB, executing a query and method to return Boolean indicating, if record was available or not in the DB. We do not write method like, isUserPasswordValid in this class, as it is a generic low level class, and should not be aware about the logic implemented in the classes calling it. Below would be the methods:</li>
</ul>
<p style="padding-left: 40px; text-align: left;"><em>public boolean containsResults(String query, String[] params) </em>-&gt; The params we have created as a String array, which will have both user name and password. If the values required for the where clause of the SQL query are of different datatype, we might need a different approach. This method is invoked by the LogonAction</p>
<p style="padding-left: 40px; text-align: left;"><em>private Connection getConnection()</em> -&gt; Internally used to get a Connection object for the DB call.</p>
<p style="padding-left: 40px; text-align: left;"><em>private void closeConnection(Connection conn)</em> &#8211; Closes an open connection after the query has been executed.</p>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-align: left;"><span style="font-size: 12pt;"><strong>Development</strong></span></p>
<p style="text-align: left;">We will first start by adding a struts.xml for our project. In eclipse, you will have to create a folder &#8216;classes&#8217; under \workspace\Struts2LoginApp\WebContent\WEB-INF\ and add struts.xml in that folder.</p>
<p style="text-align: left;">Below is the struts.xml</p>
<pre class="language-markup"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd"&gt;
&lt;struts&gt;
&lt;constant name="struts.devMode" value="true" /&gt;
   &lt;package name="loginapp" extends="struts-default"&gt;
     
      &lt;action name="logon" 
            class="com.tech_freaks.action.LogonAction" 
            method="execute"&gt;
            &lt;result name="success"&gt;/Home.jsp&lt;/result&gt;
            &lt;result name="input"&gt;/Login.jsp&lt;/result&gt;
            &lt;result name="error"&gt;/Login.jsp&lt;/result&gt;
      &lt;/action&gt;
   &lt;/package&gt;
&lt;/struts&gt;</code></pre>
<p style="text-align: left;"> The configuration file is straightforward and easy to understand. &lt;constant&gt; is setting the project in a development mode. This will give helpful errors in the logs / screen while debugging issues.</p>
<p style="text-align: left;">&lt;package&gt; is applicable when we divide the configure into multiple logical parts instead of having all action definition inside single file.<br />
Let us take a careful look at the entry for &lt;action&gt; and ensure all mapping components are named to match the entries in here.</p>
<p style="padding-left: 30px; text-align: left;">â‚¬¢ â‚¬Å“nameâ‚¬ attribute needs to be mapped to the &lt;form action=â‚¬â‚¬&gt; in the Login.jsp. This is how struts knows which Action class to invoke. We leave the method to â‚¬Å“executeâ‚¬ as our Action class will extend ActionSupport class and override the execute method.<br />
â‚¬¢ â‚¬Å“classâ‚¬ should be fully qualified class name of the Action class.<br />
â‚¬¢ When the Action executes, we can configure different JSPs / views to invoke after completion. The String value returned from Action.execute() method should match the â‚¬Å“nameâ‚¬ attribute in one of the â‚¬Å“resultâ‚¬. However, it is important to note that, if we are using struts validation framework, we need to have an &lt;result&gt; with<span class="Apple-converted-space"> </span><strong>name=â‚¬inputâ‚¬</strong>. The framework will redirect to the view configured for &lt;result&gt; name=&#8221;input&#8221; with the error message. If you do not have entry for â‚¬Å“inputâ‚¬ you will see an error saying that â‚¬Å“No result defined for action and result input &#8211; action â‚¬â€œâ‚¬Å“</p>
<p style="text-align: left;">Next, we take a look at the LogonAction.java.<br />
As we plan to validate for empty fields, we need to extend the ActionSupport class. Once extended, we need to override the methods execute() and validate(). The next thing is we need to have instance variables for user fields in the Login.jsp. Note that the instance variable (mainly the getter/ setters for the instance variables) must match exactly to the â‚¬Å“nameâ‚¬ attribute on the &lt;input&gt; fields on the JSP. This is also a difference between struts 1.1 were we had separate ActionForms which had the fields mapped to the &lt;input&gt;.<br />
The complete java code is below</p>
<pre class="language-java"><code> package com.tech_freaks.action;

import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.ValueStack;
import com.tech_freaks.utils.DBHelper;

public class LogonAction extends ActionSupport {
	
	public static final String LOGIN_SUCCESS = "success";
	public static final String LOGIN_FAILED = "error";
	
	private static final String LOGIN_QUERY = "select * from users where user_name=? and password=?";
	
	private String userName;
	private String password;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public String execute() throws Exception {
		ValueStack stack = ActionContext.getContext().getValueStack();
		String[] params = new String[] {userName, password};
		DBHelper dbHelper = new DBHelper();
		
		boolean isSuccess = dbHelper.containsResult(LOGIN_QUERY, params);
		if(isSuccess)
			return LOGIN_SUCCESS;
		else {
			Map&lt;String, Object&gt; context = new HashMap&lt;String, Object&gt;();
			context.put("errorMsg", new String("Invalid user name or password. Try again.")); 
			stack.push(context);
			return LOGIN_FAILED;
		}
	}

	@Override
	public void validate() {
		 if (userName == null || userName.trim().equals(""))
	      {
	         addFieldError("userName","Please enter a user name to login with.");
	      }
		 if (password == null || password.trim().equals(""))
	      {
	         addFieldError("password","Please enter a password.");
	      }
	}
}
 </code></pre>
<pre class="brush:java" style="color: #333333; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-indent: 0px; text-transform: none; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-align: left;"></pre>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-align: left;">Let&#8221;s take a close look at<span class="Apple-converted-space"> </span><em>validate()</em>. Use the<strong><span class="Apple-converted-space"> </span>addFieldError()</strong><span class="Apple-converted-space"> </span>method with the first parameter matching the field name which has the validation error. Again, this name needs to exactly match with &lt;input&gt; name attribute in the JSP. If we use the struts taglib in the JSP, it also takes care of showing the error message for each field inline to the field.</p>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-align: left;">Next, we take a look at the<em><span class="Apple-converted-space"> </span>execute()</em><span class="Apple-converted-space"> </span>method. It is fairly straightforward. It calls the DBHelper class to verify in the database, if a record exists for the supplied userName and password combination. Based on the result, it returns â‚¬Å“successâ‚¬ or â‚¬Å“errorâ‚¬. The value returned needs to match with the &lt;result&gt; name attribute defined in the struts.xml which we examined before. The appropriate view will be displayed.</p>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-align: left;">For the failed login attempt, we have to go back to the login page and display an error message. We use this requirement to explain<span class="Apple-converted-space"> </span><strong>ActionContext</strong><span class="Apple-converted-space"> </span>and <strong>ValueStack </strong>concept in struts 2. The ActionContext has access to variables like session, request params etc. It also contains a value stack. You can put objects into value stack. As the name suggests, it is a stack with push, pop, peek methods in it. In the JSP, when you want to access the variables in the ActionContext using the struts taglib, you use #&lt;attribute&gt; say #session. However, for accessing value stack, we do not have to use the #. As you can see, we are pushing a Map with key<span class="Apple-converted-space"> </span><em>errorMsg</em><span class="Apple-converted-space"> </span>into the value stack, with value containing the error message which needs to be displayed to the user on failed login attempt.</p>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-align: left;"><strong>Login.jsp</strong><br />
This page is modified from our previous version of Login.jsp. The main change is the struts taglib usage. We use the &lt;s:property&gt; to pull the attribute from the value stack which we previously discussed. This is used where the login attempt fails. We have used &lt;s:form&gt;, &lt;s:textfield&gt; etc. They help giving inline errors for each field as per the login in the validate() method.</p>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-align: left;">Below is the complete Login.jsp</p>
<pre class="language-markup"><code>&lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%&gt;
&lt;%@ taglib prefix="s" uri="/struts-tags"%&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;
Tech-freaks.com - Struts2 - SimpleLogin App Login Page
&lt;/title&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;s:property value="errorMsg"/&gt;&lt;br/&gt;
&lt;s:form method="POST" action="logon"&gt;
	&lt;s:textfield  name="userName" label="User Name"/&gt;
	&lt;s:password  name="password" label="Password" /&gt;
	&lt;s:submit name="submit" label="Submit" align="center" /&gt;
		
&lt;/s:form&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-align: left;"><strong>Home.jsp</strong><br />
Simple page, which when requested due to successful login, fetches the â‚¬Å“usernameâ‚¬ field and displays the welcome message. Below is the complete JSP</p>
<pre class="language-markup"><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;&lt;%@page
	language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%&gt;
&lt;%@ taglib prefix="s" uri="/struts-tags"%&gt;
&lt;html&gt;
	&lt;head&gt;
		&lt;title&gt;
		Tech-freaks.com - Struts 2 SimpleLogin App Home Page
		&lt;/title&gt;
		&lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt;
	&lt;/head&gt;
	&lt;body&gt;
	 	&lt;h1&gt; Welcome to Tech-freaks.com - Struts2 Simple Logon App, &lt;s:property value="userName"/&gt;&lt;/h1&gt;
	&lt;/body&gt;
&lt;/html&gt;</code></pre>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-align: left;"><strong><span style="font-size: 12pt;">Testing</span></strong></p>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-align: left;">Once you have all the components put in, right click the project in Eclipse and Export as WAR. Drop the generated WAR in &lt;Tomcat&gt;\webapps folder and start Tomcat. Verify Tomcat logs, if the deployment of the WAR was successful.<span class="Apple-converted-space"> </span><br />
Test by accessing the URL : http://localhost:8080/Struts2LoginApp/Login.jsp (Modify the port and context name as per your customization)<br />
Run and verify each scenario mentioned in the requirement.</p>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-align: left;"><strong>Congratulations, on completing your first &#8220;Non-Hello World&#8221; project using struts 2!</strong></p>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-align: left;">You can download the complete Eclipse project from Github by clicking the link below.</p>
<p style="color: #333333; font-family: Tahoma, Helvetica, Arial, sans-serif; font-size: 12.16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15.808px; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-align: left;"><a style="color: #1b57b1; text-decoration: none; font-weight: normal;" title="Download complete Struts 2 Login App Source code from Github" href="https://github.com/tech-freaks/struts2-login-app" target="_blank" rel="alternate noopener noreferrer">Download complete Struts 2 Login App Source code from Github</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.tech-freaks.com/java/jsp-servlets/struts2-login-application.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Simple Registration Application using JSP, Servlets and JDBC connectivity to MySQL</title>
		<link>https://www.tech-freaks.com/java/jsp-servlets/simple-registration-application.html</link>
					<comments>https://www.tech-freaks.com/java/jsp-servlets/simple-registration-application.html#respond</comments>
		
		<dc:creator><![CDATA[Tech Programmer]]></dc:creator>
		<pubDate>Mon, 18 Feb 2013 03:58:34 +0000</pubDate>
				<category><![CDATA[JSP & Servlets]]></category>
		<guid isPermaLink="false">http://localhost/tfcom_wp/2013/02/18/simple-registration-application/</guid>

					<description><![CDATA[Requirement Create a Registration Form to enter user name, password, first name, last name, email address, secret question, answer and [&#8230;]]]></description>
										<content:encoded><![CDATA[		<div class="wpulike wpulike-default " ><div class="wp_ulike_general_class wp_ulike_is_not_liked"><button type="button"
					aria-label="Like Button"
					data-ulike-id="32"
					data-ulike-nonce="c833942467"
					data-ulike-type="post"
					data-ulike-template="wpulike-default"
					data-ulike-display-likers=""
					data-ulike-likers-style="popover"
					class="wp_ulike_btn wp_ulike_put_image wp_post_btn_32"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0"></span>			</div></div>
	<p style="text-align: left;"><strong>Requirement</strong></p>
<ul style="text-align: left;">
<li><span style="line-height: 1.3em;">Create a Registration Form to enter user name, password, first name, last name, email address, secret question, answer and register a new user to system.</span></li>
<li><span style="line-height: 1.3em;">Validate if the user name and password is not blank. Display error message to user, if either of them is blank.</span></li>
<li><span style="line-height: 1.3em;">Validate if the user name already exists and display an error message to the user</span></li>
<li><span style="line-height: 1.3em;">In the event of an error, ensure that registration form is displayed again with all prefilled information</span></li>
<li><span style="line-height: 1.3em;">On successful registration, set the user name in session and forward to home page.</span></li>
</ul>
<p style="text-align: left;"><strong style="line-height: 1.3em;">Pre-requisites</strong></p>
<ul style="text-align: left;">
<li><span style="line-height: 1.3em;">MySQL and Tomcat is already installed</span></li>
<li><span style="line-height: 1.3em;">You have basic knowledge of MySQL to create tables and insert / update records</span></li>
<li><span style="line-height: 1.3em;">You have basic knowledge of Java and J2EE web applications</span></li>
<li><span style="line-height: 1.3em;">Have your favorite IDE for developing / reviewing code</span></li>
<li><span style="line-height: 1.3em;">This workshop adds the registration functionality to the previous article <a title="Simple Login Application" href="java/jsp-servlets/simple-login-application.html" target="_blank" rel="noopener noreferrer">Simple Login Application</a>. Reviewing that article prior to this article would help.</span></li>
</ul>
<p style="text-align: left;"><strong style="line-height: 1.3em;">Concepts Covered</strong></p>
<ul style="text-align: left;">
<li><span style="line-height: 1.3em;">JDBC connectivity to MySQL from Servlet</span></li>
<li><span style="line-height: 1.3em;">Simple application of JSTL tag</span></li>
<li><span style="line-height: 1.3em;">Using request attribute and request parameters</span></li>
<li><span style="line-height: 1.3em;">Basic error handling concepts</span></li>
</ul>
<p style="text-align: left;"><strong>NOTE</strong>: Don&#8217;t even think of using the code as is for a production environment<br />
This is just for education purpose but you can take inspiration from this code.</p>
<p><span id="more-32"></span></p>
<p style="text-align: left;"><strong>Analysis and Design</strong></p>
<p style="text-align: left;"><span style="line-height: 1.3em;">We start with the <a title="Simple Login Application" href="jsp-servlets/simple-login-application.html" target="_blank" rel="noopener noreferrer">Simple Login application</a> article as a baseline. First, we need to update the database to add more fields and constraints. We will make the user_name field as the primary key for the USERS table.</span></p>
<p style="text-align: left;"><span style="line-height: 1.3em;">We create a new class for database connectivity code unlike in the simple login application and refactor the connectivity code out of the Servlet code. This is a good design practice to keep the servlet layer uncoupled to the database code layer. We would still following the MVC design model.</span></p>
<p style="text-align: left;"><span style="line-height: 1.3em;">Below is a list of elements identified as part of the design:</span></p>
<ul style="text-align: left;">
<li><span style="line-height: 1.3em;"><em>com.techfreaks.db.util.ConnectionUtil</em> &#8211; Utility class for getting connection, closing connection and executing insert / update query</span></li>
<li><span style="line-height: 1.3em;"><em>com.techfreaks.registration.servlet.RegistrationServlet</em> &#8211; This servlet is the controller. It calls the ConnectionUtil and forwards to the home page or Registration page</span></li>
<li><span style="line-height: 1.3em;"><em>RegistrationForm.jsp</em> &#8211; UI page with fields for registration form</span></li>
<li><span style="line-height: 1.3em;"><em>Home.jsp</em> &#8211; UI page picked up after successful registration. It is the same page taken from Login Application</span></li>
<li><span style="line-height: 1.3em;"><em>web.xml</em> &#8211; Deployment Descriptor in which the servlet is registered.</span></li>
</ul>
<p style="text-align: left;"><strong style="line-height: 1.3em;">Development</strong></p>
<p style="text-align: left;"><em>Setup the database:</em></p>
<p style="text-align: left;">We alter the USERS table to add the new fields. However, for quick reference we provide the create USERS table DDL. You will have to drop and recreate the table using the below DML, if you already have an USER table. You could very well manually edit the existing table based on the below DDL.</p>
<pre class="brush:sql" style="text-align: left;">CREATE TABLE `users` (
	`first_name` VARCHAR(100) NOT NULL,
	`last_name` VARCHAR(100) NOT NULL,
	`email_address` VARCHAR(50) NOT NULL,
	`secret_question` VARCHAR(200) NULL DEFAULT NULL,
	`secret_answer` VARCHAR(200) NULL DEFAULT NULL,
	`user_name` VARCHAR(100) NOT NULL,
	`password` VARCHAR(100) NOT NULL,
	PRIMARY KEY (`user_name`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;
</pre>
<p style="text-align: left;">A screenshot of the development environment is provided below. Make sure the mysql drivers, jstl libraries and tlds are all available. For making your life easy, we have included a hot deployable WAR file at the end of the workshop.</p>
<p style="text-align: left;"><img loading="lazy" decoding="async" title="Simple Registration App Environment Folder structure" src="https://www.tech-freaks.com/wp-content/uploads/2013/02/registrationapp_env_setup.png" alt="Simple Registration App Environment Folder structure" width="316" height="371" border="0" /></p>
<hr class="system-pagebreak" title="Coding and Unit Testing" />
<p style="text-align: left;"><strong>Coding and Unit testing:</strong></p>
<p style="text-align: left;"><span style="line-height: 1.3em;">First, we would look at the ConnectionUtil. Below are the methods we would need for the ConnectionUtil. Note that we create this class as a static class (A class with static methods).Ã‚ </span></p>
<p style="text-align: left;">&#8211; <em>getConnection()</em><br />
<em>&#8211; closeConnection()</em><br />
<em>&#8211; executeQuery(String strQuery)</em></p>
<p style="text-align: left;">If you have read the article about simple login application, you would have already noticed thatt we just refactored the first two methods out of the LoginServlet. We prevent the code to be spread across multiple servlets this way. It is used to get a SQL Connection object and to close an open connection respectively.</p>
<p style="text-align: left;">In this example, we would use <em>java.sql.Statement</em> instead of <em>java.sql.PrepareStatement</em> which we used in LoginServlet, to spice things up. We need to pass the complete query to the Statement object to execute a query. The executeQuery can take an insert / update query and execute it. It would internally call getConnection() and closeConnection() to fetch and close a connection.</p>
<p style="text-align: left;">Below is the method executeQuery:</p>
<pre class="language-java"><code>public static void executeQuery(String strQuery) throws Exception {
		Connection conn = null;
		
		try {
			conn = getConnection();
			Statement stmt  = conn.createStatement();
			stmt.executeUpdate(strQuery);
			
		} catch (SQLException sqle) {
			System.out.println("SQLException: Unable to execute query : "+strQuery);
			throw sqle;
		} catch (Exception e) {
			System.out.println("Exception: Unable to execute query: "+strQuery);
			throw e;
		} finally {
			closeConnection(conn);
		}
	}</code></pre>
<pre class="brush:java" style="text-align: left;"></pre>
<p style="text-align: left;">We also moved the static variables like database name, db user name and db password from the servlet to the ConnectionUtil.</p>
<pre class="language-java"><code>        private static final String DBNAME = "tf_loginappdb";
	private static final String DB_USERNAME = "root";
	private static final String DB_PASSWORD = "admin*";</code></pre>
<pre style="text-align: left;"></pre>
<p style="text-align: left;">If your database has different dbname, username or password, you will need to update this and recompile you java file for the application to be able to connect to MySQL database.</p>
<p>Next, we would look at the code in the RegistrationServlet. It gets all the fields from the RegistrationForm in the request parameters. Below are the methods which we would add to this servlet.</p>
<p style="text-align: left;"><em>&#8211; doPost()</em><br />
<em>&#8211; validateData()</em><br />
<em>&#8211; setRequestAttributes()</em><br />
<em>&#8211; generateInsertQuery()</em></p>
<p style="text-align: left;">The doPost is the entry point to the servlet for html form POST. We have all the controller logic in here. The other methods are in a way, do not do the controller work. We use them for simple tasks which do not warranty creating other classes in our case. However, in a real life application, if the task is complex we might want to create new classes to delegate the task.</p>
<p style="text-align: left;">validateData() is used to implement the requirement that the userName and password cannot be empty. It validates and returns a boolean indicating success or failure of the validation.</p>
<p style="text-align: left;">generateInsertQuery() fetches the request parameters and generates the insert query which will be passed on to the executeQuery method of the ConnectionUtil. Below is the code for the method:</p>
<pre class="brush:java" style="text-align: left;"></pre>
<pre class="language-java"><code> private String generateInsertQuery(HttpServletRequest request) {
		String strUserName = request.getParameter("userName");
		String strPassword = request.getParameter("password");
		String strFirstName = request.getParameter("firstName");
		String strLastName = request.getParameter("lastName");
		String strEmail = request.getParameter("email");
		String strSecretQuestion = request.getParameter("secretQuestion");
		String strSecretAnswer = request.getParameter("secretAnswer");

		StringBuffer strQuery = new StringBuffer(INSERT_QUERY_START);
		strQuery.append(strFirstName);
		strQuery.append("', '");
		strQuery.append(strLastName);
		strQuery.append("', '");
		strQuery.append(strEmail);
		strQuery.append("', '");
		strQuery.append(strSecretQuestion);
		strQuery.append("', '");
		strQuery.append(strSecretAnswer);
		strQuery.append("', '");
		strQuery.append(strUserName);
		strQuery.append("', '");
		strQuery.append(strPassword);
		strQuery.append("')");
		
		System.out.println("Insert query : "+strQuery.toString());
		
		return strQuery.toString();

	}
 </code></pre>
<pre class="brush:java" style="text-align: left;">
setRequestAttributes() is used to implement the requirement about maintaining the data entered in the registration form in the even of an error. Do you remember banging your head against the keyboard after filling up a long registration form and clicking submit, only to find the form reloading with an error message and all the data you entered spending hours, boom! gone!<img decoding="async" title="Yell" src="media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-yell.gif" alt="Yell" border="0" /></pre>
<p style="text-align: left;">Instead of the classic get each parameter and set to attribute, we would just do a generic loop through. This would keep the code small. Imagine your registration form is 100 fields instead, the below code will not require any modification. Below is the code:</p>
<pre class="language-java"><code>	private void setRequestAttributes(HttpServletRequest request) {
		Enumeration  enumKeys =  request.getParameterNames();
		while(enumKeys.hasMoreElements()) {
			String key  = enumKeys.nextElement();
			request.setAttribute(key, request.getParameter(key))  ;
		}
	} </code></pre>
<pre class="brush:java" style="text-align: left;"></pre>
<p style="text-align: left;">The doPost() method is provided below. It has inline comment to explain key control logic. Once the insert in the database is successful, we set the userName is session and redirect to Home.jsp.</p>
<p style="text-align: left;">The error messages are managed by putting a request attribute on error situation and forwarding back to RegistrationForm. You will see the difference between the redirect and forward. You will see that the request attributes are available and also the URL of the servlet remains the same after the request is forwarded to the JSP. Also, note how we utilize the primary key duplicate error message and set the error message. We use the same pattern to set error message, set the request attributes and forward to registration page on all the error conditions.</p>
<pre class="language-java"><code>protected void doPost(HttpServletRequest request, HttpServletResponse 
			response) throws ServletException, IOException {
		
		String strUserMsg = null;
		HttpSession session = request.getSession();
		RequestDispatcher reqDisp =  request.getRequestDispatcher(REGISTRATION_PAGE);
		
		try {
			//Check if data is valid
			if(validateData(request)) {
				ConnectionUtil.executeQuery(generateInsertQuery(request));
				System.out.println("Insert into database successful");
				session.setAttribute("userName", request.getParameter("userName"));
				response.sendRedirect(getServletContext().getContextPath()+HOME_PAGE);
			} else {//If data is invalid
				strUserMsg = "User Name and Password cannot be empty";
				setRequestAttributes(request);
				request.setAttribute("userMsg", strUserMsg);
				reqDisp.forward(request, response);
			}
			
		} catch(SQLException sqle ) {
			System.out.println("Unable to register user: "+sqle.getMessage());
			//Check if we are getting duplicate key exception on userName
			if(sqle.getMessage().indexOf("Duplicate entry")!=-1) {
				System.out.println("User already exists");
				strUserMsg = "User name "+request.getParameter("userName")+" already " +
						"exists. Please try another user name.";
			} else { //If other SQLException than dup key exception
				strUserMsg = "Unable to register user "+request.getParameter("userName")+
				". Please try again later.";
			}
			setRequestAttributes(request);
			request.setAttribute("userMsg", strUserMsg);
			reqDisp.forward(request, response);

		} catch(Exception e) {//If it goes into Exception other than SQLException
			System.out.println("Unable to register user: "+e.getMessage());
			strUserMsg = "Unable to register user "+request.getParameter("userName")
			+". Please try again later.";
			setRequestAttributes(request);
			request.setAttribute("userMsg", strUserMsg);
			reqDisp.forward(request, response);

		}
		
		

	}</code></pre>
<pre class="brush:java" style="text-align: left;"></pre>
<p style="text-align: left;">Next, let us look at our RegistrationForm.jsp. We highlight small snippet of code here</p>
<pre class="language-markup"><code>&lt;p&gt;&lt;font color="#ff0000"&gt;&lt;c:out value="${userMsg}"/&gt;&lt;/font&gt;&lt;/p&gt;
&lt;form name="frmRegistration" method="post" action="&lt;c:out value="${pageContext.servletContext.contextPath}" /&gt;/servlet/RegistrationServlet"&gt;
&lt;table border="1"&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;First Name&lt;/td&gt;
&lt;td&gt;&lt;input type="text" name="firstName" value ="&lt;c:out value="${firstName}"/&gt;" size="20"&gt;&lt;/td&gt;</code></pre>
<ul style="text-align: left;">
<li><span style="line-height: 1.3em;">JSTL is used display the userMsg which we set in the request attribute in our servlet.</span></li>
<li><span style="line-height: 1.3em;">JSTL is used to pick the contextPath from servletContext</span></li>
<li><span style="line-height: 1.3em;">JSTL is used to display user entered data in the event of an error</span></li>
</ul>
<p style="text-align: left;">We picked up the Home.jsp from the simple login application. You can get the complete WAR file to the simple registration application by clicking <a title="SimpleRegistrationApp" href="sourcecode/SimpleRegistrationApp/SimpleRegistrationApp.war" target="_blank" rel="noopener noreferrer">SimpleRegistrationApp.war</a>.</p>
<p style="text-align: left;">You just need to hot deploy SimpleRegistrationApp.war to webapps folder in the Tomcat program file and it would explode. Verify the application by accessing http://localhost:8080/SimpleRegistrationApp/RegistrationForm.jsp and run some tests to figure out how it works for you.</p>
<p style="text-align: left;">Feel free to leave a comment below, if you run into any issues. Enjoy!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.tech-freaks.com/java/jsp-servlets/simple-registration-application.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Simple Login Application using JSP, Servlets and JDBC connectivity to MySQL</title>
		<link>https://www.tech-freaks.com/java/jsp-servlets/simple-login-application.html</link>
					<comments>https://www.tech-freaks.com/java/jsp-servlets/simple-login-application.html#respond</comments>
		
		<dc:creator><![CDATA[Tech Programmer]]></dc:creator>
		<pubDate>Fri, 15 Jun 2012 08:43:42 +0000</pubDate>
				<category><![CDATA[JSP & Servlets]]></category>
		<guid isPermaLink="false">http://localhost/tfcom_wp/2012/06/15/simple-login-application/</guid>

					<description><![CDATA[Requirement Create a Login page to enter user name and password On submit, validate the user name / password against [&#8230;]]]></description>
										<content:encoded><![CDATA[		<div class="wpulike wpulike-default " ><div class="wp_ulike_general_class wp_ulike_is_not_liked"><button type="button"
					aria-label="Like Button"
					data-ulike-id="47"
					data-ulike-nonce="d08d4ef225"
					data-ulike-type="post"
					data-ulike-template="wpulike-default"
					data-ulike-display-likers=""
					data-ulike-likers-style="popover"
					class="wp_ulike_btn wp_ulike_put_image wp_post_btn_47"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0"></span>			</div></div>
	<p style="text-align: left;"><strong>Requirement</strong></p>
<ul style="text-align: left;">
<li>Create a Login page to enter user name and password</li>
<li>On submit, validate the user name / password against MySQL database</li>
<li>If the authentication is successful, forward to home page showing welcome message along with the user name</li>
<li>If the authentication fails, return back to the login page with appropriate error message.</li>
<li>If there is exception / errors during authentication process return back to login page with appropriate error message.</li>
</ul>
<p style="text-align: left;"><strong>Pre-requisites</strong></p>
<ul style="text-align: left;">
<li>MySQL and Tomcat is already installed</li>
<li>You have basic knowledge of MySQL to create tables and insert / update records</li>
<li>You have basic knowledge of Java and J2EE web applications</li>
<li>Have your favorite IDE for developing / reviewing code.</li>
</ul>
<p style="text-align: left;"><strong>Concepts Covered</strong></p>
<ul style="text-align: left;">
<li>JDBC connectivity to MySQL from Servlet</li>
<li>Simple application of JSTL tag</li>
<li>Using session variable in Servlet</li>
<li>Polymorphism concept using JDBC</li>
<li>Basic error handling concepts</li>
</ul>
<blockquote><p><strong>NOTE</strong>: Don&#8217;t even think of using the code as is for a production environment<br />
This is just for education purpose but you can take inspiration from this code.</p></blockquote>
<hr />
<blockquote><p>Checkout our similar article on <a href="java/jsp-servlets/struts2-login-application.html" target="_blank" rel="noopener">simple login application using Struts 2 Framework</a></p></blockquote>
<hr class="system-pagebreak" title="Analysis-Design-MySQL-Setup" />
<p><span id="more-47"></span></p>
<p style="text-align: left;"><strong>Analysis and Design</strong></p>
<p>The application is pretty straightforward and it is not too hard to design. Looking through the requirement, we need a database instance in MySQL which has a table. We would name this table as <em>USERS</em>.</p>
<p>USERS table needs to have user_name and password field but can have other fields.</p>
<p>For the login screen, we will create a JSP. For the home page after successful login, we will create another JSP. Following MVC, we will let Servlet handle the request. The connectivity with DB should be extracted out of the Servlet for a complex application. However, for simplicity we have maintained it within the servlet.</p>
<p>Below are the identified elements:</p>
<p><em>Login.jsp<br />
Home.jsp<br />
LogonServlet.java</em></p>
<p><strong>Development</strong></p>
<p><em>Setup the database:</em></p>
<p style="text-align: left;">You can create a new database in MySQL or create the below table in an already existing database. Below is the script which you will have to execute in MySQL prompt for create the table.</p>
<pre class="brush:sql" style="text-align: left;">CREATE TABLE `USERS` (
`first_name` VARCHAR(100) NOT NULL,
`last_name` VARCHAR(100) NOT NULL,
`user_name` VARCHAR(100) NOT NULL,
`password` VARCHAR(100) NOT NULL
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;
</pre>
<p>You can use the below insert to add users to the USERS table. You can add as many users as you want in this table.</p>
<pre class="brush:sql" style="text-align: left;">INSERT INTO `users` (`first_name`, `last_name`, `user_name`, `password`) VALUES ('Tech', 'Freaks', 'tech_freaks', 'Passw0rd');
</pre>
<p style="text-align: left;">For Connecting to MySQL database from Servlet, you would require MySQL JDBC drivers. Below is the link to download the latest and greatest version of the drivers.<br />
MySQL Driver : <a title="http://dev.mysql.com/downloads/connector/j/" href="http://dev.mysql.com/downloads/connector/j/" target="_blank" rel="nofollow noopener noreferrer">http://dev.mysql.com/downloads/connector/j/</a></p>
<p style="text-align: left;">Once we have this we are good to start the Java side development. Below screen explains how the directory structure will look in your development environment.</p>
<p style="text-align: left;"><img loading="lazy" decoding="async" title="Application Directory Structure" src="https://www.tech-freaks.com/wp-content/uploads/2012/06/directory_structure.png" alt="Application Directory Structure" width="211" height="208" border="0" /></p>
<hr class="system-pagebreak" title="Coding-Servlet" />
<p style="text-align: left;"><em>Coding the Servlet:</em></p>
<p>Our servlet has is the work horse and does most of the work. We will just implement the doPost method of the servlet, as we will POST the information from the HTML Form.</p>
<p>We will write three private methods in the Servlet for doing the work internally.</p>
<p>&#8211; getConnection()<br />
&#8211; authenticateLogin()<br />
&#8211; closeConnection()</p>
<p>The getConnection() will have the code for low level connectivity with MySQL using the JDBC driver. It will return a java.sql.Connection object. For a real life application, we might have a custom Connection pool implementation or use the Connection pool implementation managed by the Application Server / Web Container. It will use the javax.sql.Datasource object to reach to Connection object.</p>
<pre class="language-java"><code>private Connection getConnection() throws Exception {
   Connection conn = null;
   try {
     String url = "jdbc:mysql://localhost/"+DBNAME+"?user="+DB_USERNAME+"&amp;password="+DB_PASSWORD;
     Class.forName("com.mysql.jdbc.Driver");
     conn = DriverManager.getConnection(url);
   } catch (SQLException sqle) {
      System.out.println("SQLException: Unable to open connection to db: "+sqle.getMessage());
      throw sqle;
   } catch(Exception e) {
      System.out.println("Exception: Unable to open connection to db: "+e.getMessage());
      throw e;
   }
   return conn;
}</code></pre>
<p style="text-align: left;">The above code is pretty straight forward for fetching Connection object. However, it has some key polymorphism concepts which are generally not clearly understood.</p>
<p><em>Question 1: </em>Connection, Statement, ResultSet are all interface. We all know, that interface cannot be instantiated. From where do we get the implementation? Who is instantiating it?<br />
<em>Answer: </em>All the interface provided above are specification or contract provided as part of JDBC specification. The driver JAR which we added has implementation classes. So, if we look at Oracle DB driver JAR, it would be different. The implementation classes will be different but it would be implementing the interfaces provided in JDBC. Our code should always Ã¢â‚¬Ëœcode to the interfaceÃ¢â‚¬â„¢ and NEVER to the implementation class. This will help us make our code generic for using with other JDBC drivers and with other databases. Ofcourse, this is just a step to make the code database independent. Neverthless this is an awesome example of Polymorphism. Try this in your next interview when they ask you about a real life example about polymorphism, instead of giving the bookish examples. You might just have the interviewer&#8217;s mouth wide open! ðŸ˜Ž</p>
<p><em>Question 2</em>: Thanks for explaining. However, it still does not explain how the implementation class is instantiated and what the name of the implementation class is.<br />
Answer: The string as a parameter to the Class.forName (&#8220;com.mysql.jdbc.Driver&#8221;) is the Driver class for the MySQL JDBC driver. It is loaded in memory. The further calls on the DriverManager works with the Driver instance com.mysql.jdbc.Driver. If you unjar the JDBC driver, you will see a implementation class for all Connection, Statement, ResultSet and so on. Once the JDBC driver is registered, the DriverManager.getConnection will give the Connection instance specific to the MySQL JDBC driver.</p>
<p>Let us get back from the interview mode, to development mode again <img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The authenticateLogin() method will look something like this:</p>
<pre class="language-java"><code>private boolean authenticateLogin(String strUserName, String strPassword) throws Exception {
   boolean isValid = false;
   Connection conn = null;
   try {
     conn = getConnection();
     PreparedStatement prepStmt = conn.prepareStatement(LOGIN_QUERY);
     prepStmt.setString(1, strUserName);
     prepStmt.setString(2, strPassword);
     ResultSet rs = prepStmt.executeQuery();
     if(rs.next()) {
       System.out.println("User login is valid in DB");
       isValid = true; 
     }
  } catch(Exception e) {
    System.out.println("validateLogon: Error while validating password: "+e.getMessage());
    throw e;
  } finally {
     closeConnection(conn);
  }
  return isValid;
}</code></pre>
<pre class="brush:java" style="text-align: left;">Notice that we have used PreparedStatement instead of Statement. We have purposely used PreparedStatement, as simple query using Statement might be easily prone to SQL Injection. For a Select query, the threat is relatively less, however, this needs to be taken care for update and delete operations.
We have maintained the queries, passwords as static variables in the Servlet as it will not change. Ideally, they should be taken from some properties or XML file.</pre>
<pre class="language-java"><code>private static final String DBNAME = "tf_loginappdb";
private static final String DB_USERNAME = "root";
private static final String DB_PASSWORD = "admin*";

private static final String LOGIN_QUERY = "select * from users where user_name=? and password=?";
private static final String HOME_PAGE = "../Home.jsp";
private static final String LOGIN_PAGE = "../Login.jsp";</code></pre>
<p style="text-align: left;">You might have to update the value specific to your database instance.</p>
<p>Another important aspect is the error handling. Any exception occurring which will impact processing should be intimated to the end user. However, it should hide the technical issues to prevent panic amongst the end user. Imagine as an end user trying to login to your bank account in which you have all your fortune and seeing the error message which reads, &#8220;Sorry the database has been deleted. All your money is gone!&#8221; <img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The approach which we use is to provide the end user with error message as &#8220;Unable to validate your login in our database&#8221;. However, in the System.out you might want to add more information about the error for debugging. You can even put the stackTrace. Using Log4J or similar libraries in high quality application is recommended for logs which can be enabled / disabled at component level depending on the environment. The approach is indicated in the doPost method of the servlet.</p>
<pre class="language-java"><code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   String strUserName = request.getParameter("userName");
   String strPassword = request.getParameter("password");
   String strErrMsg = null;
   HttpSession session = request.getSession();
   boolean isValidLogon = false;
   try {
     isValidLogon = authenticateLogin(strUserName, strPassword);
     if(isValidLogon) {
        session.setAttribute("userName", strUserName);
     } else {
        strErrMsg = "User name or Password is invalid. Please try again.";
     }
   } catch(Exception e) {
     strErrMsg = "Unable to validate user / password in database";
   }

   if(isValidLogon) {
     response.sendRedirect(HOME_PAGE);
   } else {
     session.setAttribute("errorMsg", strErrMsg);
     response.sendRedirect(LOGIN_PAGE);
   }

}</code></pre>
<p style="text-align: left;">See how we get the username and password from the request and pass to the method for authentication. Also, at the end we do a send redirect with either the errorMsg or username in session for displaying in Login.jsp or Home.jsp respectively. Ideally, the errorMsg should be put in requestScope and forwarded to JSP. However, since we are doing a redirect, we had to put it in session scope. Try changing the code for forwarding and using the requestScope instead. If you have queries, please feel free to add your comments / queries in the comments section at the end of the article.</p>
<p>Once the Servlet is ready, we need to registered and map it in the Web application&#8217;s deployment descriptor, web.xml. The web.xml is pretty straightforward.</p>
<hr class="system-pagebreak" title="Deployment-Descriptor-JSP" />
<pre class="language-markup"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt;
&lt;display-name&gt;SimpleLoginApp&lt;/display-name&gt;
  &lt;servlet&gt;
    &lt;description&gt;
    &lt;/description&gt;
    &lt;display-name&gt;LogonServlet&lt;/display-name&gt;
    &lt;servlet-name&gt;LogonServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;in.techfreaks.login.servlet.LogonServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;LogonServlet&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/servlet/LogonServlet&lt;/url-pattern&gt;
   &lt;/servlet-mapping&gt;
&lt;/web-app&gt;</code></pre>
<p style="text-align: left;">Login.jsp:<br />
The JSP code is pretty straightforward. The call of Form POST to Servlet and use of c:out tag to display errorMsg from the servlet is shown in the below snippet.</p>
<pre class="language-markup"><code>&lt;form name="frmLogin" method="POST" action="servlet/LogonServlet"&gt;
 &lt;table border="1"&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td colspan="2"&gt;&lt;c:out value="${errorMsg}"/&gt; &lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
....</code></pre>
<p>Home.jsp<br />
The JSP is pretty straightforward. It uses the c:out exactly the same way as in Login.jsp to display the logged in username.</p>
<p>That completes our simple login application. You can test it by deploying the WAR file in Tomcat or any other favorite Application Server. The complete WAR along with the source code can be downloaded by clicking <a title="Simple Login App Source Code" href="sourcecode/SimpleLoginApp/SimpleLoginApp.war" target="_blank" rel="noopener noreferrer">here</a>.</p>
<p>Bugs are inevitable! There is a complaint that you can go the Home.jsp by directly typing the URL. Also, after you login and reach the Home.jsp, if you leave the session open for a long time and then refresh the username disappears. We leave the privilege of fixing the bug with you <img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> However, your approach would be to add a check in Home.jsp for session variable &#8220;userName&#8221;. If not available, redirect to Login.jsp. If you have any queries or need assistance, feel free to add your comments in the section below.</p>
<hr />
<p style="text-align: left;">Try similar article which extends to the login application and adds Registration functionality by clicking <a href="java/jsp-servlets/simple-registration-application.html" target="_blank" rel="noopener noreferrer">Simple Registration Application using JSP, Servlet and MySQL.</a></p>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 1824px; width: 1px; height: 1px; overflow: hidden;">
<p class="MsoNormal" style="text-align: left;"><strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #7f0055; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">private</span></strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"> Connection getConnection() </span><strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #7f0055; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">throws</span></strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"> Exception {</span></p>
<p class="MsoNormal" style="text-align: left;"><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><span style="mso-tab-count: 2;">Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚  </span>Connection conn = </span><strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #7f0055; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">null</span></strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">;</span></p>
<p class="MsoNormal" style="text-align: left;"><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><span style="mso-tab-count: 2;">Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚  </span></span><strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #7f0055; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">try</span></strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"> {</span></p>
<p class="MsoNormal" style="text-align: left;"><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><span style="mso-tab-count: 3;">Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚  </span>String url = </span><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #2a00ff; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">&#8220;jdbc:mysql://localhost/&#8221;</span><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">+</span><em><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #0000c0; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">DBNAME</span></em><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">+</span><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #2a00ff; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">&#8220;?user=&#8221;</span><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">+</span><em><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #0000c0; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">DB_USERNAME</span></em><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">+</span><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #2a00ff; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">&#8220;&amp;password=&#8221;</span><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">+</span><em><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #0000c0; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">DB_PASSWORD</span></em><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">;</span></p>
<p class="MsoNormal" style="text-align: left;"><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><span style="mso-tab-count: 3;">Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚  </span>Class.<em>forName</em>(</span><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #2a00ff; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">&#8220;com.mysql.jdbc.Driver&#8221;</span><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">);</span></p>
<p class="MsoNormal" style="text-align: left;"><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><span style="mso-tab-count: 3;">Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚  </span>conn = DriverManager.<em>getConnection</em>(url);</span></p>
<p class="MsoNormal" style="text-align: left;"><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><span style="mso-tab-count: 2;">Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚  </span>} </span><strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #7f0055; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">catch</span></strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"> (SQLException sqle) {</span></p>
<p class="MsoNormal" style="text-align: left;"><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><span style="mso-tab-count: 3;">Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚  </span>System.</span><em><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #0000c0; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">out</span></em><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">.println(</span><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #2a00ff; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">&#8220;SQLException: Unable to open connection to db: &#8220;</span><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">+sqle.getMessage());</span></p>
<p class="MsoNormal" style="text-align: left;"><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><span style="mso-tab-count: 3;">Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚  </span></span><strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #7f0055; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">throw</span></strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"> sqle;</span></p>
<p class="MsoNormal" style="text-align: left;"><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><span style="mso-tab-count: 2;">Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚  </span>} </span><strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #7f0055; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">catch</span></strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">(Exception e) {</span></p>
<p class="MsoNormal" style="text-align: left;"><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><span style="mso-tab-count: 3;">Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚  </span>System.</span><em><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #0000c0; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">out</span></em><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">.println(</span><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #2a00ff; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">&#8220;Exception: Unable to open connection to db: &#8220;</span><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">+e.getMessage());</span></p>
<p class="MsoNormal" style="text-align: left;"><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><span style="mso-tab-count: 3;">Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚  </span></span><strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #7f0055; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">throw</span></strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"> e;</span></p>
<p class="MsoNormal" style="text-align: left;"><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><span style="mso-tab-count: 2;">Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚  </span>}</span></p>
<p class="MsoNormal" style="text-align: left;"><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><span style="mso-tab-count: 2;">Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚ Ã‚  </span></span><strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: #7f0055; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">return</span></strong><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"> conn;</span></p>
<p class="MsoNormal" style="text-align: left;"><span style="font-size: 10.0pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; color: black; mso-font-kerning: 0pt; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><span style="mso-tab-count: 1;">Ã‚ Ã‚ Ã‚ Ã‚ Ã‚  </span>}</span></p>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.tech-freaks.com/java/jsp-servlets/simple-login-application.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Struts 1 Session Based Shopping Cart</title>
		<link>https://www.tech-freaks.com/java/jsp-servlets/struts1-shopping-cart.html</link>
					<comments>https://www.tech-freaks.com/java/jsp-servlets/struts1-shopping-cart.html#respond</comments>
		
		<dc:creator><![CDATA[Tech Programmer]]></dc:creator>
		<pubDate>Sun, 03 Jun 2012 13:27:56 +0000</pubDate>
				<category><![CDATA[JSP & Servlets]]></category>
		<guid isPermaLink="false">http://localhost/tfcom_wp/2012/06/03/struts1-shopping-cart/</guid>

					<description><![CDATA[Purpose The purpose of this workshop is to migrate the shopping cart which we created in Session Based Shopping Cart Article and [&#8230;]]]></description>
										<content:encoded><![CDATA[		<div class="wpulike wpulike-default " ><div class="wp_ulike_general_class wp_ulike_is_not_liked"><button type="button"
					aria-label="Like Button"
					data-ulike-id="59"
					data-ulike-nonce="1e31a06d4f"
					data-ulike-type="post"
					data-ulike-template="wpulike-default"
					data-ulike-display-likers=""
					data-ulike-likers-style="popover"
					class="wp_ulike_btn wp_ulike_put_image wp_post_btn_59"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0"></span>			</div></div>
	<p style="text-align: left;"><strong>Purpose</strong></p>
<p style="text-align: left;">The purpose of this workshop is to migrate the shopping cart which we created in <a href="java/jsp-servlets/shopping-cart.html" target="_blank" rel="noopener noreferrer">Session Based Shopping Cart Article</a> and use Struts 1 framework for MVC. The article is not intended to explain all struts features like localization, validation framework, error handling etc.</p>
<p style="text-align: left;"><strong>Prerequisites</strong></p>
<ul style="text-align: left;">
<li>Knowledge about struts1 application framework</li>
<li>This articles assume that a session based shopping cart is already developed as explained in <a href="java/jsp-servlets/shopping-cart.html" target="_blank" rel="noopener noreferrer">Session Based Shopping Cart Article</a> . All requirements are same as the previous article.</li>
</ul>
<p style="text-align: left;"><strong>Analysis and design</strong></p>
<p>Our analysis and design will not be as exhaustive as the previous session based shopping cart. We already have the components designed and responsibility assigned (Also have code available). We will use the previous components and review the changes required.</p>
<p>Based on the previous article below are the list of components:<br />
1. ModelList.jsp<br />
2. ShoppingCart.jsp<br />
3. CartBean.java<br />
4. CartItemBean.java<br />
5. CartController.java</p>
<p style="text-align: left;">We will move most of the logic from CartController which was a servlet and implement a Struts Action class instead. Hence, we create a new class CartAction which extends Action class.</p>
<p>If you look at the ModelList or ShoppingCart form(HTML Form), each form submits details of an Item or Model. ModelList has Add action on Item and ShoppingCart.jsp has Update and Delete action on Item. Based on this information, we can modify the CartItemBean into CartItemForm which extends Struts ActionForm class. Instance of the ActionForm will be provided as input to CartAction.</p>
<p>Hence, the revised list of components would look something like:<br />
1. ModelList.jsp<br />
2. ShoppingCart.jsp<br />
3. CartBean.java<br />
4. CartItemForm.java<br />
5. CartAction.java</p>
<p style="text-align: left;"><strong>Development environment structure:</strong></p>
<p>I prefer starting a struts 1 application by publishing the struts-blank application to Tomcat. The struts-blank application can be download from <a href="http://struts.apache.org/download.cgi#struts1310" target="_blank" rel="nofollow noopener noreferrer">Apache website</a>. The published struts-blank application provides a sample of struts-config.xml and all the required libraries to run a struts application.</p>
<p>However, at the end of the application we have provided a link to down the Web Archive (WAR) file of the whole StrutsShoppingCart application (with Source code).</p>
<p>StrutsShoppingCart<br />
&#8211; ModelList.jsp<br />
&#8211; ShoppingCart.jsp<br />
WEB-INF<br />
&#8211; struts-config.xml<br />
&#8211; web.xml<br />
src<br />
&#8211; in.techfreaks.struts.cart.bean.CartBean.java<br />
&#8211; in.techfreaks.struts.cart.form.CartItemForm.java<br />
&#8211; in.techfreaks.struts.cart.action.CartAction.java<br />
classes<br />
lib<br />
&#8211; jstl.jar<br />
-standard.jar<br />
&#8211; &lt;ALL Struts required Lib &gt;</p>
<hr class="system-pagebreak" title="Coding and Unit Testing" />
<p style="text-align: left;"><strong>Coding and Unit Testing:</strong></p>
<p>web.xml<br />
The deployment descriptor for the Web application. It has an entry for the struts ActionServlet which the generic Controller. It also maps all *.do extension through the ActionServlet. The struts-config.xml should be available in the path specified relative to the web application context.</p>
<pre class="language-markup"><code>&lt;web-app&gt;
   &lt;display-name&gt;Struts Shopping Cart Application&lt;/display-name&gt;

   &lt;!-- Standard Action Servlet Configuration --&gt;
   &lt;servlet&gt;
      &lt;servlet-name&gt;action&lt;/servlet-name&gt;
      &lt;servlet-class&gt;org.apache.struts.action.ActionServlet&lt;/servlet-class&gt;
      &lt;init-param&gt;
        &lt;param-name&gt;config&lt;/param-name&gt;
        &lt;param-value&gt;/WEB-INF/struts-config.xml&lt;/param-value&gt;
      &lt;/init-param&gt;
      &lt;load-on-startup&gt;2&lt;/load-on-startup&gt;
   &lt;/servlet&gt;

    &lt;!-- Standard Action Servlet Mapping --&gt;
    &lt;servlet-mapping&gt;
       &lt;servlet-name&gt;action&lt;/servlet-name&gt;
       &lt;url-pattern&gt;*.do&lt;/url-pattern&gt;
     &lt;/servlet-mapping&gt;

 &lt;/web-app&gt;</code></pre>
<p style="text-align: left;">struts-config.xml:</p>
<p>For our application we just need to declare the ActionForm and  add an ActionMapping.</p>
<pre class="language-markup"><code>&lt;form-beans&gt;
    &lt;form-bean
        name="CartItemForm"
                    type="in.techfreaks.struts.cart.form.CartItemForm"/&gt;
&lt;/form-beans&gt;

&lt;action-mappings&gt;
    &lt;action path="/Cart" type="in.techfreaks.struts.cart.action.CartAction" name="CartItemForm"&gt;
           &lt;forward name="success" path="/ShoppingCart.jsp" /&gt;
    &lt;/action&gt;
&lt;/action-mappings&gt;</code></pre>
<p>The action maps the Path to the Action class. It also has a forward to ShoppingCart.jsp on success. We do not have a failure forward but it would be required for a more robust production quality application. The ActionForm associated with the request is also provided. It maps to the ActionForm defined by the form-bean tag. The path when called from the JSP would call the Action class. Note that in the path which is in the action mapping, we do not have .do added but when we declare in the html form action, we would have the Cart.do.</p>
<p>CartAction :</p>
<p>The below code is excerpt from the CartAction class. The CartItemForm is passed in as a parameter to execute() method. Also, we moved the action into the CartItemForm. The CartItemForm is automatically populated by the Struts framework. We just need to make sure that the parameter name in the ActionForm is exactly same as the html form input fields in JSP.</p>
<pre class="language-java"><code>public class CartAction extends Action {

   public static final String ADD = "Add";
   public static final String DELETE = "Delete";
   public static final String UPDATE = "Update";

   public static final String CART_SESSION = "Cart";

   public ActionForward execute(ActionMapping mapping, ActionForm form,
           HttpServletRequest request, HttpServletResponse response) throws Exception {
        CartItemForm cartItemForm = (CartItemForm) form;
        String strAction = cartItemForm.getAction();
        if(strAction!=null &amp;&amp; !strAction.equals("")) {
          if(strAction.equals(ADD)) {
              addToCart(request, cartItemForm);
          } else if (strAction.equals(UPDATE)) {
              updateCart(request, cartItemForm);
          } else if (strAction.equals(DELETE)) {
              deleteCart(request, cartItemForm);
          }
   }

   return mapping.findForward("success");
}</code></pre>
<p style="text-align: left;">CartItemForm:</p>
<p>Below is an excerpt of CartItemForm. Note that we moved itemIndex and action fields into the CartItemForm and hence we do not used the request.getParameter() to fetch these values in Action class, like we did the previous version of the controller.</p>
<pre class="language-java"><code> public class CartItemForm extends ActionForm {
    private String strPartNumber;
    private String strModelDescription;
    private double dblUnitCost;
    private int iQuantity;
    private double dblTotalCost;
    private String action ;
    private String itemIndex ;
}
 </code></pre>
<pre class="brush:java" style="text-align: left;">ModelList.jsp and ShoppingCart.jsp:

The main change is calling the Action class instead of the Servlet. Below code explains how the Action class is called:

&lt;form name="modelDetail3" method="POST" action="Cart.do"&gt;

Apart from that the JSP needs to be modified to use the web 2.0 div structure and have external CSS applied. However, we would defer to you as a home work ;)</pre>
<p style="text-align: left;"><strong>Putting the cart to test:</strong><br />
We mainly want to test the below three functionalities:<br />
1. Add to cart<br />
2. Update the quantity<br />
3. Remove an item from cart</p>
<p>Start Tomcat and access URL http://localhost:8080/StrutsShoppingCart/ModelList.jsp to test the above functionality.</p>
<p>You can download the WAR file by clicking <a href="sourcecode/Struts1_ShoppingCart/StrutsShoppingCart.war">StrutsShoppingCart download</a> application link.</p>
<p style="text-align: left;">This WAR file can be directly deploy into Tomcat Web container. Adding the WAR to the webapps folder of Tomcat will automatically perform a Hot deployment.</p>
<p style="text-align: left;">This concludes the development of session based shopping cart using Struts 1 Framework.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.tech-freaks.com/java/jsp-servlets/struts1-shopping-cart.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Simple Hit Counter Servlet</title>
		<link>https://www.tech-freaks.com/java/jsp-servlets/hit-counter-servlet.html</link>
					<comments>https://www.tech-freaks.com/java/jsp-servlets/hit-counter-servlet.html#respond</comments>
		
		<dc:creator><![CDATA[Tech Programmer]]></dc:creator>
		<pubDate>Tue, 15 Sep 2009 22:22:43 +0000</pubDate>
				<category><![CDATA[JSP & Servlets]]></category>
		<guid isPermaLink="false">http://localhost/tfcom_wp/2009/09/15/hit-counter-servlet/</guid>

					<description><![CDATA[Problem Statement: Write a simple servlet which counts the total number of hits on itself and display it in the [&#8230;]]]></description>
										<content:encoded><![CDATA[		<div class="wpulike wpulike-default " ><div class="wp_ulike_general_class wp_ulike_is_not_liked"><button type="button"
					aria-label="Like Button"
					data-ulike-id="53"
					data-ulike-nonce="d5a5a8d0dd"
					data-ulike-type="post"
					data-ulike-template="wpulike-default"
					data-ulike-display-likers=""
					data-ulike-likers-style="popover"
					class="wp_ulike_btn wp_ulike_put_image wp_post_btn_53"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0"></span>			</div></div>
	<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">Problem Statement:</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">Write a simple servlet which counts the total number of hits on itself and display it in the web page.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;"></div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">Assumptions:</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">1.The web container will not be restarted. If it is restarted or servlet destroyed, the hit counter will be reset.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">2.The servlet is not loaded in a distributed environment.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;"></div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">We will be using this example to explain certain key concepts of servlet technology. We will also explain what will happen if the above assumption is not in place.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;"></div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">The below code shows a servlet which will display the number of hits on it.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;"></div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;"></div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">Below is the excerpt from web.xml which shows the servlet registration and servlet URL mapping.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;"></div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;"></div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">We should be able to access the servlet using the below URL:</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">http://localhost:8080/&lt;contextName&gt;/servlet/SimpleCounterServlet</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;"></div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">Everytime the above URL is access, the hit counter shows an incremented value. You may like to try by closing the browser window and accessing from a different browser window.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;"></div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">Key Servlet Concept:</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">We were able to achieve the counter functionality using a single instance variable. Why?</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">1.Only one instance of the servlet is created.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">2.Init() method is called only once. This explains the reason why the counter is not reset to 0 with every hit.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;"></div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">What will happen if the assumptions are removed?</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">1.If the web container is restarted, the old servlet instance will be destroyed. New servlet instance will be instantiated and init() will be called. Thus, we will lose the counter is the old servlet.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">2.In a distributed environment, there may be multiple JVMs. For each node in which the web container is distributed, a different servlet instance may be created. Hence, the instance variable approach will fail.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;"></div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">For fixing the first issue, we could modify the servlet code to persist the hitCounter into a database or file. The init() would be loading the hitCounter from the file/database.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;"></div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">For fixing the second issue, we need to stored the hitCounter variable somewhere else&#8230; well, that somewhere is &#8216;ApplicationScope&#8217;.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;"></div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden; text-align: left;">Try the above fixes as &#8216;Home Work&#8217;!</div>
<p style="text-align: left;"><strong>Problem Statement</strong></p>
<p style="text-align: left;">Write a simple servlet which counts the total number of hits on itself and display it in the web page.</p>
<p style="text-align: left;"><span class="Apple-style-span" style="font-weight: bold;">Assumptions</span></p>
<ul style="text-align: left;">
<li><span class="Apple-style-span" style="line-height: 15px;">The web container will not be restarted. If it is restarted or servlet destroyed, the hit counter will be reset.</span></li>
<li><span class="Apple-style-span" style="line-height: 15px;">The servlet is not loaded in a distributed environment.</span></li>
</ul>
<p style="text-align: left;">We will be using this example to explain certain key concepts of servlet technology. We will also explain what will happen if the above assumption is not in place.</p>
<p style="text-align: left;">The below code shows a servlet which will display the number of hits on it.</p>
<pre class="language-java"><code>package in.techfreaks.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SimpleCounterServlet extends HttpServlet {

	//Instance variable used for counting hits on this servlet
	private int iHitCounter;

	/**
	* init method just initializes the hitCounter to zero
	*/

	public void init() throws ServletException {
		iHitCounter = 0;
	}

	/**
	* Work horse of this servlet
	* Displays a welcome msg along with hitCounter
	* Increments the hitCounter
	*/

	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {

	PrintWriter out =  response.getWriter();
		out.println("&lt;h2&gt;Welcome to SimpleCounterServlet.java&lt;/h2&gt;");
		out.println("Hits on this servlet so far: "+ (++iHitCounter)); 
	}

	/**
	* Passes the call to doGet method. 
	* Thus, works similar to doGet
	*/

	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		doGet(request, response);
	}
}</code></pre>
<p style="text-align: left;">Below is the excerpt from web.xml which shows the servlet registration and servlet URL mapping.  </p>
<pre class="language-markup"><code>  ...
  &lt;servlet&gt;
    &lt;servlet-name&gt;SimpleCounterServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;in.techfreaks.servlet.SimpleCounterServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;
  ...
  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;SimpleCounterServlet&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/servlet/SimpleCounterServlet&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
  ....</code></pre>
<div style="text-align: left;">We should be able to access the servlet using the below URL:</div>
<p style="text-align: left;">http://localhost:8080/&lt;contextName&gt;/servlet/SimpleCounterServlet</p>
<p style="text-align: left;">Everytime the above URL is access, the hit counter shows an incremented value. You may like to try by closing the browser window and accessing from a different browser window.</p>
<p style="text-align: left;"><strong>Key Servlet Concept</strong></p>
<p style="text-align: left;">We were able to achieve the counter functionality using a single instance variable. Why?</p>
<ul style="text-align: left;">
<li><span class="Apple-style-span" style="line-height: 15px;">Only one instance of the servlet is created</span></li>
<li><span class="Apple-style-span" style="line-height: 15px;">init() method is called only once. This explains the reason why the counter is not reset to 0 with every hit</span></li>
</ul>
<p style="text-align: left;"><span class="Apple-style-span" style="font-weight: bold;">What will happen if the assumptions are removed?</span></p>
<ul style="text-align: left;">
<li><span class="Apple-style-span" style="line-height: 15px;">If the web container is restarted, the old servlet instance will be destroyed. New servlet instance will be instantiated and init() will be called. Thus, we will lose the counter is the old servlet.</span></li>
<li><span class="Apple-style-span" style="line-height: 15px;">In a distributed environment, there may be multiple JVMs. For each node in which the web container is distributed, a different servlet instance may be created. Hence, the instance variable approach will fail.</span></li>
</ul>
<p style="text-align: left;">For fixing the first issue, we could modify the servlet code to persist the hitCounter into a database or file. The init() would be loading the hitCounter from the file/database.</p>
<p style="text-align: left;">For fixing the second issue, we need to stored the hitCounter variable somewhere else&#8230; well, that somewhere is &#8216;ApplicationScope&#8217;.</p>
<p style="text-align: left;">Try the above two fixes for self study and post your solution in the comments below.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.tech-freaks.com/java/jsp-servlets/hit-counter-servlet.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Session Based Shopping Cart</title>
		<link>https://www.tech-freaks.com/java/jsp-servlets/session-shopping-cart.html</link>
					<comments>https://www.tech-freaks.com/java/jsp-servlets/session-shopping-cart.html#respond</comments>
		
		<dc:creator><![CDATA[Tech Programmer]]></dc:creator>
		<pubDate>Tue, 23 Sep 2008 22:29:30 +0000</pubDate>
				<category><![CDATA[JSP & Servlets]]></category>
		<guid isPermaLink="false">http://localhost/tfcom_wp/2008/09/23/shopping-cart/</guid>

					<description><![CDATA[This workshop is for you, if: You want to get hands on feel of JSP and Servlets in real life [&#8230;]]]></description>
										<content:encoded><![CDATA[		<div class="wpulike wpulike-default " ><div class="wp_ulike_general_class wp_ulike_is_not_liked"><button type="button"
					aria-label="Like Button"
					data-ulike-id="45"
					data-ulike-nonce="d5a8c93595"
					data-ulike-type="post"
					data-ulike-template="wpulike-default"
					data-ulike-display-likers=""
					data-ulike-likers-style="popover"
					class="wp_ulike_btn wp_ulike_put_image wp_post_btn_45"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0"></span>			</div></div>
	<p style="text-align: left;"><strong>This workshop is for you, if:</strong></p>
<ul style="text-align: left;">
<li>You want to get hands on feel of JSP and Servlets in real life scenarios</li>
<li>You are dying to write some code and see it work</li>
<li>You have heard enough about shopping carts and finally want to see what the heck, they are made of!</li>
</ul>
<p style="text-align: left;"><strong>This workshop is not for you, if:<br />
</strong></p>
<ul style="text-align: left;">
<li>You do not have any idea about JSP, Servlets or core Java</li>
<li>You are looking for a production quality or ready to use shopping cart</li>
</ul>
<p style="text-align: left;"><strong>Pre-requisites:</strong></p>
<ul style="text-align: left;">
<li>Knowledge of Java fundamentals and collection framework</li>
<li>JSP and servlet knowledge, especially, about session handling and JSTL</li>
<li>
<div align="justify">Setup of environment: Tomcat and IDE. Check article</div>
<div align="justify"><a href="java/jsp-servlets/eclipse-tomcat-integration.html" target="_blank" rel="noopener"><span style="text-decoration: underline;"><span style="color: #0000ff;">Eclipse Tomcat integration</span></span></a></div>
</li>
</ul>
<p><span id="more-45"></span></p>
<p style="text-align: left;"><strong>Requirement:</strong></p>
<ul style="text-align: left;">
<li>Create simple catalog page with hard coded list of models with an &#8220;Add to Cart&#8221; button.</li>
<li>The catalog model list page should contain a list of models with model number, description and price.</li>
<li>On clicking the &#8220;Add to Cart&#8221; button, the model should get added to the shopping cart.</li>
<li>The cart should display all the models added to it. For each line item, it should display model number, description and unit price of item and total price. It should also display the total price for the whole order.</li>
<li>For each item in the cart, there should be a delete button next to it for removing the item from cart.</li>
<li>For each item in the cart, there should be a text input to enter a quantity value with update button to update the quantity of item in the cart.</li>
<li>The cart should have a link back to catalog model list page.</li>
</ul>
<p style="text-align: left;"><strong>Shopping Cart overview:</strong></p>
<p style="text-align: left;">Shopping cart is the heart of any e-commerce application. It is something highly talked about. But, what do you mean by a session based shopping cart? Well, shopping carts can be mainly session based or database based. As the name indicates, session based carts are completely maintained in the user&#8221;s session. Only after the checkout is completed, the information is persisted in the database. On the other hand, a database based shopping cart is maintained in the database. Every time cart items are added or updated, it gets persisted in the database. Both of them have their own advantages and disadvantages. For each add or update in database based cart, there will be a hit in the database. On the other hand, it gives us the advantage of cart persistence. You can leave your shopping halfway and come back after sometime and resume the shopping session.</p>
<p style="text-align: left;"><strong>Analysis and Design:</strong></p>
<p>Designing the components prior to coding is pretty useful. Better the designing, easier it is to code and lesser the rework. We will be digging pretty deep into the design to throw light on some of the design principles. If you are not interested in designing and stuff, you may want to glance through the UML diagrams and move on to code.</p>
<p><em>Identifying components:</em><br />
Let us analyze the requirements, and try to identify the different components needed for this workshop. For our analysis, we try to identify components based on Model-View-Controller (MVC) design.</p>
<p>We need to create a ModelList page, with &#8220;Add to cart&#8221; button.</p>
<p>Technically speaking, what does a cart comprise? It is a collection of items added to the session. Let us use, ArrayList for our cart. So, the basic idea is to have an ArrayList added to session object.</p>
<p>We will refine this a bit. Going forward, we may need the cart item to hold other things than just CartItems. Something like Promotion code data. So, we will maintain a special cart object. And the cart will contain ArrayList of cart items.</p>
<p>But, what will the ArrayList comprise? String will not do for sure. Probably, we need a special item bean. Right, so we will have ItemBean added to ArrayList, and the ArrayList will be added to session. This sounds great!</p>
<p>We need a shopping cart jsp. It would need to pull ArrayList out of the session and iterate this, and display it in the JSP.</p>
<p>Aren&#8217;t we missing something? We need something to control the events coming from the &#8220;Add to cart&#8221;, &#8220;Update Item&#8221; and &#8220;Delete Item&#8221;. We need a rocking controller to handle these events. The servlet should be the one to do this job.</p>
<p>Based on the above analysis, let us summarize the components we had identified:<br />
1. ModelList.jsp<br />
2. ShoppingCart.jsp<br />
3. CartBean.java<br />
4. CartItemBean.java<br />
5. CartController.java</p>
<p><em>Identifying attributes for cart:</em><br />
Now, let us try to identify more information for the cart related classes.</p>
<p>CartBean:</p>
<ul style="text-align: left;">
<li>ArrayList of CartItemBean</li>
<li>totalCost of items in cart</li>
</ul>
<p style="text-align: left;">CartItemBean:</p>
<ul style="text-align: left;">
<li>Part number for the model</li>
<li>Model description</li>
<li>Unit cost</li>
<li>Quantity</li>
<li>Total item cost</li>
</ul>
<p style="text-align: left;"><em>Identifying methods:</em><br />
CartController:<br />
This servlet controller needs to implement the doGet/doPost methods. It needs to handle the events for addToCart, updateCart and deleteCart. It is a better design to handle each of these events separately. So, based on this discussion, the CartController will need to have the following methods:</p>
<ul style="text-align: left;">
<li>doGet/doPost &#8211; Delegates request to different event methods like addToCart etc.</li>
<li>addToCart &#8211; Handle the add to cart functionality</li>
<li>updateCart &#8211; Handle the update cart item functionality</li>
<li>deleteCart &#8211; Handle delete cart item from cart functionality</li>
</ul>
<p style="text-align: left;">Let us work through the &#8220;Calculate the cart total&#8221; and &#8220;Add to cart&#8221; functionality to analyze and come up with methods related to it.</p>
<p style="text-align: left;"><span style="text-decoration: underline;">Calculating the cart total:</span><br />
This is a major functionality, which needs to be utilized every time an item is added, removed or updated. Let us discuss considering different design principles and try to come up with a realization for this functionality.</p>
<p>Information expert principle says that, any object which has the information to perform an operation should do the job.<br />
For calculating the total price, we need to first know the total for each line item. So, let us apply expert principle to get the line item total. Since, CartItemBean has both quantity and unit cost, based on expert, it is the right candidate.</p>
<p>Just to understand the association between the different objects, we know, that CartBean houses a list of CartItemBean. The CartController on the other hand will be one to add the CartBean in session. Now, this means, CartBean is associated with CartItemBean and CartBean is associated also with CartController.</p>
<p>Coupling design principle says that, the association or coupling between different objects should be as less as possible. More the coupling, more spaghetti code syndrome. You make changes to code in one class; all the associated classes need changes.</p>
<p>Since CartController has access to CartBean, we can write a calculateTotal method in the CartController, where we will have to pull the list of CartItemBeans from CartBean in this method and calculate the total price. However, this means, iterating through the CartItemBean list in CartController and also calls on CartItemBean.getSubtotal(). This introduces CartItemBean to CartController coupling.</p>
<p>Hmmmm! Not that good news isn&#8217;t it?</p>
<p>But, do we have a choice? Going again by expert, CartBean does have access to all CartItemBeans. So, it is an expert to calculate the order total. Also, it does not have a CartItemBean to CartController coupling. So, this is a better choice.</p>
<p style="text-align: left;"><span style="text-decoration: underline;">Add to Cart functionality:</span></p>
<p style="text-align: left;">We said that CartBean will house an ArrayList of CartItemBeans. So, we will have a getter/setter for setting this ArrayList inside CartBean. But, who will create the ArrayList of CartItemBeans and then call setCartItems? It has to be CartController. This intern means, CartItemBean creation, setting values and adding to ArrayList, needs to be performed in CartController. HmmmÃ¢â‚¬¦.But, we have been working so hard eliminate the CartController to CartItemBean coupling while designing the &#8220;calculate order total&#8221; functionality. Even with this, creating the ArrayList of CartItemBeans and setting it in CartBean everytime is a tall order. We need something like addCartItem(CartItemBean) in CartBean. This will add to the ArrayList of CartItemBeans everytime this is called. So, the CartController does not have to worry above the ArrayList and setting the ArrayList using the setCartItem method. That is a great relief!!</p>
<p>Hey, hold on! But, when we still will call setters in CartItemBean from CartController and then call the CartBean.addCartItem(CartItemBean). Isn&#8221;t it not adding coupling between CartController and CartItemBean. Well, sad but true! Let us try to look for any some more options.</p>
<p>It would be dreamy, if CartBean can take complete control of the CartItemBean, without any CartController intervention.  Let us try to delegate the task of creating CartItemBean and setting values into it to CartBean. But, is it possible; is the question to be answered? How will the CartBean know, what should be the state of the CartItemBean created? Well, since the CartController has this information, it can pass on this information to CartBeans method as parameters. Like</p>
<ul style="text-align: left;">
<li>addCartItem(String strModelNo, String strDescription, String strUnitCost, String strQuantity)</li>
</ul>
<p style="text-align: left;">Passing 4 parameters in the method call may not be that bad! But, in a real production cart scenario, we may need more parameters. We can generally work around this by using a value object. But for our example this is fine.</p>
<p>Party time! We just designed the addToCart without increasing the coupling. Note here that, CartController is the information expert. The CartBean may be considered as a partial expert. However, we considered both coupling and expert to come up with this design. This leads us to something very important while using design principles. No single design principle can be used in isolation to design functionality. We need to consider different design principles to come up with a design.</p>
<p>We will use the same principle for updateCartItem and deleteCartItem functionality. You may want to think over it.</p>
<p>So, based on the above discussion, below the class diagram for our cart sub-system.</p>
<p><img loading="lazy" decoding="async" title="UML Class diagram for Shopping Cart" src="https://www.tech-freaks.com/wp-content/uploads/2008/09/cart_class_diagram.jpg" alt="UML Class diagram for Shopping Cart" width="513" height="465" border="0" /></p>
<p>Sequence diagram for Add To Cart:</p>
<p style="text-align: left;"><img loading="lazy" decoding="async" title="Add to cart - UML Sequence diagram" src="https://www.tech-freaks.com/wp-content/uploads/2008/09/add_to_cart_seq.jpg" alt="Add to cart - UML Sequence diagram" width="761" height="427" border="0" /></p>
<p style="text-align: left;"><strong>Setting up the environment for development:</strong></p>
<p style="text-align: left;">We will be using Tomcat 6.x for running and testing our shopping cart. Refer &#8220;First JSP/Servlet workshop&#8221; for Tomcat installation details.<br />
We will be developing using Eclipse 3.x integrated with Tomcat via Sysdeo plugin. Refer &#8220;Integration of Eclipse with Tomcat&#8221; article for details.</p>
<p>Let us create a new Tomcat Project, with context name as /ShoppingCart.<br />
Set the source path and build path correctly. We will need JSTL libraries (jstl.jar and standard.jar) as we will be using JSTL/EL for the shopping cart page.</p>
<p>We should be able to start Tomcat from Eclipse, and access the any JSP page inside /ShoppingCart context which we created using the URL http://localhost:8080/ShoppingCart/&lt;AnyFile.jsp&gt;</p>
<p>The following will be approximate directory structure of the ShoppingCart project.</p>
<pre class="code-style" style="text-align: left;">ShoppingCart
- ModelList.jsp
- ShoppingCart.jsp
     WEB-INF
        src
        - in.techfreaks.shoppingcart.beans.CartBean.java
        - in.techfreaks.shoppingcart.beans.CartItemBean.java
        - in.techfreaks.shoppingcart.servlet.CartController.java
        classes
        lib
        - jstl.jar
        -standard.jar</pre>
<p style="text-align: left;"><strong>Coding the Cart:</strong><br />
Such detailed design generally makes coding just a formality. Below is the code for each of the element identified during design. The code is pretty straight forward.</p>
<p>CartItemBean:</p>
<pre class="language-java"><code>package in.techfreaks.shoppingcart.beans;

public class CartItemBean {
    private String strPartNumber;
    private String strModelDescription;
    private double dblUnitCost;
    private int iQuantity;
    private double dblTotalCost;
    
    public String getPartNumber() {
        return strPartNumber;
    }
    public void setPartNumber(String strPartNumber) {
        this.strPartNumber = strPartNumber;
    }
    public String getModelDescription() {
        return strModelDescription;
    }
    public void setModelDescription(String strModelDescription) {
        this.strModelDescription = strModelDescription;
    }
    public double getUnitCost() {
        return dblUnitCost;
    }
    public void setUnitCost(double dblUnitCost) {
        this.dblUnitCost = dblUnitCost;
    }
    public int getQuantity() {
        return iQuantity;
    }
    public void setQuantity(int quantity) {
        iQuantity = quantity;
    }
    public double getTotalCost() {
        return dblTotalCost;
    }
    public void setTotalCost(double dblTotalCost) {
        this.dblTotalCost = dblTotalCost;
    }
}</code></pre>
<p style="text-align: left;">CartBean:</p>
<pre class="language-java"><code> package in.techfreaks.shoppingcart.beans;

import java.util.ArrayList;


public class CartBean {
 private ArrayList alCartItems = new ArrayList();
 private double dblOrderTotal ;
 
 public int getLineItemCount() {
  return alCartItems.size();
 }
 
 public void deleteCartItem(String strItemIndex) {
  int iItemIndex = 0;
  try {
   iItemIndex = Integer.parseInt(strItemIndex);
   alCartItems.remove(iItemIndex - 1);
   calculateOrderTotal();
  } catch(NumberFormatException nfe) {
   System.out.println("Error while deleting cart item: "+nfe.getMessage());
   nfe.printStackTrace();
  }
 }
 
 public void updateCartItem(String strItemIndex, String strQuantity) {
  double dblTotalCost = 0.0;
  double dblUnitCost = 0.0;
  int iQuantity = 0;
  int iItemIndex = 0;
  CartItemBean cartItem = null;
  try {
   iItemIndex = Integer.parseInt(strItemIndex);
   iQuantity = Integer.parseInt(strQuantity);
   if(iQuantity&gt;0) {
    cartItem = (CartItemBean)alCartItems.get(iItemIndex-1);
    dblUnitCost = cartItem.getUnitCost();
    dblTotalCost = dblUnitCost*iQuantity;
    cartItem.setQuantity(iQuantity);
    cartItem.setTotalCost(dblTotalCost);
    calculateOrderTotal();
   }
  } catch (NumberFormatException nfe) {
   System.out.println("Error while updating cart: "+nfe.getMessage());
   nfe.printStackTrace();
  }
  
 }
 
 public void addCartItem(String strModelNo, String strDescription,
String strUnitCost, String strQuantity) {
  double dblTotalCost = 0.0;
  double dblUnitCost = 0.0;
  int iQuantity = 0;
  CartItemBean cartItem = new CartItemBean();
  try {
   dblUnitCost = Double.parseDouble(strUnitCost);
   iQuantity = Integer.parseInt(strQuantity);
   if(iQuantity&gt;0) {
    dblTotalCost = dblUnitCost*iQuantity;
    cartItem.setPartNumber(strModelNo);
    cartItem.setModelDescription(strDescription);
    cartItem.setUnitCost(dblUnitCost);
    cartItem.setQuantity(iQuantity);
    cartItem.setTotalCost(dblTotalCost);
    alCartItems.add(cartItem);
    calculateOrderTotal();
   }
   
  } catch (NumberFormatException nfe) {
   System.out.println("Error while parsing from String to primitive types: "+nfe.getMessage());
   nfe.printStackTrace();
  }
 }
 
 public void addCartItem(CartItemBean cartItem) {
  alCartItems.add(cartItem);
 }
 
 public CartItemBean getCartItem(int iItemIndex) {
  CartItemBean cartItem = null;
  if(alCartItems.size()&gt;iItemIndex) {
   cartItem = (CartItemBean) alCartItems.get(iItemIndex);
  }
  return cartItem;
 }
 
 public ArrayList getCartItems() {
  return alCartItems;
 }
 public void setCartItems(ArrayList alCartItems) {
  this.alCartItems = alCartItems;
 }
 public double getOrderTotal() {
  return dblOrderTotal;
 }
 public void setOrderTotal(double dblOrderTotal) {
  this.dblOrderTotal = dblOrderTotal;
 }
 
 protected void calculateOrderTotal() {
  double dblTotal = 0;
  for(int counter=0;counter&lt;alCartItems.size();counter++) {
   CartItemBean cartItem = (CartItemBean) alCartItems.get(counter);
   dblTotal+=cartItem.getTotalCost();
   
  }
  setOrderTotal(dblTotal);
 }

}
 </code></pre>
<p style="text-align: left;">CartController:</p>
<pre class="language-java"><code>package in.techfreaks.shoppingcart.servlet;

import in.techfreaks.shoppingcart.beans.CartBean;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CartController extends HttpServlet {
 
 //public static final String addToCart
 
 public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

  String strAction = request.getParameter("action");
  
  
  if(strAction!=null &amp;&amp; !strAction.equals("")) {
   if(strAction.equals("add")) {
    addToCart(request);
   } else if (strAction.equals("Update")) {
    updateCart(request);
   } else if (strAction.equals("Delete")) {
    deleteCart(request);
   }
  }
  response.sendRedirect("../ShoppingCart.jsp");
 }
 
 protected void deleteCart(HttpServletRequest request) {
  HttpSession session = request.getSession();
  String strItemIndex = request.getParameter("itemIndex");
  CartBean cartBean = null;
  
  Object objCartBean = session.getAttribute("cart");
  if(objCartBean!=null) {
   cartBean = (CartBean) objCartBean ;
  } else {
   cartBean = new CartBean();
  }
  cartBean.deleteCartItem(strItemIndex);
 }
 
 protected void updateCart(HttpServletRequest request) {
  HttpSession session = request.getSession();
  String strQuantity = request.getParameter("quantity");
  String strItemIndex = request.getParameter("itemIndex");
 
  CartBean cartBean = null;
  
  Object objCartBean = session.getAttribute("cart");
  if(objCartBean!=null) {
   cartBean = (CartBean) objCartBean ;
  } else {
   cartBean = new CartBean();
  }
  cartBean.updateCartItem(strItemIndex, strQuantity);
 }
 
 protected void addToCart(HttpServletRequest request) {
  HttpSession session = request.getSession();
  String strModelNo = request.getParameter("modelNo");
  String strDescription = request.getParameter("description");
  String strPrice = request.getParameter("price");
  String strQuantity = request.getParameter("quantity");
  
  CartBean cartBean = null;
  
  Object objCartBean = session.getAttribute("cart");

  if(objCartBean!=null) {
   cartBean = (CartBean) objCartBean ;
  } else {
   cartBean = new CartBean();
   session.setAttribute("cart", cartBean);
  }
  
  cartBean.addCartItem(strModelNo, strDescription, strPrice, strQuantity);
 }

}</code></pre>
<dl id="tf-message">
<dt class="error"></dt>
<dd class="message message fade">
<ul>
<li>Do not ever maintain any state in servlet&#8221;s instance variables. You may find mixing of data between requests or user sessions. The best part of this is that, it will only happen in a production environment and you win a severity 1 ticket and that too completely free!</li>
</ul>
</dd>
</dl>
<p style="text-align: left;"> ModelList.jsp</p>
<pre class="language-markup"><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;www.tech-freaks.in - Model List&lt;/title&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;p&gt;&lt;font size="3" face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;strong&gt;Model List
  &lt;/strong&gt;&lt;/font&gt;&lt;/p&gt;
&lt;a href="ShoppingCart.jsp" mce_href="ShoppingCart.jsp"&gt;View Cart&lt;/a&gt;
&lt;p/&gt;    
&lt;table width="75%" border="1"&gt;
  &lt;tr&gt;
    &lt;td&gt;&lt;form name="modelDetail1" method="POST" action="servlet/CartController"&gt;
 &lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;strong&gt;Model:&lt;/strong&gt;
        TF-Model1&lt;/font&gt;&lt;input type="hidden" name="modelNo" value="TF-MODEL1"&gt;
      &lt;p&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;strong&gt;Description:&lt;/strong&gt;
        Tech-Freaks imaginary model 1. &lt;/font&gt;&lt;input type="hidden" name="description" value="Tech-Freaks imaginary model 1."&gt;&lt;/p&gt;
      &lt;p&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;strong&gt;Quantity:&lt;input type="text" size="2" value="1" name="quantity"&gt;&lt;/strong&gt;&lt;/font&gt;&lt;/p&gt;
      &lt;p&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;strong&gt;Price:&lt;/strong&gt;
        $10.00&lt;/font&gt;&lt;input type="hidden" name="price" value="10"&gt;&lt;/p&gt;&lt;input type="hidden" name="action" value="add"&gt;&lt;input type="submit" name="addToCart" value="Add To Cart"&gt;
      &lt;/form&gt;&lt;/td&gt;
    &lt;td&gt;&lt;form name="modelDetail2" method="POST" action="servlet/CartController"&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;strong&gt;Model&lt;/strong&gt;:
      TF-Model2 &lt;/font&gt;&lt;input type="hidden" name="modelNo" value="TF-MODEL2"&gt;
&lt;font face="Verdana, Arial, Helvetica, sans-serif"&gt;
      &lt;p&gt;&lt;font size="2"&gt;&lt;strong&gt;Description&lt;/strong&gt;: Tech-Freaks imaginary model
        2. &lt;/font&gt;&lt;input type="hidden" name="description" value="Tech-Freaks imaginary model 2."&gt;&lt;/p&gt;
      &lt;p&gt;&lt;font size="2"&gt;&lt;strong&gt;Quantity&lt;/strong&gt;: &lt;input type="text" size="2" value="1" name="quantity"&gt;&lt;/font&gt;&lt;/p&gt;
      &lt;p&gt;&lt;font size="2"&gt;&lt;strong&gt;Price&lt;/strong&gt;: $20.00&lt;input type="hidden" name="price" value="20"&gt;&lt;/font&gt;&lt;/p&gt;
           &lt;input type="hidden" name="action" value="add"&gt;
             &lt;input type="submit" name="addToCart" value="Add To Cart"&gt;
      &lt;/font&gt;&lt;/form&gt;&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;&lt;form name="modelDetail3" method="POST" action="servlet/CartController"&gt;&lt;p&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;strong&gt;Model:&lt;/strong&gt;
        TF-Model3&lt;/font&gt;&lt;input type="hidden" name="modelNo" value="TF-MODEL3"&gt;&lt;/p&gt;
      &lt;p&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;strong&gt;Description:&lt;/strong&gt;
        Tech-Freaks imaginary model 3. &lt;/font&gt;&lt;input type="hidden" name="description" value="Tech-Freaks imaginary model 3."&gt;&lt;/p&gt;
      &lt;p&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;strong&gt;Quantity:&lt;/strong&gt;&lt;/font&gt; &lt;input type="text" size="2" value="1" name="quantity"&gt;&lt;/p&gt;
      &lt;p&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;strong&gt;Price: $30.00&lt;/strong&gt;&lt;/font&gt;&lt;input type="hidden" name="price" value="30"&gt;&lt;/p&gt;        &lt;input type="hidden" name="action" value="add"&gt;
        &lt;input type="submit" name="addToCart" value="Add To Cart"&gt;
&lt;/form&gt;&lt;/td&gt;
    &lt;td&gt;&lt;form name="modelDetail4" method="POST" action="servlet/CartController"&gt;&lt;p&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;strong&gt;Model&lt;/strong&gt;:
        TF-Model4&lt;/font&gt;&lt;input type="hidden" name="modelNo" value="TF-MODEL4"&gt;&lt;/p&gt;
      &lt;p&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;strong&gt;Description&lt;/strong&gt;:
        Tech-Freaks imaginary model 4. &lt;/font&gt;&lt;input type="hidden" name="description" value="Tech-Freaks imaginary model 4."&gt;&lt;/p&gt;
      &lt;p&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;strong&gt;Quantity&lt;/strong&gt;:&lt;/font&gt; &lt;input type="text" size="2" value="1" name="quantity"&gt;&lt;/p&gt;
      &lt;p&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;strong&gt;Price&lt;/strong&gt;: $40.00&lt;/font&gt;&lt;input type="hidden" name="price" value="40"&gt;&lt;/p&gt;
   &lt;input type="hidden" name="action" value="add"&gt;&lt;input type="submit" name="addToCart" value="Add To Cart"&gt;&lt;/form&gt;&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt; &lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre>
<p style="text-align: left;">ShoppingCart.jsp</p>
<p style="text-align: left;">For iterating the elements in the cart session, we are using simple JSTL tags with EL.</p>
<pre class="language-markup"><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;www.tech-freaks.in - Shopping Cart&lt;/title&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %&gt;
&lt;p&gt;&lt;font face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;strong&gt;Shopping Cart&lt;/strong&gt;&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="ModelList.jsp" mce_href="ModelList.jsp"&gt;Model List&lt;/a&gt; &lt;/p&gt;
&lt;table width="75%" border="1"&gt;
  &lt;tr bgcolor="#CCCCCC"&gt;
    &lt;td&gt;&lt;strong&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;Model
      Description&lt;/font&gt;&lt;/strong&gt;&lt;/td&gt;
    &lt;td&gt;&lt;strong&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;Quantity&lt;/font&gt;&lt;/strong&gt;&lt;/td&gt;
    &lt;td&gt;&lt;strong&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;Unit
      Price&lt;/font&gt;&lt;/strong&gt;&lt;/td&gt;
    &lt;td&gt;&lt;strong&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;Total&lt;/font&gt;&lt;/strong&gt;&lt;/td&gt;
  &lt;/tr&gt;
  &lt;jsp:useBean id="cart" scope="session" class="in.techfreaks.shoppingcart.beans.CartBean" /&gt;
  &lt;c:if test="${cart.lineItemCount==0}"&gt;
  &lt;tr&gt;
  &lt;td colspan="4"&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;- Cart is currently empty -&lt;br/&gt;
  &lt;/tr&gt;
  &lt;/c:if&gt;
  &lt;c:forEach var="cartItem" items="${cart.cartItems}" varStatus="counter"&gt;
  &lt;form name="item" method="POST" action="servlet/CartController"&gt;
  &lt;tr&gt;
    &lt;td&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;b&gt;&lt;c:out value="${cartItem.partNumber}"/&gt;&lt;/b&gt;&lt;br/&gt;
      &lt;c:out value="${cartItem.modelDescription}"/&gt;&lt;/font&gt;&lt;/td&gt;
    &lt;td&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;&lt;input type='hidden' name='itemIndex' value='&lt;c:out value="${counter.count}"/&gt;'&gt;&lt;input type='text' name="quantity" value='&lt;c:out value="${cartItem.quantity}"/&gt;' size='2'&gt; &lt;input type="submit" name="action" value="Update"&gt;
 &lt;br/&gt;         &lt;input type="submit" name="action" value="Delete"&gt;&lt;/font&gt;&lt;/td&gt;
    &lt;td&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;</code></pre>
<pre></pre>
<pre class="language-markup"><code>lt;c:out value="${cartItem.unitCost}"/&gt;&lt;/font&gt;&lt;/td&gt; &lt;td&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;</code></pre>
<pre></pre>
<pre class="language-markup"><code>lt;c:out value="${cartItem.totalCost}"/&gt;&lt;/font&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/form&gt; &lt;/c:forEach&gt; &lt;tr&gt; &lt;td colspan="2"&gt; &lt;/td&gt; &lt;td&gt; &lt;/td&gt; &lt;td&gt;&lt;font size="2" face="Verdana, Arial, Helvetica, sans-serif"&gt;Subtotal:</code></pre>
<pre></pre>
<pre class="language-markup"><code>lt;c:out value="${cart.orderTotal}"/&gt;&lt;/font&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt;</code></pre>
<p style="text-align: left;">web.xml</p>
<pre class="language-markup"><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;
&lt;web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"&gt;

  &lt;display-name&gt;Shopping Cart&lt;/display-name&gt;
  &lt;description&gt;
    Simple Shopping Cart
  &lt;/description&gt;

  &lt;servlet&gt;
    &lt;servlet-name&gt;CartController&lt;/servlet-name&gt;
    &lt;servlet-class&gt;in.techfreaks.shoppingcart.servlet.CartController&lt;/servlet-class&gt;
  &lt;/servlet&gt;

  &lt;!-- Define the Manager Servlet Mapping --&gt;
  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;CartController&lt;/servlet-name&gt;
      &lt;url-pattern&gt;/servlet/*&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;

&lt;/web-app&gt;</code></pre>
<p style="text-align: left;"><strong>Putting the cart to test:</strong><br />
We mainly want to test the below three functionalities:<br />
1. Add to cart<br />
2. Update the quantity<br />
3. Remove an item from cart</p>
<p>Start Tomcat from Eclipse and access URL http://localhost:8080/ShoppingCart/ModelList.jsp to test the above functionality.</p>
<p><strong>Change requests:</strong><br />
Change is the essence of life! Same happens to business requirements and code. This means, that a &#8220;hardly working&#8221; developer has to become &#8220;hardworking&#8221;. So, we would like you to be the &#8220;hardworking&#8221; programmer to add the below functionality in this existing cart.<br />
1. Currently, if the same item is again added to cart, a new line item is added. Modify this in such a way that, if the same item is added again, the existing item&#8217;s quantity should be incremented by one. All other state of the cart/cart items should be adjusted accordingly.<br />
2. In the cart page, provide a new text box for redeeming promotion codes. The discount of 5% should be provided on the order total, when any of the promotion code from a list of pre-defined codes is used.</p>
<p>Feel free to write to us at programmer@tech-freaks.com for any queries regarding this change request.</p>
<p>Enjoy! Coding and rock n roll, always rulz!</p>
<p style="text-align: left;"><span style="font-size: medium;"><strong>UPDATE:</strong> Checkout our latest article on Session Based <a href="java/jsp-servlets/struts1-shopping-cart.html" target="_blank" rel="noopener noreferrer">Shopping Cart using Struts 1 Framework</a>.</span></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.tech-freaks.com/java/jsp-servlets/session-shopping-cart.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Integrating Eclipse with Tomcat</title>
		<link>https://www.tech-freaks.com/java/jsp-servlets/eclipse-tomcat-integration.html</link>
					<comments>https://www.tech-freaks.com/java/jsp-servlets/eclipse-tomcat-integration.html#respond</comments>
		
		<dc:creator><![CDATA[Tech Programmer]]></dc:creator>
		<pubDate>Sun, 10 Aug 2008 00:21:23 +0000</pubDate>
				<category><![CDATA[JSP & Servlets]]></category>
		<guid isPermaLink="false">http://localhost/tfcom_wp/2008/08/10/eclipse-tomcat-integration/</guid>

					<description><![CDATA[This workshop is for you, if: You are looking to use an IDE for writing your JSP and Servlet code [&#8230;]]]></description>
										<content:encoded><![CDATA[		<div class="wpulike wpulike-default " ><div class="wp_ulike_general_class wp_ulike_is_not_liked"><button type="button"
					aria-label="Like Button"
					data-ulike-id="58"
					data-ulike-nonce="a7d34ddf51"
					data-ulike-type="post"
					data-ulike-template="wpulike-default"
					data-ulike-display-likers=""
					data-ulike-likers-style="popover"
					class="wp_ulike_btn wp_ulike_put_image wp_post_btn_58"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0"></span>			</div></div>
	<p style="text-align: left;"><strong>This workshop is for you, if:</strong></p>
<ul style="text-align: left;">
<li>You are looking to use an IDE for writing your JSP and Servlet code</li>
<li>You are trying to figure out, how to integrate your Eclipse IDE with Tomcat</li>
</ul>
<p style="text-align: left;"><strong>This workshop is not for you, if:</strong></p>
<ul style="text-align: left;">
<li>You do not have any clue what JSP or Servlet is and you are trying to understand it</li>
</ul>
<p style="text-align: left;"><strong>Introduction:</strong></p>
<p style="text-align: left;">Writing endless JSP/Servlet code using Notepad, compiling it from command line and then deploying them in Tomcat can be a tedious job. Using an IDE like Eclipse for web development, does make life easy. It takes up the work of finding compilation errors before even you start to compile, which is a big relief. Also, no need to go back to the command line&#8230; set the CLASSPATH for each new library which you want to use. But, won&#8217;t it be an icing on the cake, if we could just write the code compile it and test it, without deploying the compiled file to Tomcat server, for every change we do to the file?</p>
<p dir="ltr" style="text-align: left;">Yes, that will be awesome! This is what we are trying to do in the workshop. Have our work environment configured such that, we will just make changes, compile it and test in browser without having to worry about deploying etc again and again.</p>
<p style="text-align: left;"> </p>
<p style="text-align: left;"><strong>Software requirement:</strong></p>
<p style="text-align: left;">For this workshop the below mentioned versions of the software will be necessary. It may be possible to work with a different version, as long as the versions of different softwares are compatible with each other.</p>
<ul style="text-align: left;">
<li>J2SE 1.5 or above</li>
<li>Eclipse 3.4 &#8211; It can be download and installed from <a href="http://www.eclipse.org/downloads/" target="_blank" rel="nofollow noopener noreferrer">Eclipse website</a></li>
<li>Tomcat 6.x &#8211; Download and install from <a href="http://tomcat.apache.org/" target="_blank" rel="nofollow noopener noreferrer">Apache website</a></li>
<li>Sysdeo Eclipse Tomcat Launcher plugin &#8211; Download the latest version of Sysdeo Eclipse Tomcat Launcher plugin from the <a href="http://www.eclipsetotale.com/tomcatPlugin.html" target="_blank" rel="nofollow noopener noreferrer">Eclipsetotale website</a></li>
</ul>
<p style="text-align: left;"> </p>
<p style="text-align: left;"><strong>Installing Tomcat and Eclipse:</strong></p>
<ul style="text-align: left;">
<li>Refer article <a href="java-basics/java-hello-world-eclipse.html" target="_blank" rel="nofollow noopener noreferrer">Java Hello World using Eclipse</a> for details regarding installing and setting up Eclipse</li>
<li>Refer article <a href="jsp-servlets/jsp-servlet-workshop.html" target="_blank" rel="nofollow noopener noreferrer">First JSP/Servlet Workshop</a> for details regarding installing and setting up Tomcat</li>
</ul>
<p style="text-align: left;"> </p>
<p style="text-align: left;"><strong>Integrating Tomcat with Eclipse using Tomcat Launcher Plugin</strong></p>
<p style="text-align: left;">Let us see, how we can bell the Tomcat within the Eclipse environment</p>
<ul style="text-align: left;">
<li>First, let us unzip the downloaded Sysdeo Tomcat plugin and extract to the location &lt;Eclipse Installation Directory&gt;/dropins folder.</li>
</ul>
<dl id="tf-message">
<dt class="error"></dt>
<dd class="message message fade">
<ul>
<li>For Eclipse version 3.1, 3.2 and 3.3 you need to extract the plugin zip contents to &lt;Eclipse Installation Directory&gt;/plugins folder </li>
</ul>
</dd>
</dl>
<ul style="text-align: left;">
<li>
<div>Restart Eclipse if it already open.</div>
</li>
<li>
<div>You will see three tomcat icon on the eclipse toolbar. Tomcat start, Tomcat stop and Tomcat restart. Yippie!! Let us try starting Tomcat. It looks like eclipse was unable to locate certain information for Tomcat. The error message reads, &#8220;Tomcat settings should be set in Tomcat Preference Page&#8221;.</div>
</li>
</ul>
<p style="text-align: left;"> </p>
<p style="text-align: left;">          <img decoding="async" src="https://www.tech-freaks.com/wp-content/uploads/2008/08/eclipse_preference.jpg" alt="Eclipse Tomcat Preference page" border="0"></p>
<p style="text-align: left;"> </p>
<ul style="text-align: left;">
<li> So, let us check this preference page. From the top menu, select Windows &#8211;&gt; Preference (See image above).</li>
<li>We need to set the correct values here:<br />Select Version 6.x<br />Browse and Select Tomcat Home<br />Other information will get automatically populated</li>
<li>In this window, there are other tabs like Advanced, JVM settings, Source Path etc under Tomcat tree expand icon. You may want to verify the JVM settings. Ensure that the JRE is set to 1.5 or above. Once done, just click Ok to save and exit that window.</li>
<li>Now, click the Tomcat start button and you should be able to startup logs in the console. </li>
<li>Let check, if Tomcat is working now. In the web browser, type http://localhost:8080/<br />You should be able to see Tomcat standing proudly!</li>
</ul>
<p style="text-align: left;">Well, we are done! But, let us try a simple web context, a servlet and a JSP, all using Eclipse.</p>
<p style="text-align: left;"> </p>
<p style="text-align: left;"><strong>Simple web app using Eclipse:</strong></p>
<ul style="text-align: left;">
<li>We need to create a new project in Eclipse. From the menu, we need to select File &#8211;&gt; New &#8211;&gt; Project</li>
</ul>
<p style="text-align: left;">            <img decoding="async" title="Eclipse - New Tomcat Project wizard page 1" src="https://www.tech-freaks.com/wp-content/uploads/2008/08/new_proj_wizard1.JPG" alt="Eclipse - New Tomcat Project wizard page 1" border="0"></p>
<p style="text-align: left;"> </p>
<ul style="text-align: left;">
<li>In the new project window, expand the Java section and you will be able to see Tomcat Project (See image above). Select it and click Next.</li>
</ul>
<p style="text-align: left;"> </p>
<p style="text-align: left;">            <img decoding="async" title="Eclipse - New Tomcat Project wizard page 1" src="https://www.tech-freaks.com/wp-content/uploads/2008/08/new_proj_wizard2.JPG" alt="Eclipse - New Tomcat Project wizard page 2" border="0"> </p>
<p style="text-align: left;"> </p>
<ul style="text-align: left;">
<li>In the Java Project settings, provide a Project Name. You can also override the location where you want the project files to be present (see image above). Click Next when done.</li>
</ul>
<p style="text-align: left;"> </p>
<p style="text-align: left;">            <img decoding="async" title="Eclipse - New Tomcat Project wizard page 3" src="https://www.tech-freaks.com/wp-content/uploads/2008/08/new_proj_wizard3.JPG" alt="Eclipse - New Tomcat Project wizard page 3" border="0"> </p>
<p style="text-align: left;"> </p>
<ul style="text-align: left;">
<li>In this step, you will have to provide a context name. This is the same context name by which the web application will be created in Tomcat. You can verify this from the manager console later. So, provide a context name and move ahead. Do not forget to put a slash (/) before the context name (see image above). We are done! Let us click finish.</li>
<li>You will notice that, the creation of the project itself creates most of the directories and files needed.</li>
<li>Let us now verify, if build path and libraries are present for compiling our servlet.</li>
<li>We can get the details in the Project Properties window and Java Build Path section<br />Source tab:<br />The Default output folder should be &lt;ContextRoot&gt;/WEB-INF/classes folder. This means, all compiled classes will be added to this folder.<br />The Source folder on build path, should have the folder listed where you are planning to have your Java source files. &lt; ContextRoot &gt;/WEB-INF/src will be the folder by default.<br />Library tab:<br />We will have to add any external libraries which we are planning to use in our web application. You will see, servlet-api.jar already listed there. This means, we are good to compile our simple servlet.</li>
</ul>
<blockquote>
<p>The only missing thing for the web application is the heart! The web.xml! It would have been great, if the web.xml was added automatically, however, it does not happen. We will have to manually create the web.xml and add it under WEB-INF folder.</p>
</blockquote>
<ul style="text-align: left;">
<li>So, let us create the JSP, Servlet and web.xml file using Eclipse:</li>
</ul>
<blockquote>
<p>JSP: We will create the MyFirstJspPage.jsp and place it under &lt;ContextRoot&gt;/ folder</p>
<pre class="language-markup"><code>&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;First JSP&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;div id="error" style="display:block;"&gt;&lt;font color="red"&gt;
    &lt;%if(request.getAttribute("errMsg")!=null) { out.println(request.getAttribute("errMsg"));} %&gt;
  &lt;/font&gt;&lt;/div&gt;
  &lt;form name="form" action="servlet/MyFirstServlet"&gt;
  First Name: &lt;input type="text" name="firstName" &gt;&lt;br&gt;
  Last Name: &lt;input type="text" name="lastName" &gt;&lt;br&gt;&lt;br&gt;
  &lt;input type="submit" name="submit" value="Submit" &gt;
  &lt;/form&gt;
  &lt;/body&gt;
&lt;/html&gt;</code></pre>
<p>Servlet: We will create the MyFirstServlet.java under &lt;ContextRoot&gt;/WEB-INF/src/. Ofcourse, under appropriate package structure in.techfreaks.servlet.</p>
<pre class="language-java"><code>package in.techfreaks.servlet;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;

public class MyFirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
 String strErrMsg = "Please enter first name and last name";
 String strFirstName = request.getParameter("firstName");
 String strLastName = request.getParameter("lastName");
 if(strFirstName!=null &amp;&amp; !strFirstName.equals("") &amp;&amp; strLastName!=null &amp;&amp; !strLastName.equals("")) {
  PrintWriter out = response.getWriter();
  out.println("Name : "+strFirstName+" "+strLastName);
  } else {
   request.setAttribute("errMsg", strErrMsg);
   request.getRequestDispatcher("../MyFirstJspPage.jsp").forward(request, response);
  }
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
  doPost(request, response);
 }
}</code></pre>
<p>web.xml: We will create the web.xml under &lt;ContextRoot&gt;/WEB-INF/</p>
<pre class="language-markup"><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;
&lt;web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation=http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"&gt;
 &lt;display-name&gt;Simple WebApp&lt;/display-name&gt;
  &lt;description&gt;
    Simple Web Application
  &lt;/description&gt;  &lt;servlet&gt;
    &lt;servlet-name&gt;MyFirstServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;in.techfreaks.servlet.MyFirstServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;  &lt;!-- Define the Manager Servlet Mapping --&gt;
  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;MyFirstServlet&lt;/servlet-name&gt;
      &lt;url-pattern&gt;/servlet/*&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
&lt;/web-app&gt;</code></pre>
<p> </p>
</blockquote>
<p style="text-align: left;">After you write the servlet, without compilation error and save, if you peep in the file system, you will find the class file automatically compiled at &lt;ContextRoot&gt;/WEB-INF/classes.</p>
<p style="text-align: left;">Restart Tomcat from Eclipse and we are all ready!</p>
<p style="text-align: left;"><strong>Testing:</strong></p>
<p style="text-align: left;">We are not testing the complete logic of the servlet here. We will just test to see, if the servlet and JSP are getting called, as expected.</p>
<p style="text-align: left;">http://localhost:8080/FirstJspServlet/MyFirstJspPage.jsp</p>
<p style="text-align: left;">The JSP file with first name and last name input should open.<br />Enter first name and last name and click enter, it should display the name in the next page, which is our servlet.</p>
<p style="text-align: left;">We are all set now for doing bigger things, using Eclipse IDE! So, sit backâ‚¬¦. get a cup of coffeeâ‚¬¦ and enjoy writing your JSP and servlet code!</p>
<blockquote>
<p style="text-align: left;">Check the latest article <a title="Quick Tomcat and Eclipse Integration Ã¢â‚¬â€œ Deploying Web apps to Tomcat from within Eclipse" href="jsp-servlets/quick-eclipse-tomcat-integration.html" target="_blank" rel="alternate noopener noreferrer">Quick Tomcat and Eclipse Integration â‚¬â€œ Deploying Web apps to Tomcat from within Eclipse </a>which walks through step by step for configuring Tomcat 8 with the latest Eclipse Kepler version</p>
</blockquote>
]]></content:encoded>
					
					<wfw:commentRss>https://www.tech-freaks.com/java/jsp-servlets/eclipse-tomcat-integration.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
