概要
エンティティモデル(Bean)に設定したデータは
JSPタグを用いてブラウザ画面に表示できる。
Java
ロジックとBeanを以下に記載する。
ロジック
Javaプログラム内でBeanにデータをセットする。
import bean.BeanSample;
public class BeanController extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletRespons e resp)
throws ServletException, IOException {
ArrayList<BeanSample> beans = new ArrayList<BeanSample>();
BeanSample bean = new BeanSample();
bean.setBeanId("001");
beans.add(bean);
req.setAttribute("beanData", beans.get(0));
RequestDispatcher rd = req.getRequestDispatcher("/beanSample.jsp");
rd.forward(req, resp);
}
}
Bean
BeanはGetter/Setterメソッドを用意する。
public class BeanSample {
String beanId = null;
public String getBeanId() {
return beanId;
}
public void setBeanId(String beanId) {
this.beanId = beanId;
}
}
JSP
「jsp:useBean」、「jsp:getProperty」タグを見てほしい。
各タグの要素は以下を指定している。
id:BeanControllerにてsetAttributeで設定した"BeanData"
class:「bean.BeanSample」はBeanの完全限定クラス名
property:BeanSample定義しているメンバ変数
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ビーンサンプル</title>
</head>
<body>
<jsp:useBean id="beanData" class="bean.BeanSample" scope="request" />
<jsp:getProperty name="beanData" property="beanId"/>
</body>
</html>