- package controller;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import dto.User;
- /**
- *Servlet implementation class UserList
- */
- @WebServlet(“/user”)
- public class UserListServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- /**
- *@see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- List userList = new ArrayList<>();
- userList.add(new User(“山田”, 25));
- userList.add(new User(“佐藤”, 27));
- userList.add(new User(“田中”, 21));
- request.setAttribute(“userList”, userList); request.getRequestDispatcher(“/WEB-INF/view/user.jsp”).forward(request, response);
- }
- }
User.java
- package dto;
- public class User {
- private String name;
- private int age;
- public User(String name, int age) {
- this.name = name;
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
user.jsp
- <%@ page pageEncoding=”UTF-8″%>
- <%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %>
- <%@ taglib prefix=”fmt” uri=”http://java.sun.com/jsp/jstl/fmt” %>
- <html>
- <head></head>
- <body>
- <h1>生徒名簿</h1>
- <table border=”1″>
- <tr>
- <th>番号</th>
- <th>名前</th>
- <th>年齢</th>
- </tr>
- <c:forEach items=”${userList}” var=”user” varStatus=”vs”>
- <tr>
- <td><c:out value=”${vs.count}” /></td>
- <td><c:out value=”${user.name}” /></td>
- <td><c:out value=”${user.age}” />才</td>
- </tr>
- </c:forEach>
- </table>
- </body>
- </html>