<?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>Java Programming &#8211; Tech-Freaks.com</title>
	<atom:link href="https://www.tech-freaks.com/java/feed" rel="self" type="application/rss+xml" />
	<link>https://www.tech-freaks.com</link>
	<description></description>
	<lastBuildDate>Mon, 30 Jun 2025 02:43:15 +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>Java Programming &#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="894dd3979e"
					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="cb6cf67075"
					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="63cdb2e33a"
					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="b618dcc06c"
					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="bc1bd5add8"
					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>Javascript with JSON</title>
		<link>https://www.tech-freaks.com/java/javascript/json-javascript.html</link>
					<comments>https://www.tech-freaks.com/java/javascript/json-javascript.html#respond</comments>
		
		<dc:creator><![CDATA[Tech Programmer]]></dc:creator>
		<pubDate>Sun, 20 Jan 2013 05:10:11 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">http://localhost/tfcom_wp/2013/01/20/json-javascript/</guid>

					<description><![CDATA[This workshop is for you, if: You are looking for a data structure to store your data for easy javascript [&#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="77"
					data-ulike-nonce="8fcf869cc8"
					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_77"></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 for a data structure to store your data for easy javascript access</li>
<li>You have seen JSON structure but do not know, how to access it using javascript</li>
</ul>
<p style="text-align: left;"><strong>This workshop is not for you, if:</strong></p>
<ul style="text-align: left;">
<li>You have no idea about client side scripting</li>
</ul>
<p style="text-align: left;">This workshop intends to provide hands on example on creating JSON structure and accessing the contents of the JSON using Javascript.</p>
<p style="text-align: left;"><strong>&#8216;JSON&#8217; the new kid in town</strong></p>
<p style="text-align: left;">JSON which stands for JavaScript Object Notation is the new buzz word and will definitely look good in your resume! But, how is JSON useful from a technology perspective.</p>
<ul style="text-align: left;">
<li>JSON can store data in the client side, where data security is not important.</li>
<li>JSON can be used for data exchange just like XML. But, why not XML itself? JSON comes handy when the exchanged data needs to be handled in the client side. JSON structure is easy to be manipulated in client side using javascript.</li>
</ul>
<p style="text-align: left;"><strong>Workshop Requirement</strong></p>
<p style="text-align: left;">Let us say, we need to maintain the summary of contents of this website. We want the data not to be maintained in database. We need to get information from a data structure using Javascript and of course, this data is not sensitive. The website contains, two sections (while writing this article), Java Programming and Stock Market. Each section contains categories and each category contains articles. Based on this data, we would like to see the number of pages in Java category etc.</p>
<p style="text-align: left;"><strong>Meeting JSON flesh and blood</strong></p>
<p style="text-align: left;">Enough talking about JSON! Let us actually see a JSON structure. The code snippet provided below shows a JSON structure assigned to a Javascript variable. When we use JSON for data exchange, we will write or receive JSON structure starting from braces without the javascript variable. To convert this into a javascript variable, we can use &#8216;eval&#8217; function, which is not recommended. There are parsers available in <a title="www.json.org" href="http://www.json.org/" target="_blank" rel="nofollow noopener noreferrer"><span style="text-decoration: underline;"><span style="color: #800080;">JSON.org</span></span></a> which converts the JSON structure to javascript variable.</p>
<pre class="language-javascript"><code>var varSiteData = {
  "sections" : [ //Array
     {//Each element in array, ie. Section is a structure not a simple attribute
      "name": "Java Programming", //this is a simple attribute
      "categories": [
      {
         "name":"Java Basics",
         "articles": [
         {
            "name" : "Java Hello World",
            "pages" : "1",
            "author" : "Tech Programmer"         
         },
         {
            "name" : "Java Hello World using Eclipse IDE",
            "pages" : "5",
            "author" : "Tech Programmer"         
         },
         ...
         ...
       ]
      },
      ...
      ...
     ]
    },
    ...
    ....
   ]
 }</code></pre>
<pre class="code-style" style="text-align: left;"></pre>
<p style="text-align: left;">Let us try to understand the syntax. JSON always start and end with curly braces. They contain attributes. The value of each attribute can be simple string, a structure (which internally is composed of many simple string attributes), array of simple string or array of structures. Here &#8220;section&#8221; is an attribute. How many sections we have in the site? Two, Java programming and Stock market. This calls for an array. Arrays are defined by square brackets. Now, each section contains categories. Also, each section needs a name to be stored. So, we have added an attribute by &#8220;name&#8221;. Attribute &#8220;name&#8221; is a simple string. Other attributes shown work in the same way. Click <a title="JSON in JS" href="sourcecode/JSON/v1/website_json.js" target="_blank" rel="nofollow noopener noreferrer">here</a> to download the complete JSON structure stored in JS file.</p>
<dl id="tf-message">
<dd class="message message fade">
<ul>
<li>An attribute name or key cannot start with numeric value. Although this is not a rule written anywhere, when the key or attribute name starts with or is a numeric value, the javascript which parse through the JSON does not understand the key. A simple workaround to resolve this issue is to append a constant string before the numeric value. Example: &#8220;str_25&#8221;</li>
</ul>
</dd>
</dl>
<p style="text-align: left;"> One more important thing is, if for an attribute, the value needs to be multiple attributes but not an array, then it is achieved using curly brackets only. A simple snippet which shows the attribute structure for Alphonsa mango:</p>
<pre class="language-javascript"><code>"alphonsa" : {
  "type": "mango",
  "taste": "sweet",
  "color": "yellow"
}</code></pre>
<p style="text-align: left;">Well, that&#8217;s that. We got started with JSON. But, let us try to have a quick look, why JSON is compared with XML. See the above JSON structure in an XML format.</p>
<pre class="language-markup"><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;
&lt;sections&gt;
  &lt;section&gt;
     &lt;name&gt;Java Programming&lt;/name&gt;
     &lt;category&gt;
        &lt;name&gt;Java Basics&lt;/name&gt;
        &lt;article&gt;
           &lt;name&gt;Java Hello World&lt;/name&gt;
           &lt;pages&gt;1&lt;/pages&gt;
           &lt;author&gt;Tech Programmer&lt;/author&gt;
        &lt;/article&gt;
        &lt;article&gt;
           &lt;name&gt;Java Hello World using Eclipse IDE&lt;/name&gt;
           &lt;pages&gt;5&lt;/pages&gt;
           &lt;author&gt;Tech Programmer&lt;/author&gt;
        &lt;/article&gt;
       ...
       ...
     &lt;/category&gt;
  &lt;/section&gt;
..
&lt;/sections&gt;</code></pre>
<p style="text-align: left;"><strong>Validating JSON structure</strong></p>
<p style="text-align: left;">Just like we validate XML structures using Internet Explorer and other tools for well-formedness, there are certain JSON viewers available, which verify the JSON structure and provide details regarding any missing braces etc. <a title="JSON Viewer" href="http://www.codeplex.com/JsonViewer" target="_blank" rel="nofollow noopener noreferrer"><span style="text-decoration: underline;"><span style="color: #800080;">JSON Viewer</span></span></a> is one such hand helpful too.</p>
<p style="text-align: left;"><strong>Javascript and JSON</strong></p>
<p style="text-align: left;">Now, let us see how Javascript can access different elements within the JSON structure. We will try to calculate the total number of pages in &#8216;Stock Market&#8217; and &#8216;Java Programming&#8217; section. The HTML page includes the JSON data from a JS file. The javascript present in the HTML page iterates through the JSON structure to determine the result.</p>
<p style="text-align: left;">See the below javascript function, with comments explaining how the JSON structure is iterated through.</p>
<pre class="language-javascript"><code>function getSectionTotalPages(section) {

 //entry point into JSON variable..Accessing sections attribue, which is an array
 var arrSections = varSiteData.sections;
 var totalPages = 0;
 //loop through each of the sections
 for(var i=0;i&lt;arrSections.length;i++) {
  var currSection = arrSections[i];
  //we get the section for which we want to calculate the page total
  if(currSection.name==section) {
   //Now into category array from section
   var arrCategories = currSection.categories;
   
   //loop through the category array
   for(var j=0;j&lt;arrCategories.length;j++) {
    var currCategory = arrCategories[j];
    //For each category, get the article list (array)
    var arrArticles = currCategory.articles;
    //loop through each article
    for(var k=0;k&lt;arrArticles.length;k++) {
     var currArticle = arrArticles[k];
 
     //for each article, get the # of pages and add it to total
     totalPages = totalPages + parseInt(currArticle.pages);
    }
   }
   //This method works for one section, so break the loop, if the section is found
   break;
  }
 }
 return totalPages;
}</code></pre>
<pre class="brush:javascript" style="text-align: left;"><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;">The complete HTML containing the javascripts is given below. On clicking the compare button, the compareSectionPages function is called. It internally,calls getSectionTotalPages function twice, for getting pages for </span><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;">'</span><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;">Java Programming</span><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;">'</span><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;"> section and </span><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;">'</span><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;">Market Analysis</span><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;">'</span><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;"> section.</span></pre>
<pre class="language-markup"><code>&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;JSON and Javascript example&lt;/title&gt;
  &lt;script type="text/javascript" src="website_json.js" &gt;&lt;/script&gt;
  &lt;script language="javascript" type="text/javascript"&gt;
  function getSectionTotalPages(section) {
 var arrSections = varSiteData.sections;
 var totalPages = 0;
 for(var i=0;i&lt;arrSections.length;i++) {
  var currSection = arrSections[i];
  if(currSection.name==section) {
   var arrCategories = currSection.categories;
  for(var j=0;j&lt;arrCategories.length;j++) {

    var currCategory = arrCategories[j];
    var arrArticles = currCategory.articles;
    for(var k=0;k&lt;arrArticles.length;k++) {
     var currArticle = arrArticles[k];
     totalPages = totalPages + parseInt(currArticle.pages);
    }
   }
   break;
  }
 }
 return totalPages;
}

  function compareSectionPages() {
   var totalJavaPages = getSectionTotalPages('Java Programming');
 var totalMarketPages = getSectionTotalPages('Market Analysis');
   var result = "&lt;table border='1'&gt;&lt;tr&gt;&lt;td&gt;Java Programming&lt;/td&gt;&lt;td&gt;Market Analysis&lt;/td&gt;

&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;"+totalJavaPages+"&lt;/td&gt;&lt;td&gt;"+totalMarketPages+"&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;";
   document.getElementById('result').innerHTML = result;
  }

  &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;h2&gt;Welcome to JSON with javascript workshop!&lt;/h2&gt;
  &lt;p&gt;
  &lt;input type="button" name="button1" value="Compare Section pages" onclick="compareSectionPages();"&gt;

  &lt;p&gt;&lt;p&gt;
  Result: &lt;div id="result"&gt;&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre>
<p style="text-align: left;"> And the result is 17 to 12. Java programming wins by 5 goals!</p>
<p style="text-align: left;">The author of the &#8216;Market analysis&#8217; section may feel bit hard done by.  Some articles missed out were missed out. &#8216;Technical Analysis&#8217; and &#8216;Market Summary&#8217; articles were not considered. We added every article inside the category, but these two articles are not maintained at category level. They are maintained in section level.</p>
<hr class="system-pagebreak" title="JSON flexibility" />
<p style="text-align: left;">Well, change is inevitable in the JSON structure! However, the flexibility of JSON will cover up for it. But, the change in data structure will cause a change to javascript code to calculate the total pages in section.</p>
<p style="text-align: left;">Let us get this thing fixed. For the JSON fix, a little thought will make it clear that adding articles inside section structure will be similar to articles maintained inside categories. The below code snippet shows the portion of the changed JSON:</p>
<pre class="code-style" style="text-align: left;"></pre>
<pre class="language-javascript"><code> ...
      {
      "name":"Market Analysis",
      "articles": [
       {
          "name": "Market Summary",
          "pages": "1",
          "author" : "Market Analyst"        
       },
       {
          "name": "Tech Analysis",
          "pages": "1",
          "author" : "Market Analyst"        
       }
      ] 
      ....
     .....</code></pre>
<p style="text-align: left;">The change in  getSectionTotalPages will be bit more challenging. Now, in the code we have to deal with one section, which has articles array and another which does not. Also, this method needs to be generic enough to handle any new sections added to the website in the future. Some of the section may have articles inside it and some may not. Many times, while using javascript we see the &#8216;undefined&#8217; variable. We will have to use this, to check if articles array is present directly within sections.</p>
<p>The below modified function getSectionTotalPages will do the trick. See the comments explaining the main changes and the <em>typeof</em> function used to good effect.</p>
<pre class="language-javascript"><code>function getSectionTotalPages(section) {
 var arrSections = varSiteData.sections;
 var totalPages = 0;
 for(var i=0;i&lt;arrSections.length;i++) {
  var currSection = arrSections[i];
  if(currSection.name==section) {
   //Check if articles inside section is undefined (does not exist)
   //If not undefined, then section as articles like Market Analysis section
   if(typeof(currSection.articles)!='undefined') {

    var arrSecArticles = currSection.articles;
    for(var j=0;j&lt;arrSecArticles.length;j++) {
     var currSecArticle = arrSecArticles[j];
     totalPages = totalPages + parseInt(currSecArticle.pages);

    }
   }
   var arrCategories = currSection.categories;

   for(var j=0;j&lt;arrCategories.length;j++) {
    var currCategory = arrCategories[j];
    var arrArticles = currCategory.articles;
    for(var k=0;k&lt;arrArticles.length;k++) {
     var currArticle = arrArticles[k];
     totalPages = totalPages + parseInt(currArticle.pages);
    }
   }
   break;
  }
 }
 return totalPages;
}</code></pre>
<p style="text-align: left;">Update the HTML code contents with the above updated function. Click <span style="text-decoration: underline;"><span style="color: #0066cc;"><a title="JSON structure" href="sourcecode/JSON/v2/website_json.js" target="_blank" rel="nofollow noopener noreferrer">here</a></span></span> to download the updated JSON code. Place the HTML and JS file in the same directory. Access the HTML page from browser and then click the &#8216;Compare Section pages&#8217; button to view the result table. &#8216;Java Programming&#8217; still wins by a margin of 3!</p>
<p style="text-align: left;">Welcome to the whole new world of client side scripting with JSON!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.tech-freaks.com/java/javascript/json-javascript.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="f2337421b3"
					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="83295b2cc7"
					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>Accessing Websphere Commerce Context Objects</title>
		<link>https://www.tech-freaks.com/java/websphere-commerce/wc-context-objects.html</link>
					<comments>https://www.tech-freaks.com/java/websphere-commerce/wc-context-objects.html#respond</comments>
		
		<dc:creator><![CDATA[Tech Programmer]]></dc:creator>
		<pubDate>Wed, 23 May 2012 23:58:52 +0000</pubDate>
				<category><![CDATA[Websphere Commerce]]></category>
		<guid isPermaLink="false">http://localhost/tfcom_wp/2012/05/23/wc-context-objects/</guid>

					<description><![CDATA[IBM Infocenter URL for CommandContext is Infocenter CommandContext API When you review the methods you will see lot of deprecated [&#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="34"
					data-ulike-nonce="7f5282b49d"
					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_34"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0"></span>			</div></div>
	<p style="text-align: left;">IBM Infocenter URL for CommandContext is <a href="https://help.hcltechsw.com/commerce/8.0.0/api/com/ibm/commerce/command/CommandContext.html" target="_blank" rel="noopener">Infocenter CommandContext API</a></p>
<p style="text-align: left;">When you review the methods you will see lot of deprecated methods which mention use of other context objects to access the information.</p>
<p>For this article we will review the CommandContext.getRemoteAddr() method which will give the IP address of the user accessing the site.</p>
<p style="text-align: left;">Infocenter mentions:</p>
<p><em>getRemoteAddr()<br />Deprecated. The TransportData object should be retrieved from the AuditContext of the request. The remote address is retrieved by calling TransportData.getRemoteAddress()<br /></em><br />We need to use the AuditContext, but the first question is how we get instance of AuditContext.</p>
<p><em>CommandContext.getContext(strContextName)</em> is the method we need to use.</p>
<p>Below sample code explains how to get IP address using the AuditContext</p>
<pre class="language-java"><code>AuditContext auditCtx = (AuditContext) getCommandContext().getContext(AuditContext.NAME);
System.out.println("IP Address "+auditCtx.getTransportData().getRemoteAddress());</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://www.tech-freaks.com/java/websphere-commerce/wc-context-objects.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Troubleshooting &#8216;Order is not locked, but it should be locked&#8217; issue</title>
		<link>https://www.tech-freaks.com/java/websphere-commerce/order-not-locked.html</link>
					<comments>https://www.tech-freaks.com/java/websphere-commerce/order-not-locked.html#respond</comments>
		
		<dc:creator><![CDATA[Tech Programmer]]></dc:creator>
		<pubDate>Sun, 13 Feb 2011 12:48:20 +0000</pubDate>
				<category><![CDATA[Websphere Commerce]]></category>
		<guid isPermaLink="false">http://localhost/tfcom_wp/2011/02/13/order-not-locked/</guid>

					<description><![CDATA[Issue: In the final step of check out flow, when the user clicks the order button he might be displayed [&#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="33"
					data-ulike-nonce="1294064ffa"
					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_33"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0"></span>			</div></div>
	<p><strong>Issue</strong>:</p>
<p>In the final step of check out flow, when the user clicks the order button he might be displayed with a message like &#8220;Order not locked but should be locked&#8221;.</p>
<p><strong>Sample Logs:</strong></p>
<p>[2/13/11 1:09:15:500 EST] 0000009f WC_ORDER      &gt; 222ee85c:12e1d76ea52:-7ffb com.ibm.commerce.order.commands.PreProcessOrderCmdImpl.validateShippingAddress Entry</p>
<p>[2/13/11 1:09:15:500 EST] 0000009f WC_ORDER      &lt; 222ee85c:12e1d76ea52:-7ffb com.ibm.commerce.order.commands.PreProcessOrderCmdImpl.validateShippingAddress Exit</p>
<p>[2/13/11 1:09:15:500 EST] 0000009f CommerceSrvr  A com.ibm.commerce.order.commands.PreProcessOrderCmdImpl performExecute CMN1022E: Order 11001 is not locked, but it should be locked.</p>
<p>[2/13/11 1:09:15:609 EST] 0000009f FfdcProvider  W com.ibm.ws.ffdc.impl.FfdcProvider logIncident FFDC1003I: FFDC Incident emitted on C</p>
<p>[2/13/11 1:09:16:078 EST] 0000009f servlet       I com.ibm.ws.webcontainer.servlet.ServletWrapper init SRVE0242I: [WC] [/webapp/wcs/stores] [/AjaxActionErrorResponse.jsp[2/13/11 1:09:15:890 EST] 0000009f bod           I   Order 11001 is not locked, but it should be locked.</p>
<p> </p>
<p><strong>Cause:</strong></p>
<p>The final step of the order confirmation might be calling the Out-Of-Box OrderProcessCmdImpl. Before proceeding with the processing of the order, the command checks the state of order. In the database, it would check for ORDERS.LOCKED field. If the value of this field is 0, it would indicate that the order was not locked and ready for order confirmation.</p>
<p>This could happen if the call to the OrderPrepareCmdImpl got skipped. During the process of preparing the order, this command also locks(LOCKED=1) before the order can be confirmed using the OrderProcessCmdImpl.</p>
<p>The command invoked when the cart is access unlocks the orders (LOCKED=0). One command would be OrderItemDeleteCmdImpl which unlocks.</p>
<p> </p>
<p><strong>Solution:</strong></p>
<ol>
<li>Understand the checkout flow and the possible skipped step which could miss the call to OrderPrepareCmdImpl.</li>
<li>Ensure by using a workflow like check to ensure that OrderProcessCmdImpl should not be invoked before OrderPrepareCmdImpl invocation step is executed.</li>
</ol>
<p> </p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.tech-freaks.com/java/websphere-commerce/order-not-locked.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
