読者です 読者をやめる 読者になる 読者になる

似非プログラマのうんちく

「似非プログラマの覚え書き」出張版

MyBatis + Guice でカンタン DAO 実装(その 3)

Java MyBatis Guice

Servlet の作成

DAO の使い方の例として。

package jp.mydns.akanekodou;

import java.io.IOException;

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

import java.util.List;

import jp.mydns.akanekodou.bean.City;
import jp.mydns.akanekodou.dao.CityDAO;
import jp.mydns.akanekodou.dao.util.DaoUtil;

@WebServlet("/list")
@SuppressWarnings("serial")
public class ListServlet extends HttpServlet {
    @Override
    protected void doGet(
        HttpServletRequest request,
        HttpServletResponse response
    ) throws ServletException, IOException {
        CityDAO dao = DaoUtil.getDao(CityDAO.class);

        List<City> citylist = dao.all();
        request.setAttribute("citylist", citylist);

        getServletContext()
            .getRequestDispatcher("/list.vm")
            .forward(request, response);
    }
}
package jp.mydns.akanekodou;

import java.io.IOException;

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

import jp.mydns.akanekodou.bean.City;
import jp.mydns.akanekodou.dao.CityDAO;
import jp.mydns.akanekodou.dao.util.DaoUtil;

@WebServlet("/detail")
@SuppressWarnings("serial")
public class DetailServlet extends HttpServlet {
    @Override
    protected void doGet(
        HttpServletRequest request,
        HttpServletResponse response
    ) throws ServletException, IOException {
        getServletContext()
            .getRequestDispatcher("/error.html")
            .forward(request, response);
    }

    @Override
    protected void doPost(
        HttpServletRequest request,
        HttpServletResponse response
    ) throws ServletException, IOException {
        CityDAO dao = DaoUtil.getDao(CityDAO.class);

        int id = Integer.parseInt(request.getParameter("id"));
        City city = dao.find(id);
        request.setAttribute("city", city);

        getServletContext()
            .getRequestDispatcher("/detail.vm")
            .forward(request, response);
    }
}