Showing posts with label apache tomcat. Show all posts
Showing posts with label apache tomcat. Show all posts

Friday, September 18, 2026

Debian 13: jakarta tomcat create servlet manually

under directory WEB-INF create 2 folder

  1. src
  2. classes 

under src, we place servlet and java code.

for package com.dedetok, create folder ~/WEB-INF/src/com/dedetok/ and write 2 files

MyWorld.java

package com.dedetok;

public class MyWorld {

    public String getMessage() {
        return "hello world";
    }
}

HelloServlet.java 

package com.dedetok;

import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request,
                          HttpServletResponse response)
            throws IOException {

        MyWorld world = new MyWorld();

        response.setContentType("text/plain");
        response.getWriter().println(world.getMessage());
    }
} 

We map our servlet, edit ~/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
                             https://jakarta.ee/xml/ns/jakartaee/web-app_6_1.xsd"
         version="6.1">

    <display-name>My Application</display-name>

    <servlet>
        <servlet-name>Hello Anything</servlet-name>
        <servlet-class>com.dedetok.HelloServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Hello Anything</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

Note: <servlet-name> between <servlet> and <servlet-mapping> must match.

compile your java, go it ~/WEB-INF/ folder and run

$ javac   -cp <your_path_to_jakarta_tomcat>/apache-tomcat-11.0.26/lib/servlet-api.jar   -d ./classes   ./src/com/dedetok/*.java 

restart your jakarta tomcat and try servlet http://localhost:8080/myapp/hello. hello comes from <servlet-mapping>

It is not practicable to map every servlet, there is other way

now at directory ~/WEB-INF/src/com/dedetok/  create HelloServlet2.java

package com.dedetok;

import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import jakarta.servlet.annotation.WebServlet;

@WebServlet("/hello2")
public class HelloServlet2 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request,
                          HttpServletResponse response)
            throws IOException {

        MyWorld world = new MyWorld();

        response.setContentType("text/plain");
        response.getWriter().println(world.getMessage()+" 2");
    }
}  

we use  @WebServlet("/hello2") to map url. do not forget to import  jakarta.servlet.annotation.WebServlet.

compile it, and restart your jakarta tomcat. you can access it via http://localhost:8080/myapp/hello2.

To use MyWorld class into jsp, at directory ~/myapp/ (upper directory from WEB-INF) , create file callservlet.jsp

<%@ page import="com.dedetok.MyWorld" %>

<%
    MyWorld world = new MyWorld();
%>

<html>
<body>
    <h1><%= world.getMessage() %></h1>
</body>
</html> 

or use wildcard for import="com.dedetok.*"  

Now you can directly build your application. MVC model can be used if you like. happy coding.  

 

Thursday, September 17, 2026

Debian 13: jakarta tomcat add application myapp manually without war (part 2)

It this part, we will: 

  1. Add myapp
  2. Add mariadb library

Add myapp

  1. under folder <home>/webapps/ create folder myapp
  2. under folder <home>/webapps/myapp/  create folder WEB-INF
  3. optional, at folder <home>/webapp/myapp> write index.html e.g  
<!DOCTYPE html>
<html lang="en">
<body>
    <h1>Hello, World!</h1>
</body>
</html>

Restart your jakarta tomcat, and myapp appear in list of application. Test your index.html, url http://localhost:8080/myapp/.

Add mariadb 

  1. Under folder  <home>/webapps/myapp/WEB_INF, create folder lib.
  2. download jconnect from https://mariadb.org/connector-java/all-releases/, and put it in <home>/webapps/myapp/WEB_INF/lib, i.e. <home>/webapps/myapp/WEB-INF/lib/mariadb-java-client-3.5.3.jar

Under folder  <home>/webapps/myapp/ write test.jsp

<%
try {
    Class.forName("org.mariadb.jdbc.Driver");
    out.println("MariaDB JDBC driver FOUND");
} catch (ClassNotFoundException e) {
    out.println("MariaDB JDBC driver NOT FOUND");
}
%>

restart your jakarta tomcat and test it http://localhost:8080/myapp/test.jsp.

if you have mariadb running, you can extend test.jsp to this

<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>

<%
try {
    Class.forName("org.mariadb.jdbc.Driver");
    out.println("MariaDB JDBC driver FOUND<br>");

    Connection conn = DriverManager.getConnection(
        "jdbc:mariadb://localhost:3306/mydb", // change to your db name
        "admin", // change to your user
        "admin" // change to your password
    );

    out.println("Connected to MariaDB!<br>");

    conn.close();

} catch (ClassNotFoundException e) {
    out.println("MariaDB JDBC driver NOT FOUND<br>");
    out.println(e);

} catch (Exception e) {
    out.println("Database connection FAILED<br>");
    out.println(e);
}
%> 

 

 

 

Debian 13: jakarta tomcat & openjdk 21 installation (part 1)

Assume openjdk 21 installed, it is lts verssion.

Download latest jakarta tomcat from https://tomcat.apache.org/download-11.cgi, i.e. version 11.0.26 (currently).

extract it into your home (user) directory

change permission to start jakarta tomcat

$ cd apache-tomcat-11.0.26/bin/
$ chmod 744 *.sh

Directory structure is:

  • bin
  • conf
  • lob
  • logss
  • temps
  • webapps
  • work 

You must add user to manage your jakarta tomcat. User rules are:

  1. manager-gui - allows access to the HTML GUI and the status pages
  2. manager-script - allows access to the text interface and the status pages
  3. manager-jmx - allows access to the JMX proxy and the status pages
  4. manager-status - allows access to the status pages only 

Edit <tomcat_home>/conf/tomcat-users.xml

<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
...
  <role rolename="manager-gui"/>
  <user username="admin" password="admin" roles="manager-gui"/>
</tomcat-users> 

To run jakarta tomcat

$ ./startup.sh&
[1] 6430
~/apache-tomcat-11.0.26/bin$ Using CATALINA_BASE:   <home>/apache-tomcat-11.0.26
Using CATALINA_HOME:   <home>/apache-tomcat-11.0.26
Using CATALINA_TMPDIR: <home>/apache-tomcat-11.0.26/temp
Using JRE_HOME:        /usr
Using CLASSPATH:       <home>/apache-tomcat-11.0.26/bin/bootstrap.jar:<home>/apache-tomcat-11.0.26/bin/tomcat-juli.jar
Using CATALINA_OPTS:   
Tomcat started.

[1]+  Done                    ./startup.sh

Open your browser and open url http://localhost:8080/. 

To shutdown, run $ ./shutdown.sh.

Your application will on <home>/webapps and root for http://localhost:8080 is on <home>/webapps/ROOT/

For production, go to "List Application", Undeploy any unused applications.  

 

Wednesday, January 27, 2016

Installing OpenJDK 8 and Tomcat 8 on Debian Jessie

Debian 8 (Jessie) already support JDK 8 and Tomcat 8.

Tomcat 8 exist in jessie repository and jessie-backports repository. For latest Tomcat 8, we use jessie-backports

Do these easy step to install OpenJDK 8 and Tomcat 8 on Debian Jessie:
  1. Edit /etc/apt/sources.list and add these lines (you may ignore line with #)
    # Backport Testing on stable
    # JDK 8
    deb http://ftp.de.debian.org/debian jessie-backports main
  2. # apt-get update
  3. # apt-get install openjdk-8-jdk
  4. # apt-get install tomcat8 tomcat8-admin
If you upgrade your Debian 7 (does not support Tomcat 8) to Debian 8, you may lost some Tomcat 8 files. Here is some script you can used into your tomcat8 installation:
/etc/default/tomcat8
 # Run Tomcat as this user ID. Not setting this or leaving it blank will use the
# default of tomcat8.
TOMCAT8_USER=tomcat8

# Run Tomcat as this group ID. Not setting this or leaving it blank will use
# the default of tomcat8.
TOMCAT8_GROUP=tomcat8

# The home directory of the Java development kit (JDK). You need at least
# JDK version 7. If JAVA_HOME is not set, some common directories for
# OpenJDK and the Oracle JDK are tried.
#JAVA_HOME=/usr/lib/jvm/java-7-openjdk

# You may pass JVM startup parameters to Java here. If unset, the default
# options will be: -Djava.awt.headless=true -Xmx128m -XX:+UseConcMarkSweepGC
#
# Use "-XX:+UseConcMarkSweepGC" to enable the CMS garbage collector (improved
# response time). If you use that option and you run Tomcat on a machine with
# exactly one CPU chip that contains one or two cores, you should also add
# the "-XX:+CMSIncrementalMode" option.
JAVA_OPTS="-Djava.awt.headless=true -Xmx128m -XX:+UseConcMarkSweepGC"

# To enable remote debugging uncomment the following line.
# You will then be able to use a java debugger on port 8000.
#JAVA_OPTS="${JAVA_OPTS} -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,serv
er=y,suspend=n"

# Java compiler to use for translating JavaServer Pages (JSPs). You can use all
# compilers that are accepted by Ant's build.compiler property.
#JSP_COMPILER=javac

# Use the Java security manager? (yes/no, default: no)
#TOMCAT8_SECURITY=no

# Number of days to keep logfiles in /var/log/tomcat8. Default is 14 days.
#LOGFILE_DAYS=14
# Whether to compress logfiles older than today's
#LOGFILE_COMPRESS=1

# Location of the JVM temporary directory
# WARNING: This directory will be destroyed and recreated at every startup !
#JVM_TMP=/tmp/tomcat8-temp

# If you run Tomcat on port numbers that are all higher than 1023, then you
# do not need authbind.  It is used for binding Tomcat to lower port numbers.
# (yes/no, default: no)
#AUTHBIND=no
/etc/init.d/tomcat8 with chmod 755
#!/bin/sh
#
# /etc/init.d/tomcat8 -- startup script for the Tomcat 8 servlet engine
#
# Written by Miquel van Smoorenburg <miquels@cistron.nl>.
# Modified for Debian GNU/Linux    by Ian Murdock <imurdock@gnu.ai.mit.edu>.
# Modified for Tomcat by Stefan Gybas <sgybas@debian.org>.
# Modified for Tomcat6 by Thierry Carrez <thierry.carrez@ubuntu.com>.
# Modified for Tomcat7 by Ernesto Hernandez-Novich <emhn@itverx.com.ve>.
# Additional improvements by Jason Brittain <jason.brittain@mulesoft.com>.
#
### BEGIN INIT INFO
# Provides:          tomcat8
# Required-Start:    $local_fs $remote_fs $network
# Required-Stop:     $local_fs $remote_fs $network
# Should-Start:      $named
# Should-Stop:       $named
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start Tomcat.
# Description:       Start the Tomcat servlet engine.
### END INIT INFO

set -e

PATH=/bin:/usr/bin:/sbin:/usr/sbin
NAME=tomcat8
DESC="Tomcat servlet engine"
DEFAULT=/etc/default/$NAME
JVM_TMP=/tmp/tomcat8-$NAME-tmp

if [ `id -u` -ne 0 ]; then
    echo "You need root privileges to run this script"
    exit 1
fi

# Make sure tomcat is started with system locale
if [ -r /etc/default/locale ]; then
    . /etc/default/locale
    export LANG
fi

. /lib/lsb/init-functions

if [ -r /etc/default/rcS ]; then
    . /etc/default/rcS
fi


# The following variables can be overwritten in $DEFAULT

# Run Tomcat 8 as this user ID and group ID
TOMCAT8_USER=tomcat8
TOMCAT8_GROUP=tomcat8

# this is a work-around until there is a suitable runtime replacement
# for dpkg-architecture for arch:all packages
# this function sets the variable JDK_DIRS
find_jdks()
{
    for java_version in 9 8 7
    do
        for jvmdir in /usr/lib/jvm/java-${java_version}-openjdk-* \
                      /usr/lib/jvm/jdk-${java_version}-oracle-* \
                      /usr/lib/jvm/jre-${java_version}-oracle-*
        do
            if [ -d "${jvmdir}" ]
            then
                JDK_DIRS="${JDK_DIRS} ${jvmdir}"
            fi
        done
    done

    # Add older non multi arch installations
    JDK_DIRS="${JDK_DIRS} /usr/lib/jvm/java-7-oracle"
}

# The first existing directory is used for JAVA_HOME (if JAVA_HOME is not
# defined in $DEFAULT)
JDK_DIRS="/usr/lib/jvm/default-java"
find_jdks

# Look for the right JVM to use
for jdir in $JDK_DIRS; do
    if [ -r "$jdir/bin/java" -a -z "${JAVA_HOME}" ]; then
    JAVA_HOME="$jdir"
    fi
done
export JAVA_HOME

# Directory where the Tomcat 8 binary distribution resides
CATALINA_HOME=/usr/share/$NAME

# Directory for per-instance configuration files and webapps
CATALINA_BASE=/var/lib/$NAME

# Use the Java security manager? (yes/no)
TOMCAT8_SECURITY=no

# Default Java options
# Set java.awt.headless=true if JAVA_OPTS is not set so the
# Xalan XSL transformer can work without X11 display on JDK 1.4+
# It also looks like the default heap size of 64M is not enough for most cases
# so the maximum heap size is set to 128M
if [ -z "$JAVA_OPTS" ]; then
    JAVA_OPTS="-Djava.awt.headless=true -Xmx128M"
fi

# End of variables that can be overwritten in $DEFAULT

# overwrite settings from default file
if [ -f "$DEFAULT" ]; then
    . "$DEFAULT"
fi

if [ ! -f "$CATALINA_HOME/bin/bootstrap.jar" ]; then
    log_failure_msg "$NAME is not installed"
    exit 1
fi

POLICY_CACHE="$CATALINA_BASE/work/catalina.policy"

if [ -z "$CATALINA_TMPDIR" ]; then
    CATALINA_TMPDIR="$JVM_TMP"
fi

# Set the JSP compiler if set in the tomcat8.default file
if [ -n "$JSP_COMPILER" ]; then
    JAVA_OPTS="$JAVA_OPTS -Dbuild.compiler=\"$JSP_COMPILER\""
fi

SECURITY=""
if [ "$TOMCAT8_SECURITY" = "yes" ]; then
    SECURITY="-security"
fi

# Define other required variables
CATALINA_PID="/var/run/$NAME.pid"
CATALINA_SH="$CATALINA_HOME/bin/catalina.sh"

# Look for Java Secure Sockets Extension (JSSE) JARs
if [ -z "${JSSE_HOME}" -a -r "${JAVA_HOME}/jre/lib/jsse.jar" ]; then
    JSSE_HOME="${JAVA_HOME}/jre/"
fi

catalina_sh() {
    # Escape any double quotes in the value of JAVA_OPTS
    JAVA_OPTS="$(echo $JAVA_OPTS | sed 's/\"/\\\"/g')"

    AUTHBIND_COMMAND=""
    if [ "$AUTHBIND" = "yes" -a "$1" = "start" ]; then
        AUTHBIND_COMMAND="/usr/bin/authbind --deep /bin/bash -c "
    fi

    # Define the command to run Tomcat's catalina.sh as a daemon
    # set -a tells sh to export assigned variables to spawned shells.
    TOMCAT_SH="set -a; JAVA_HOME=\"$JAVA_HOME\"; source \"$DEFAULT\"; \
        CATALINA_HOME=\"$CATALINA_HOME\"; \
        CATALINA_BASE=\"$CATALINA_BASE\"; \
        JAVA_OPTS=\"$JAVA_OPTS\"; \
        CATALINA_PID=\"$CATALINA_PID\"; \
        CATALINA_TMPDIR=\"$CATALINA_TMPDIR\"; \
        LANG=\"$LANG\"; JSSE_HOME=\"$JSSE_HOME\"; \
        cd \"$CATALINA_BASE\"; \
        \"$CATALINA_SH\" $@"

    if [ "$AUTHBIND" = "yes" -a "$1" = "start" ]; then
        TOMCAT_SH="'$TOMCAT_SH'"
    fi

    # Run the catalina.sh script as a daemon
    set +e
    touch "$CATALINA_PID" "$CATALINA_BASE"/logs/catalina.out
    chown $TOMCAT8_USER "$CATALINA_PID" "$CATALINA_BASE"/logs/catalina.out
    start-stop-daemon --start -b -u "$TOMCAT8_USER" -g "$TOMCAT8_GROUP" \
        -c "$TOMCAT8_USER" -d "$CATALINA_TMPDIR" -p "$CATALINA_PID" \
        -x /bin/bash -- -c "$AUTHBIND_COMMAND $TOMCAT_SH"
    status="$?"
    set +a -e
    return $status
}

case "$1" in
  start)
    if [ -z "$JAVA_HOME" ]; then
        log_failure_msg "no JDK or JRE found - please set JAVA_HOME"
        exit 1
    fi

    if [ ! -d "$CATALINA_BASE/conf" ]; then
        log_failure_msg "invalid CATALINA_BASE: $CATALINA_BASE"
        exit 1
    fi

    log_daemon_msg "Starting $DESC" "$NAME"
    if start-stop-daemon --test --start --pidfile "$CATALINA_PID" \
        --user $TOMCAT8_USER --exec "$JAVA_HOME/bin/java" \
        >/dev/null; then

        # Regenerate POLICY_CACHE file
        umask 022
        echo "// AUTO-GENERATED FILE from /etc/tomcat8/policy.d/" \
            > "$POLICY_CACHE"
        echo ""  >> "$POLICY_CACHE"
        cat $CATALINA_BASE/conf/policy.d/*.policy \
            >> "$POLICY_CACHE"

        # Remove / recreate JVM_TMP directory
        rm -rf "$JVM_TMP"
        mkdir -p "$JVM_TMP" || {
            log_failure_msg "could not create JVM temporary director
y"
            exit 1
        }
        chown $TOMCAT8_USER "$JVM_TMP"

        catalina_sh start $SECURITY
        sleep 5
            if start-stop-daemon --test --start --pidfile "$CATALINA_PID" \
            --user $TOMCAT8_USER --exec "$JAVA_HOME/bin/java" \
            >/dev/null; then
            if [ -f "$CATALINA_PID" ]; then
                rm -f "$CATALINA_PID"
            fi
            log_end_msg 1
        else
            log_end_msg 0
        fi
    else
            log_progress_msg "(already running)"
        log_end_msg 0
    fi
    ;;
  stop)
    log_daemon_msg "Stopping $DESC" "$NAME"

    set +e
    if [ -f "$CATALINA_PID" ]; then
        start-stop-daemon --stop --pidfile "$CATALINA_PID" \
            --user "$TOMCAT8_USER" \
            --retry=TERM/20/KILL/5 >/dev/null
        if [ $? -eq 1 ]; then
            log_progress_msg "$DESC is not running but pid file exis
ts, cleaning up"
        elif [ $? -eq 3 ]; then
            PID="`cat $CATALINA_PID`"
            log_failure_msg "Failed to stop $NAME (pid $PID)"
            exit 1
        fi
        rm -f "$CATALINA_PID"
        rm -rf "$JVM_TMP"
    else
        log_progress_msg "(not running)"
    fi
    log_end_msg 0
    set -e
    ;;
   status)
    set +e
    start-stop-daemon --test --start --pidfile "$CATALINA_PID" \
        --user $TOMCAT8_USER --exec "$JAVA_HOME/bin/java" \
        >/dev/null 2>&1
    if [ "$?" = "0" ]; then

        if [ -f "$CATALINA_PID" ]; then
            log_success_msg "$DESC is not running, but pid file exists."
            exit 1
        else
            log_success_msg "$DESC is not running."
            exit 3
        fi
    else
        log_success_msg "$DESC is running with pid `cat $CATALINA_PID`"
    fi
    set -e
        ;;
  restart|force-reload)
    if [ -f "$CATALINA_PID" ]; then
        $0 stop
        sleep 1
    fi
    $0 start
    ;;
  try-restart)
        if start-stop-daemon --test --start --pidfile "$CATALINA_PID" \
        --user $TOMCAT8_USER --exec "$JAVA_HOME/bin/java" \
        >/dev/null; then
        $0 start
    fi
        ;;
  *)
    log_success_msg "Usage: $0 {start|stop|restart|try-restart|force-reload|
status}"
    exit 1
    ;;
esac

exit 0
You can check folder /etc/tomcat8 and compare them with its default https://packages.debian.org/jessie-backports/all/tomcat8/filelist

Tuesday, July 7, 2015

Tomcat 6.x User Roles

file name [tomcat 6 folder]//conf/tomcat-users.xml
Available Rules
  • <role rolename="manager-gui"/>
  • <role rolename="manager-script"/>
  • <role rolename="manager-jmx"/>
  • <role rolename="manager-status"/>
WARNING: users with the manager-gui role should not be granted either the manager-script or manager-jmx roles
Example configuration
<tomcat-users>
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jmx"/>
  <role rolename="manager-status"/>
  <user username="example" password="example" roles="manager-gui"/>
</tomcat-users>