Boobada
Boobada

Reputation: 21

How to deploy and run first JSP application on Tomcat server 8.0.2?

I hope a tomcat veteran can help me here! I have two major problems (linking the pages and database connectivity)

A. Linking the pages:

  1. I renamed myapps.war to ROOT.war;

  2. I have deployed the WAR file in tomcat/web-apps/application.com/ROOT Tomcat then unpacked the WAR and generated a sub file;

  3. I have placed jstl.jar in tomcat/web-apps/application.com/ROOT/WEB-INF/lib.

The index.jsp displays well in the browser. Everything appears fine but when I click on any given URL whether is /viewCart to see cart.jsp or category?{category.id} to display data from that selected category, I receive a 404 Http error resource not available in the browser. All the pages (except the index page) are stored in tomcat/web-apps/application.com/ROOT/WEB-INF/view.

Since no other page but index.jsp displays at all, I'm guessing I have to move the files up and put them in the same sub-directory of index.jsp? But does it not remove all the purposes of WEB-INF to hide dynamic pages?

I'm a bit confused. I dont know what i'm doing wrong...

B. Database connectivity

  1. I have downloaded the platform independant JDBC driver here and placed it (mysql-connector-java-version-bin.jar) in tomcat/web-apps/application.com/ROOT/WEB-INF/lib

I'm trying to follow this documentation: http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-tomcat.html

This is where it gets a bit confusing... In the documentation they say to configure the JNDI DataSource by adding a declaration resource to $CATALINA_HOME/conf/server.xml in the context that defines the web application and they provide a piece of code. My question for this segment is: what do they mean by server.xml? Do they mean web.xml or persistence.xml? Because the JNDI name of the data source used by my application to interact with the database is found in the persistence unit (persistence.xml file) and is stored in tomcat/web-apps/application.com/ROOT/WEB-INF/classes/META-INF... Should I move persistence.xml elsewhere or should I just add piece of code in web.xml?

EDIT ON REQUEST - CONFIGURATION FILES

PERSISTENCE.XML

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="ApplicationNamePU" transaction-type="JTA">
  <jta-data-source>jdbc/applicationName</jta-data-source>
  <properties>
    <property name="eclipselink.logging.level" value="FINEST"/>
  </properties>
</persistence-unit>
</persistence>

SERVER.XML - RAW NOT MODIFIED

<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="15005" shutdown="SHUTDOWN" address="127.8.97.129">
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener className="org.apache.catalina.core.JasperListener" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000" address="127.8.97.129" 
               redirectPort="8443" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
    <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="15009" protocol="AJP/1.3" redirectPort="8443" address="127.8.97.129" />


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

      </Host>
    </Engine>
  </Service>
</Server>

3RD EDIT ON REQUEST

Controller entry for /cart:

// if cart page is requested
        } else if (userPath.equals("/viewCart")) {

            String clear = request.getParameter("clear");

            if ((clear != null) && clear.equals("true")) {

                ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
                cart.clear();
            }

            userPath = "/cart";


// if addToCart action is called
        if (userPath.equals("/addToCart")) {

            // if user is adding item to cart for first time
            // create cart object and attach it to user session
            if (cart == null) {

                cart = new ShoppingCart();
                session.setAttribute("cart", cart);
            }

            // get user input from request
            String productId = request.getParameter("productId");

            if (!productId.isEmpty()) {

                Product product = productFacade.find(Integer.parseInt(productId));
                cart.addItem(product);
            }

            userPath = "/category";


        // if updateCart action is called
        } else if (userPath.equals("/updateCart")) {

            // get input from request
            String productId = request.getParameter("productId");
            String quantity = request.getParameter("quantity");

            boolean invalidEntry = validator.validateQuantity(productId, quantity);

            if (!invalidEntry) {

                Product product = productFacade.find(Integer.parseInt(productId));
                cart.update(product, quantity);
            }

            userPath = "/cart";

Upvotes: 1

Views: 613

Answers (1)

Tony Vu
Tony Vu

Reputation: 4361

To answer your question:

A. Linking the pages

How your url is linked to jsp pages depend on the web framework that you are using. Are you using Spring MVC or Struts?

For example, if you use Spring MVC, the linking is done by @RequestMapping in your controller and view resolver defined in your xml configuration. http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html

If you use struts 2, the linking is defined in struts.xml file and in your action. Example: http://struts.apache.org/docs/hello-world-using-struts-2.html

B. Database Connectivity

When the documentation says $CATALINA_HOME/conf/server.xml, it refers to your apache tomcat instance home. Go to your Tomcat folder(something like apache-tomcat-7.0.42), you will see a folder called conf where all the tomcat configuration files(like server.xml, context.xml, web.xml,...) are located. You can specify the database connection there. But remember that if you do that way, all your web apps deployed to this tomcat will share the same configuration. My preferred way of specifying the database connection with JNDI is to have it inside context.xml file under META-INF folder. In that way, I can have specific database config for my application.

Upvotes: 1

Related Questions