MVC in Eclipse.

Introduction

Let's make a sample program of MVC in Eclipse.

Development environment

Windows 10 Pro 1709(16299.192) Eclipse pleiades-4.7.3 java 1.8.0_162

procedure

    1. Install Eclipse Pleiades All in One I want to use it in other languages later, so I will install the full version. "Ultimate": Can be developed in other than Java (C / C ++, Python ...) "Full Edition": Includes compiler and execution environment
  1. Creating a dynamic web project

    1. "Hello World" in Servlet
  2. "Employee list display" in MVC M (Model): JavaBeans (Java class)    V(View) : JSP C (Controller): Servlet (Java class)

1. 1. Install Eclipse Pleiades All in One

URL

http://mergedoc.osdn.jp/

Installation procedure

1. Click "Eclipse 4.7 Oxygen"

image.png

2. Change the mirror server (because it may time out in 3.)

image.png

3. Click "Ultimate" "Full Edition" of Windws 64bit

image.png

4. Unzip the download file into your working folder

image.png

2. Creating a dynamic web project

Start Eclipse

1. Double-click "eclipse.exe"

image.png

2. Click the "Start" button

New project generation

3. Select "File"-> "New"-> "Other" menu

image.png

4. Select "Dynamic Web Project" and click the "Next" button.

image.png

5. Enter the "Project Name", select "Tomcat8", and click the "Next" button.

image.png

6. Click the "Next" button

image.png

7. Check "Generate web.xml Deployment Descriptor" and click "Finish" button.

image.png

3. 3. "Hello World" in Servlet

1) Create Servlet

1. Select "File"-> "New"-> "Other" menu

image.png

2. Select "Jakarta" and click the "Next" button.

image.png

3. Enter the "Java Package" and "Class Name" and click the "Finish" button.

image.png

4. Open the created Servlet class and add one line

response.getWriter().append("\nHello World !!"); 

image.png

2) Operation check

1. Select the "Run"-> "Run"-> "Run on Server" menu

image.png

2. Select "Tomcat 8.0 server", check "Always use this server when running this project", and click the "Finish" button.

image.png

3. Enter the URL on your browser

http://localhost:8080/SampleMVC/ShowHelloWorld

image.png

4. Check the definition of the URL path (http: // localhost / SampleMVC / ShowHelloWorld)

SampleMVC :The project name is defined in the Tomcat configuration file when selecting the server to use

image.png

ShowHelloWorld :URL mapping when creating a Servlet Java file,@WebServlet("/ShowHelloWorld")Defined as

image.png

4. "Employee list display" in MVC

0) JSTL download

1. Download taglibs-standard-impl-1.2.5.jar, taglibs-standard-jstlel-1.2.5.jar, taglibs-standard-spec-1.2.5.jar

http://tomcat.apache.org/download-taglibs.cgi

image.png

2. Copy to WEB-INF \ lib of the project

image.png

1) Model (JavaBeans) creation

1. Select "File"-> "New"-> "Class" menu

image.png

2. Enter the "Java Package" and "Class Name" and click the "Finish" button.

image.png

3. Code creation

package emp;

public class EmployeeBean {
    private String id            = "";
    private String name          = "";
    private String email         = "";

    public void setId(String id){
        this.id = id;
    }

    public String getId(){
        return this.id;
    }

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return this.name;
    }

    public void setEmail(String email){
        this.email = email;
    }

    public String getEmail(){
        return this.email;
    }
}

2) Create Servlet (Controller)

1. Select "File"-> "New"-> "Other" menu

image.png

2. Select "Jakarta" and click the "Next" button.

image.png

3. Enter the "Java Package" and "Class Name" and click the "Next" button.

image.png

4. Set the Servlet deployment identifier name, check the URL mapping, and click the "Finish" button.

image.png

5. Code generation

package emp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class EmployeeServlet
 */
@WebServlet(name = "EmpList", urlPatterns = { "/EmpList" })
public class EmployeeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

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

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    //Model generation
		List<EmployeeBean> employeeList = new ArrayList<EmployeeBean>();
		EmployeeBean bean = new EmployeeBean();
	    bean.setId("00001");
	    bean.setName("Hayako Sato");
	    bean.setEmail("[email protected]");
	    employeeList.add(bean);

	    bean =  new EmployeeBean();
	    bean.setId("00002");
	    bean.setName("Taro Suzuki");
	    bean.setEmail("[email protected]");
	    employeeList.add(bean);

	    bean =  new EmployeeBean();
	    bean.setId("00003");
	    bean.setName("Ryo Ikeda");
	    bean.setEmail("[email protected]");
	    employeeList.add(bean);

	    //Pass Model to View
	    request.setAttribute("employeeList", employeeList);

	    //Show View
	    this.getServletContext()
	        .getRequestDispatcher("/employeeList.jsp")
	        .forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Model generation
		Map<String, EmployeeBean> employeeMap = new HashMap<String, EmployeeBean>();
		EmployeeBean bean = new EmployeeBean();
	    bean.setId("00001");
	    bean.setName("Hayako Sato");
	    bean.setEmail("[email protected]");
	    employeeMap.put(bean.getId(), bean);

	    bean =  new EmployeeBean();
	    bean.setId("00002");
	    bean.setName("Taro Suzuki");
	    bean.setEmail("[email protected]");
	    employeeMap.put(bean.getId(), bean);

	    bean =  new EmployeeBean();
	    bean.setId("00003");
	    bean.setName("Ryo Ikeda");
	    bean.setEmail("[email protected]");
	    employeeMap.put(bean.getId(), bean);

		String id = request.getParameter("id");
		List<EmployeeBean> employeeList = new ArrayList<EmployeeBean>();
		if (id.isEmpty()) {
			for (Map.Entry<String, EmployeeBean> entry : employeeMap.entrySet()) {
				employeeList.add(entry.getValue());
			}

		}
		else {
			employeeList.add(employeeMap.get(id));
		}

	    //Pass Model to View
		request.setAttribute("employeeList", employeeList);


		//Show View
	    this.getServletContext()
	        .getRequestDispatcher("/employeeList.jsp")
	        .forward(request, response);

	}

}

3) View (JSP) creation

1. Select "File"-> "New"-> "Other" menu

image.png

2. Select "JSP File" and click the "Next" button.

image.png

4. Enter the "Folder" and "File name" and click the "Finish" button.

image.png

5. Code generation

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Employee list</title>
	</head>
	<body>

		<form action="EmpList" method="post">
			<p>
				ID:<input type="text" name="id">
			</p>
			<p>
				<input type="submit" value="Send">
				<input type="reset" value="Reset your input">
			</p>
		</form>


		<table>
			<caption>
				<strong>Employee list</strong>
			</caption>
			<thead>
				<tr>
					<th>ID</th>
					<th>NAME</th>
					<th>EMAIL</th>
				</tr>
			</thead>
			<tbody>
				<c:forEach items="${employeeList}" var="emp" >
					<tr>
						<th><c:out value="${emp.id}" /></th>
						<td><c:out value="${emp.name}" /></td>
						<td><c:out value="${emp.email}" /></td>
					</tr>
				</c:forEach>
			</tbody>
		</table>

	</body>
</html>

4) Operation check

1. Select the "Run"-> "Run"-> "Run on Server" menu

image.png

2. Enter the URL on your browser

http://localhost:8080/SampleMVC/EmpList

image.png

3. You can search by ID

image.png

image.png

4. If no ID is entered, all items will be displayed.

image.png

image.png

in conclusion

--EmployeeBean accessors (setXxx (), getXxx ()) can be omitted using lombok.

--When you enter the URL ( http: // localhost: 8080 / SampleMVC / EmpList), call the EmployeeServlet.doGet () method.

--When you click the "Send" button, call the EmployeeServlet.doPost () method.

--The HashMap class cannot retrieve elements in the order they were put. You can use LinkedHashMap to retrieve them in the order they were inserted.

Recommended Posts

MVC in Eclipse.
To debug in eclipse
Install the plugin in Eclipse
Null-safe program in Java (Eclipse)
First Java development in Eclipse
Using Amateurs UML in Eclipse
eclipse all in one installation
Install tomcat plugin in eclipse
Introduction of javaFX in Eclipse (April 2020)
Spring Boot Hello World in Eclipse
Spring Boot application development in Eclipse
How to run JUnit in Eclipse
Use the Findbugs plugin in Eclipse
Hello World in java in eclipse now
Create a Servlet program in Eclipse
CRUD features and MVC in Rails
Use completion in Eclipse on mac
How to set Lombok in Eclipse
JPA (Java Persistence API) in Eclipse
Eclipse error
Building a Lambda development environment in Eclipse
Get in touch with Eclipse MicroProfile Health
How to include Spring Tool in Eclipse 4.6.3?
Enjoy JUnit 5 in Eclipse before official release
Enable code completion in Eclipse for Mac
[Java] Set AdoptOpen JDK in STS (Eclipse)
Play Framework 2.6 (Java) environment construction in Eclipse
MVC model
How Dispatcher servlet works in Spring MVC
Open multiple workspaces in Eclipse on Mac
Maven configuration problem in Spring pom.xml in Eclipse
[For beginners] How to debug in Eclipse
Eclipse --Springboot
[For beginners] I tried using DBUnit in Eclipse
Test controller with Mock MVC in Spring Boot
[JavaFX] How to write Eclipse permissions in build.gradle
Eclipse Pleiades All in One for Mac released
How to color code console output in Eclipse
Technology for reading Java source code in Eclipse
[For beginners] I tried using JUnit 5 in Eclipse
[Java] API creation using Jerjey (Jax-rs) in eclipse
Create a simple batch processing framework in Eclipse.
When the server fails to start in Eclipse
Prepare for log output using log4j in Eclipse.
[Eclipse / Tomcat] Servlet + JSP in Maven webapp project
[Note] Struts2 environment construction using Gradle in Eclipse
Allow development in Eclipse environment using iPLAss SDK
Automatically modify and save coding conventions in Eclipse
When the project is not displayed in eclipse
Tips for generating files for eclipse projects in Gradle
How to automatically generate a constructor in Eclipse