[Eclipse / Tomcat] Servlet + JSP in Maven webapp project

Previously, I created a web application project with "Tomcat project" in Create memo application with Tomcat + JSP + Servlet + MySQL using Eclipse. I made it because it is better to select maven-archetype-webapp as the archetype in the Maven project and create the project.

Reference: Exporting the project and war file when creating server-side Java in Eclipse

Project settings

maven-archetype-webapp project creation

Select "Maven Project"

image.png

Uncheck "Create a simple project (S)" __ "Next"

image.png

Select "maven-archtype-webapp" as the archetype

image.png

image.png

Directory structure

initial state

image.png

In the project configuration immediately after creation, src / main / java and src / test / java of the directory for the source file are missing, so this is created manually from the folder of the new creation menu or Explorer etc. To do.

image.png

(This is not output as an error for some reason)

Java version setting

If you create a Maven project in Eclipse, it's a specification that Java 1.5 settings are used. ..

System library

Since "JRE System Library" is "J2SE-1.5", select "JavaSE-1.8 (java8)" from the right-click properties.

image.png

Project facets

Then I get the error "Does not match Java project facet version"

image.png

Open the project properties and set the version to 1.8 from "Project Facets"

image.png

Maven compiler version

Specify the compiler version when doing maven build separately from the JDK version in Eclipse.

image.png

The following is described directly under <project> of the root element. (You may enter it by hand)

pom.xml


 <properties>
  <java.version>1.8</java.version>
  <maven.compiler.source>1.8</maven.compiler.source>
  <maven.compiler.target>1.8</maven.compiler.target>
 </properties>

Without this, for example, source code using collections will result in an error because the 1.5 version of the compiler does not support it.

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.395 s
[INFO] Finished at: 2018-12-23T16:03:11+09:00
[INFO] Final Memory: 9M/245M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project memoapp2: Compilation failure
[ERROR] /C:/Users/zaki/src/java-study/memoapp2/src/main/java/jp/example/www/MainServlet.java:[30,51]Diamond operator-source 1.Not supported in 5
[ERROR](To enable the diamond operator-Please use source 7 or later)
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Include Servlet jar in Maven

I'm getting the error (from the beginning) that the superclass "javax.servlet.http.HttpServlet" was not found in the Java build path, because the Servlet-related libraries are not referenced in the project.

Set using Maven.

The jar file of Java Servlet API is set. To incorporate the latest Java Servlet API 4.0.1 from the link as of December 2018 into the project, Maven tab Copy the contents of the XML displayed in to the <dependencies> ~ </ dependencies> part of pom.xml

image.png

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>

Copy and paste this content into the project's pom.xml

image.png

Now when you save the file, the servlet-api will be automatically downloaded and included in the project according to the contents of the file.

If the process completes successfully, the error that HttpServlet is not found in the build path will be resolved.

Display of JSP

At this point, select Tomcat from "Run"-> "Run on Server" in the right-click menu of the project, check that the resources configured on the server include the target project, and execute it. The contents of ʻindex.jsp` included when the project was created can be displayed on the browser.

image.png

image.png

image.png

However, it is not preferable to configure the jsp file in a location that is directly accessed from the browser, so move to any path under src / main / webapp / WEB-INF (such as WEB-INF / jsp) and directly Make it inaccessible and display it via Servlet.

Creating and displaying a Servlet

From "Servlet" in the new menu.

image.png

image.png

After entering the package name and class name, you can also enter meta information.

image.png

Choosing which method to override

image.png

The value of the meta information entered here is also reflected in src / main / webapp / WEB-INF / web.xml

web.xml(initial value)


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
</web-app>

web.xml(After addition)


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
  	<servlet-name>MainServlet</servlet-name>
  	<display-name>MainServlet</display-name>
  	<description>Main screen</description>
  	<servlet-class>jp.example.www.MainServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>MainServlet</servlet-name>
  	<url-pattern>/MainServlet</url-pattern>
  </servlet-mapping>
</web-app>

The Servlet source is created with the specified method overridden.

package jp.example.www;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MainServlet
 */
public class MainServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MainServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("webapp-maven! Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

Even in the state immediately after creation, if you start (or restart) Tomcat with "Run (R)"-> "Run on server", it will be executed with the contents of the automatically generated code

image.png

Calling JSP from Servlet

[For Tomcat project](https://qiita.com/zaki-lknr/items/32690b071abf202281d6#%E3%83%A1%E3%82%A4%E3%83%B3%E7%94%BB%E9% 9D% A2% E3% 81% AEui% E3% 81% A8% E5% 87% A6% E7% 90% 86% E9% 83% A8% E5% 88% 86% E3% 82% 92% E4% BD% Same as 9C% E6% 88% 90% E3% 81% 99% E3% 82% 8B).

For the jsp file of /WEB-INF/jsp/main.jsp, it will be displayed if you write the following withdoGet ()of the servlet.

        String path = "/WEB-INF/jsp/main.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(path);
        dispatcher.forward(request, response);

maven install and war files

By executing "Run (R)"-> "Maven install", a war file will be generated directly under the target directory.

image.png

If you execute "Maven clean", all build results will be erased.

War file creation by export

You can also create a war file by selecting "Export" from the project menu.

image.png

In this case, it can be created regardless of Maven and can be output to any path.

Recommended Posts

[Eclipse / Tomcat] Servlet + JSP in Maven webapp project
About [servlet] [JSP] [tomcat]
Introduce Maven to Tomcat project
Install tomcat plugin in eclipse
Create a tomcat project using Eclipse Pleiades All in One
Create a tomcat project using Eclipse
Create a Servlet program in Eclipse
Added slf4J + logback to Eclipse Maven project
Maven configuration problem in Spring pom.xml in Eclipse
CI for Maven project in Azure Pipelines
Run JUnit and Spock in a maven project
When the project is not displayed in eclipse
JSP on tomcat
MVC in Eclipse.
Create a Java Servlet and JSP WAR file to deploy to Apache Tomcat 9 in Gradle
The right way to see the tomcat source in eclipse
How to switch Tomcat context.xml with WTP in Eclipse