Skip to content
Snippets Groups Projects
Commit 7d77e368 authored by Morais Fonseca, Claudenir (UT-EEMCS)'s avatar Morais Fonseca, Claudenir (UT-EEMCS)
Browse files

Pratical session 2

parent d4b2ec6e
No related branches found
No related tags found
No related merge requests found
# Pokemon Trainer Database
The [Pokemon Trainer Database](https://gitlab.utwente.nl/claudenirmf/mod4-wp-2023-2024-pokemon) is a sample web
The [PokeApp](https://gitlab.utwente.nl/claudenirmf/mod4-wp-2023-2024-pokemon) is a sample web
application designed to teach web development concepts at
the [Data & Information module](https://www.utwente.nl/en/education/bachelor/programmes/technical-computer-science/study-programme/#modules-technical-computer-science)
of the [Technical Computer Science](https://www.utwente.nl/en/education/bachelor/programmes/technical-computer-science/)
......@@ -10,11 +10,7 @@ The contents of this repository are licensed
under [Creative Commons Attribution 4.0 International (CC-BY-4.0)](./LICENSE). Viewers are welcome to reuse its contents
and to submit their own contributions.
## Repository structure
- `/`:
## Class Diagram
![](./design/models/Class%20Diagram.png)
## External resources
......@@ -34,3 +30,5 @@ The following datasets and resources have been used in the development this proj
- GitHub: [@claudenirmf](https://github.com/claudenirmf)
- LinkedIn: [@claudenir-fonseca](https://www.linkedin.com/in/claudenir-fonseca/)
- E-mail: [c.moraisfonseca@utwente.nl](c.moraisfonseca@utwente.nl)
Additional contributions are welcome in the forms of issues and merge requests.
# Web Programming Practical Session 1
**Topic: Tool installation and project setup**
**Module 4: Data & Information (202101028)**
**Authors: Claudenir M. Fonseca, Wallace C. Ugulino, and Luis Ferreira Pires**
The objective of these exercises is to make you acquainted with some of the tools that will be used in this module. These exercises have been also designed to help you install the tools and give you initial hands-on experience with them.
Content:
- [Web Programming Practical Session 1](#web-programming-practical-session-1)
- [Java installation and configuration](#java-installation-and-configuration)
- [Maven installation](#maven-installation)
- [Tomcat installation](#tomcat-installation)
- [Creating a web application project on IntelliJ](#creating-a-web-application-project-on-intellij)
- [Common pitfalls and final remarks](#common-pitfalls-and-final-remarks)
## Java installation and configuration
For this module, we will be using Java's [JDK 17 LTS](https://en.wikipedia.org/wiki/Java_version_history#Java_17), which you are expected to be familiar with. Even though the Java language received significant updates recently, it is a rather retro-compatible language, so you should not face any difficulties by using a newer version, as long a you set the target environment accordingly. This is important to avoid incompatibilities collaboration and deployment issues, as we shall discuss later on.
> Due to changes in the licensing of Oracle JDK, please do NOT use it. Instead, use any of the open distributions available, such as [Adoptium's Temurin](https://adoptium.net/)
>
> Due to these licensing issues, you will also come across the name Jakarta, the name for Java EE now under control of the Eclipse Foundation in agreement with Oracle. Be careful with incompatibilities due to the new `jakarta` namespace on your dependencies.
In case Java is not yet installed in your machine, we list here a few resources that you can use depending on your development environment:
- ["How do I install Java on Windows?" by Cameron McKenzie](https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/How-do-I-install-Java-on-Windows)
- ["3 ways to install Java on macOS [2023]" by Andrew Hoog](https://www.andrewhoog.com/post/3-ways-to-install-java-on-macos-2023/)
- ["How to Install Java 17 LTS on Ubuntu 20.04" by Jeff Wilson](https://www.rosehosting.com/blog/how-to-install-java-17-lts-on-ubuntu-20-04/)
**Recommendations:**
- If you are a Shell user, do adopt the package manager of choice for your system (e.g., [Homebrew](https://brew.sh/), [Advanced Packaging Tool - APT](https://ubuntu.com/server/docs/package-management)).
- If you need to manage multiple JDK versions, a Java version management tool like [jEnv](https://www.jenv.be/) can greatly help you.
- If you struggle to connect IntelliJ to one of the JDKs on your machine, you can always download a JDK directly from the UI (may not be available on terminal).
## Maven installation
In this module, you will be using [Maven](http://maven.apache.org/) as the software project management tool of choice. Maven is extremely useful because it allows the management of code dependencies, like dependencies of libraries that are necessary to compile and run the software applications. In a sense, IntelliJ already does that, but Maven goes a step further by support the IDE, resolving dependencies from the web, and much more, making projects extremely portable.
Libraries are (binary) code that can be reused in a program, so that the programmer can concentrate on the task at hand. You should already know what a library is, but an example is the java.utils package that you have to import in order to use the Java collection classes. This package is quite stable, but other packages have more specific versions that you have to load to guarantee the compilation and execution of your code. Maven not only allows you to define the dependencies, but also downloads these packages from the Maven repository at (http://mvnrepository.com/), so it is very handy.
Maven prescribes a specific structure for the files in a project (source code, web resources
like HTML and CSS files, class files, etc.) and a pom.xml file that describes the Maven project. This repository is organized to mimic this structure also according to the recommendations on your Project Guide.
- `/design`: folder containing design files, such as UML diagrams, database schemas, OpenAPI specifications, prototypes (week 3).
- `/documents`: folder containing files such as project proposal, security report, or user manuals.
- `/meetings`: folder containing reports of each sprint; in our case it contains the guide for all practical sessions.
- `/src`: folder containing source files of the web application.
We refer students to [this Maven installation guide](https://www.baeldung.com/install-maven-on-windows-linux-mac), but Shell users should be comfortable with using their system's package managers instead (e.g., Homebrew, APT). The source files provided were tested with Maven 3.9.5, but recent version should suffice.
## Tomcat installation
In order to be executed, Web applications require a so called Application server, which can be considered as a special web server that knows how to handle the components of a web application (https://en.wikipedia.org/wiki/Application_server). In this module, we use the most popular Application server for Java applications, namely [Apache Tomcat](http://tomcat. apache.org/). In this module, we will be using [Tomcat 10](http://tomcat.apache.org), which is the version that will later be used for your project's deployment. You should download the ‘Core’ version that matches your OS and hardware (and Java installation), preferably one of the .zip files, and extract the contents of this .zip file to a directory that does not contain spaces in its name (Java does not like spaces). For example, you can create a directory Development in the root of the C: disk and extract the Tomcat installation to this directory. In Windows, after extracting Tomcat to the `C:\Development\` directory, the path to my Tomcat installation became `C:\Development\apache-tomcat-10.1.20`.
You can test the Tomcat installation by starting up the Application server and accessing the welcome page of the server through a browser. The script programs to startup and shutdown Tomcat can be found in the bin directory of the Tomcat installation (e.g., `startup.sh` and `startup.bat` for Linux/MacOS and Windows, respectively). Start up Tomcat by running the script that matches your machine. If everything goes well, Tomcat will return the values of environment variables `CATALINA_BASE`, `CATALINA_HOME`, etc. before starting up. You can now test the server by starting a browser and going to the page `http://localhost:8080`.
For Linux and MacOS you may have to add execution permissions to the scripts of the bin directory of the Tomcat installation, e.g., with command `chmod 755 +x`, or run these scripts as administrator with sudo. Normally, only the scripts `startup.sh`, `shutdown.sh` and `catalina.sh` have to get these permissions.
If Tomcat is properly installed, you should see a page similar to the one in the figure below.
![Tomcat initial page after successful installation.](./resources/session-1-tomcat-home.png)
After that don’t forget to shutdown Tomcat with the proper script program (`shutdown.sh` and `shutdown.bat` for Linux/MacOS and Windows, respectively). Make sure you always properly shutdown the server when you want to stop it.
## Creating a web application project on IntelliJ
The IntelliJ IDEA channel on YouTube provides a great step-by-step guide on how to create your first Java web application with Tomcat, already setting up most of your Maven dependencies (including JUnit) and the core of the folder structure recommended for your project.
> For the purposes of this practical session, cloning this repository into your machine and opening its root directory as an IntelliJ project will already configure most things for deployment. Still, create a web application first, such that IntelliJ has already the path to your Tomcat and JDK installations.
[![](http://img.youtube.com/vi/ThBw3WBTw9Q/0.jpg)](http://www.youtube.com/watch?v=ThBw3WBTw9Q)
["Tomcat in IntelliJ IDEA Ultimate" by Dalia Abo Sheasha](http://www.youtube.com/watch?v=ThBw3WBTw9Q)
<!-- ["Tomcat in IntelliJ IDEA Ultimate" by Dalia Abo Sheasha![](http://img.youtube.com/vi/ThBw3WBTw9Q/0.jpg)](http://www.youtube.com/watch?v=ThBw3WBTw9Q) -->
After creating a project, please perform the following procedures:
1. On your `pom.xml` file, upgrade the version of all Jersey dependencies to 3.1.6 or greater for compatibility with Jakarta 10
```xml
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>3.1.6</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>3.1.6</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>3.1.6</version>
</dependency>
```
2. On your `pom.xml` file, add the build below to simplify your build file's name.
```xml
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
<configuration>
<filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
</configuration>
</plugin>
</plugins>
</build>
```
3. If you are read/writing JSON files, remember to add a dependency to your `pom.xml`, such as [FasterXML Jackson](https://github.com/FasterXML/jackson):
```xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.0</version>
</dependency>
```
4. This tutorial creates a Jakarta REST server, so remember to add a folder `src/main/webapp` to contain your HTML, CSS, JavaScript, and other resources.
<!-- ## Test-based design in Maven -->
<!-- ### Adding the JUnit dependency -->
<!-- ### Defining a test case -->
<!-- ### Running tests -->
<!-- ## Implementing a web application -->
<!-- ### Deploying your application with IntelliJ -->
<!-- ### Deploying your application on Tomcat -->
<!-- ### Testing your application -->
<!-- ## Uploading your Maven project to GitLab -->
<!-- ### Preparation -->
<!-- ### Creating and populating the local Git repository -->
<!-- ### IntelliJ projects and Git -->
<!-- ## Celsius to Fahrenheit translator -->
<!-- ## Additional exercises -->
## Common pitfalls and final remarks
- Do not use annotations and configuration files (`WEB-INF/web.xml`) to configure your Servlets as to avoid inconsistent declaration.
- After adding files to your `src/main/resources` or `src/main/webapp` folders, check whether they are present in your build folder (`/target/classes` and `target/{artifactId}`, respectively). If IntelliJ's build fails to execute `mvn clean install`, you won't be able to access your files on Tomcat server which contains a copy of your build file (more specifically, `target/{artifactId}.war`). Running Maven directly on your terminal will should never fail.
- Whenever working from your IDE, remember to update the reload your Maven after any modification to your dependencies. This can be done in several ways, including *1 - right clicking the `pom.xml` file on the project explorer, then 2 - clicking the context menu 'Maven > Reload project'*
Do you have comments or suggestions on how to improve this repository and the practical sessions? Then visit our [repository on GitLab](https://gitlab.utwente.nl/claudenirmf/mod4-wp-2023-2024-pokemon) and submit an [issue](https://gitlab.utwente.nl/claudenirmf/mod4-wp-2023-2024-pokemon/-/issues) or a [pull/merge request](https://gitlab.utwente.nl/claudenirmf/mod4-wp-2023-2024-pokemon/-/merge_requests).
meetings/resources/session-1-tomcat-home.png

1.01 MiB

......@@ -9,7 +9,7 @@ import nl.utwente.mod4.pokemon.dao.TrainerDao;
import java.io.IOException;
@WebListener
public class Listenner implements ServletContextListener {
public class InitializationListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("Initializing PokeApp...");
......
......@@ -6,6 +6,6 @@
version="3.1">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>pokemonTypes.html</welcome-file>
</welcome-file-list>
</web-app>
\ No newline at end of file
src/main/webapp/favicon.ico

33.7 KiB

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>Hello there</p>
<img src="/pokemon/images/red.png" style="height: 150px"/>
<img src="/pokemon/images/abra.png" style="height: 150px"/>
<form action="/pokemon/api/trainers">
<input type="submit" value="Trainers" />
</form>
<form action="/pokemon/api/pokemonTypes">
<input type="submit" value="Pokemon Types" />
</form>
</body>
</html>
\ No newline at end of file
let pokemonTypes = {};
let tableParentId = 'table';
let detailsParentId = 'details';
function getRowId(resource) {
return `${resource.id}_row`
}
function updateDetails(pokemonTypeId) {
const pt = pokemonTypes?.data?.find(item => item.id === pokemonTypeId);
const parent = document.getElementById(detailsParentId);
parent.innerHTML = `
<div class="card" id="${pt.id}_card">
<img src="${pt.imgUrl}" class="card-img-top" alt="${pt.classification}">
<div class="card-body">
<h5 class="card-title">${pt.name} #${pt.pokedexNumber}</h5>
<p class="card-text">
Japanese name: ${pt.japaneseName} </br>
Classification: ${pt.classification} </br>
Abilities: ${pt.abilities?.join(", ") || "none"} </br>
Type: ${pt.primaryType}${pt.secondaryType ? " , " + pt.secondaryType : ""}
</p>
</div>
</div>
`
}
function pokemonTypeToRow(pokemonType) {
return `
<tr id="${getRowId(pokemonType)}" onclick="updateDetails('${pokemonType?.id?.trim()}')">
<th scope="row">${pokemonType.id}</th>
<td>${pokemonType.name}</td>
<td>#${pokemonType.pokedexNumber}</td>
<td>${pokemonType.primaryType}</td>
<td>${pokemonType.secondaryType || '-'}</td>
</tr>
`
}
function createPokemonTypesTable() {
const tableParent = document.getElementById(tableParentId);
tableParent.innerHTML = `
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Pokedex Number</th>
<th scope="col">Primary Type</th>
<th scope="col">Secondary Type</th>
</tr>
</thead>
<tbody>
${
pokemonTypes.data.map(resource => `${pokemonTypeToRow(resource)}`).join("\n")
|| "no data"
}
</tbody>
</table>
`
}
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"
integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<title>Title</title>
<link rel="icon" type="image/x-icon" href="/pokemon/favicon.ico">
</head>
<body>
<script src="js/requests.js"></script>
<script>
tableParentId = "tableDiv";
detailsParentId = "detailsDiv";
fetch('/pokemon/api/pokemonTypes')
.then(res => res.json())
.then(data => {
pokemonTypes = data;
createPokemonTypesTable();
})
.catch(err => {
console.error(`Unable to fetch Pokemon Types: ${err.status}`);
console.error(err);
});
</script>
<h1>Pokemon Types</h1>
<div class="container">
<div class="row">
<div id="tableDiv" class="col-8">No data</div>
<div id="detailsDiv" class="col-4">No data</div>
</div>
</div>
</body>
</html>
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment