Skip to content

Commit 77f7864

Browse files
authored
Merge pull request #2 from bobocode-projects/GP-64_hello-servlet-api_MAIN
Gp 64 new date servlet api exercise main
2 parents 7bef299 + 5fb4e21 commit 77f7864

File tree

6 files changed

+285
-1
lines changed

6 files changed

+285
-1
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# <img src="https://raw.githubusercontent.com/bobocode-projects/resources/master/image/logo_transparent_background.png" height=50/>Welcome Date Servlet
2+
Your first acquaintance with Servlets, JSP and servlet Container 👀
3+
4+
[Servlets are the Java platform technology of choice for extending and enhancing Web servers.](https://www.oracle.com/java/technologies/servlet-technology.html)
5+
6+
### Pre-conditions ❗
7+
You're supposed to be familiar with [Java Fundamentals](https://github.com/bobocode-projects/java-fundamentals-course)
8+
9+
### Objectives
10+
* **install** [Apache Tomcat Container](https://tomcat.apache.org/download-90.cgi) if you didn't ✅
11+
12+
-*Servlets don’t have any main() method. Instead, are used Containers to control Servlets.
13+
Containers are other Java applications such as Tomcat, GlassFish or Jetty. You have to install one of it if you didn't.
14+
We suggest to use Tomcat as more lightweight and easier in configuration.*
15+
***configure a Container** depending on your environment ✅
16+
- [IntelliJ IDEA:](https://www.jetbrains.com/help/idea/run-debug-configuration-tomcat-server.html)
17+
1. Create a new server configuration:
18+
19+
**Run****Edit configurations...** ▶ (➕)Add New Configuration ▶ Tomcat Server (Local)
20+
2. Configure or choose Application Server in **Run/Debug Configurations**:
21+
22+
**Server** tab ▶ **Configure** ▶ (➕)**Add Application Server** ▶ Add a path to folder with Tomcat
23+
3. Deploy welcome-servlet application into Container in **Run/Debug Configurations**:
24+
25+
**Deployment** tab ▶ (➕)Artifact ▶ `welcome-servlet:war exploded` ▶ ❗ Clear **Application Context** field
26+
27+
- Eclipse
28+
- Open Eclipse Java EE (Enterprise edition ) environment. Click on Servers tab at bottom. Click on No servers are available.
29+
- A dialog box will appear. Select Tomcat 9.0 server folder. Click Next.
30+
- Browse to Apache Tomcat 9.0 folder select it. Click Finish.
31+
* **create a new Servlet** with a name `DateServlet`
32+
1. Create a new class `DateServlet` in the same package
33+
2. Extend the class from `HttpServlet`
34+
3. Annotate the class as `@WebServlet` with parameter `"/date""` to create a path to the servlet.
35+
4. Override `doGet` method to return present date in the response using `LocalDate.now()`.
36+
* **run `DateServletTest`** to check your code ✅
37+
* **run configured server**
38+
- If everything is configured properly, the server should run `WelcomeServlet` on [http://localhost:8080/](http://localhost:8080/)
39+
* **send request to `DateServlet`** using [http://localhost:8080/date](http://localhost:8080/date) URL in order to get present date ✅
40+
41+
### Related Materials ℹ️
42+
todo
43+
44+
---
45+
#### 🆕 First time here? – [See Introduction](https://github.com/bobocode-projects/java-fundamentals-course/tree/main/0-0-intro#introduction)
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<parent>
6+
<artifactId>2-0-servlet-api</artifactId>
7+
<groupId>com.bobocode</groupId>
8+
<version>1.0-SNAPSHOT</version>
9+
</parent>
10+
<modelVersion>4.0.0</modelVersion>
11+
12+
<artifactId>2-0-1-date-servlet-api</artifactId>
13+
<packaging>war</packaging>
14+
15+
<properties>
16+
<maven.compiler.source>11</maven.compiler.source>
17+
<maven.compiler.target>11</maven.compiler.target>
18+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
19+
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
20+
</properties>
21+
22+
<dependencies>
23+
<dependency>
24+
<groupId>org.mockito</groupId>
25+
<artifactId>mockito-core</artifactId>
26+
<version>3.8.0</version>
27+
<scope>test</scope>
28+
</dependency>
29+
<dependency>
30+
<groupId>org.mockito</groupId>
31+
<artifactId>mockito-junit-jupiter</artifactId>
32+
<version>3.8.0</version>
33+
<scope>test</scope>
34+
</dependency>
35+
</dependencies>
36+
37+
<build>
38+
<plugins>
39+
<plugin>
40+
<groupId>org.apache.maven.plugins</groupId>
41+
<artifactId>maven-war-plugin</artifactId>
42+
<version>3.3.0</version>
43+
</plugin>
44+
</plugins>
45+
</build>
46+
</project>
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.bobocode.servlet;
2+
3+
import javax.servlet.annotation.WebServlet;
4+
import javax.servlet.http.HttpServlet;
5+
import javax.servlet.http.HttpServletRequest;
6+
import javax.servlet.http.HttpServletResponse;
7+
import java.io.IOException;
8+
import java.io.PrintWriter;
9+
10+
/**
11+
* To create a servlet you have to extend your class from {@link HttpServlet}.
12+
* Also add annotation {@link WebServlet} with parameter to map a path for URL.
13+
*/
14+
@WebServlet("/")
15+
public class WelcomeServlet extends HttpServlet {
16+
17+
/**
18+
* This method is overridden from {@link HttpServlet} class.
19+
* It called by the server (container) to allow servlets to handle GET requests.
20+
*
21+
* @param request an {@link HttpServletRequest} object that contains the request
22+
* the client has made of the servlet.
23+
* @param response an {@link HttpServletResponse} object that contains the response
24+
* the servlet sends to the client.
25+
*/
26+
@Override
27+
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
28+
response.setContentType("text/html");
29+
30+
PrintWriter out = response.getWriter();
31+
32+
out.println("<html><body align=\"center\">");
33+
out.println("<img src=\"https://raw.githubusercontent.com/bobocode-projects/resources/2a3cf642ed8e5d2cc48c6d0dd9dfcdf220cb377c/image/logo_white.svg\" " +
34+
"alt=\"Bobocode\" width=\"500\">");
35+
out.println("<h1>" + "Good job! This page is a response of <code>WelcomeServlet</code> object." + "</h1>");
36+
out.println("<h2>" + "You should create your own class <code>DateServlet</code> which returns " +
37+
"current date as a response on <code>/date</code> path.<br> Use <code>LocalDate.now()</code> " +
38+
"to get current date." + "</h2>");
39+
out.println("</body></html>");
40+
}
41+
}
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
package com.bobocode;
2+
3+
import org.junit.jupiter.api.*;
4+
import org.junit.jupiter.api.extension.ExtendWith;
5+
import org.mockito.Mock;
6+
import org.mockito.junit.jupiter.MockitoExtension;
7+
import org.reflections.Reflections;
8+
9+
import javax.servlet.ServletOutputStream;
10+
import javax.servlet.annotation.WebServlet;
11+
import javax.servlet.http.HttpServlet;
12+
import javax.servlet.http.HttpServletRequest;
13+
import javax.servlet.http.HttpServletResponse;
14+
import java.io.IOException;
15+
import java.io.PrintWriter;
16+
import java.io.StringWriter;
17+
import java.lang.reflect.InvocationTargetException;
18+
import java.lang.reflect.Method;
19+
import java.time.LocalDate;
20+
import java.util.Optional;
21+
import java.util.Set;
22+
23+
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
24+
import static org.mockito.Mockito.verify;
25+
import static org.mockito.Mockito.when;
26+
27+
28+
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
29+
@ExtendWith(MockitoExtension.class)
30+
public class DateServletTest {
31+
32+
@Mock
33+
private HttpServletRequest request;
34+
35+
@Mock
36+
private HttpServletResponse response;
37+
38+
@Mock
39+
private ServletOutputStream outputStream;
40+
41+
private Object dateServletObject;
42+
private Class<?> dateServletClass;
43+
44+
public static final String SERVLET_PACKAGE = "com.bobocode.servlet";
45+
public static final String DATE_SERVLET = "DateServlet";
46+
Reflections reflections;
47+
48+
@BeforeEach
49+
public void init() throws ClassNotFoundException, IllegalAccessException, InvocationTargetException,
50+
InstantiationException {
51+
reflections = new Reflections(SERVLET_PACKAGE);
52+
dateServletClass = Class.forName(SERVLET_PACKAGE + "." + DATE_SERVLET);
53+
dateServletObject = dateServletClass.getConstructors()[0].newInstance();
54+
}
55+
56+
@Test
57+
@Order(1)
58+
void dateServletClassExists() throws ClassNotFoundException {
59+
Class.forName(SERVLET_PACKAGE + "." + DATE_SERVLET);
60+
}
61+
62+
@Test
63+
@Order(2)
64+
void dateServletExtendsHttpServlet() {
65+
66+
Set<Class<? extends HttpServlet>> httpServlets =
67+
reflections.getSubTypesOf(HttpServlet.class);
68+
69+
Optional<String> anyDateHttpServlet = httpServlets.stream()
70+
.map(Class::getSimpleName)
71+
.filter(servlet -> servlet.equals(DATE_SERVLET))
72+
.findAny();
73+
assertThat(anyDateHttpServlet).isNotEmpty();
74+
}
75+
76+
@Test
77+
@Order(3)
78+
void dateServletIsMarkedAsWebServlet() {
79+
Set<Class<?>> servlets =
80+
reflections.getTypesAnnotatedWith(WebServlet.class);
81+
Optional<String> anyMarkedDateServlet = servlets.stream()
82+
.map(Class::getSimpleName)
83+
.filter(servlet -> servlet.equals(DATE_SERVLET))
84+
.findAny();
85+
assertThat(anyMarkedDateServlet).isNotEmpty();
86+
}
87+
88+
@Test
89+
@Order(4)
90+
void dateServletIsMarkedWithProperPath() throws ClassNotFoundException {
91+
String[] value = Class.forName(SERVLET_PACKAGE + "." + DATE_SERVLET)
92+
.getAnnotation(WebServlet.class).value();
93+
assertThat(value).contains("/date");
94+
}
95+
96+
@Test
97+
@Order(5)
98+
void dateServletReturnsDateInResponse() throws IOException, NoSuchMethodException, InvocationTargetException,
99+
IllegalAccessException {
100+
Method doGetMethod = getDoGetMethod();
101+
102+
StringWriter stringWriter = new StringWriter();
103+
PrintWriter printWriter = new PrintWriter(stringWriter);
104+
when(response.getWriter()).thenReturn(printWriter);
105+
106+
doGetMethod.invoke(dateServletObject, request, response);
107+
assertThat(stringWriter.getBuffer().toString()).contains(LocalDate.now().toString());
108+
}
109+
110+
private Method getDoGetMethod() throws NoSuchMethodException {
111+
return dateServletClass
112+
.getMethod("doGet", HttpServletRequest.class, HttpServletResponse.class);
113+
}
114+
}

2-0-servlet-api/pom.xml

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,19 @@
1010
<modelVersion>4.0.0</modelVersion>
1111

1212
<artifactId>2-0-servlet-api</artifactId>
13+
<packaging>pom</packaging>
14+
<modules>
15+
<module>2-0-1-date-servlet-api</module>
16+
</modules>
17+
18+
19+
<dependencies>
20+
<dependency>
21+
<groupId>javax.servlet</groupId>
22+
<artifactId>javax.servlet-api</artifactId>
23+
<version>4.0.1</version>
24+
<scope>provided</scope>
25+
</dependency>
26+
</dependencies>
1327

1428
</project>

pom.xml

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,5 +23,29 @@
2323
<maven.compiler.target>11</maven.compiler.target>
2424
</properties>
2525

26-
26+
<dependencies>
27+
<dependency>
28+
<groupId>org.junit.jupiter</groupId>
29+
<artifactId>junit-jupiter-engine</artifactId>
30+
<version>5.7.0</version>
31+
<scope>test</scope>
32+
</dependency>
33+
<dependency>
34+
<groupId>org.junit.jupiter</groupId>
35+
<artifactId>junit-jupiter-params</artifactId>
36+
<version>5.7.0</version>
37+
<scope>test</scope>
38+
</dependency>
39+
<dependency>
40+
<groupId>org.assertj</groupId>
41+
<artifactId>assertj-core</artifactId>
42+
<version>3.18.1</version>
43+
<scope>test</scope>
44+
</dependency>
45+
<dependency>
46+
<groupId>org.reflections</groupId>
47+
<artifactId>reflections</artifactId>
48+
<version>0.9.12</version>
49+
</dependency>
50+
</dependencies>
2751
</project>

0 commit comments

Comments
 (0)