Faisons un exemple de programme de MVC avec Eclipse.
Windows 10 Pro 1709(16299.192) Eclipse pleiades-4.7.3 java 1.8.0_162
Créer un projet Web dynamique
"Affichage de la liste des employés" dans MVC M (modèle): JavaBeans (classe Java) V(View) : JSP C (contrôleur): Servlet (classe Java)
URL
http://mergedoc.osdn.jp/














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



http://localhost:8080/SampleMVC/ShowHelloWorld

SampleMVC :Le nom du projet est défini dans le fichier de configuration Tomcat lors de la sélection du serveur à utiliser

ShowHelloWorld :Mappage d'URL lors de la création d'un fichier Java de servlet,@WebServlet("/ShowHelloWorld")Défini comme

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




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;
    }
}




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 {
	    //Génération de modèle
		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);
	    //Passer le modèle à la vue
	    request.setAttribute("employeeList", employeeList);
	    //Afficher la vue
	    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 {
		//Génération de modèle
		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));
		}
	    //Passer le modèle à la vue
		request.setAttribute("employeeList", employeeList);
		//Afficher la vue
	    this.getServletContext()
	        .getRequestDispatcher("/employeeList.jsp")
	        .forward(request, response);
	}
}



<%@ 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>Liste des employés</title>
	</head>
	<body>
		<form action="EmpList" method="post">
			<p>
				ID:<input type="text" name="id">
			</p>
			<p>
				<input type="submit" value="Envoyer">
				<input type="reset" value="Réinitialisez votre entrée">
			</p>
		</form>
		<table>
			<caption>
				<strong>Liste des employés</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>

http://localhost:8080/SampleMVC/EmpList





--Lorsque vous entrez l'URL (  http: // localhost: 8080 / SampleMVC / EmpList ''), appelez la méthode EmployeeServlet.doGet ().
--Lorsque vous cliquez sur le bouton "Envoyer", appelez la méthode EmployeeServlet.doPost ().
Recommended Posts