Model(JavaBeans),View(Jsp),Controller(Servlet)を連携させ以下のアプリを作成せよ。
実行画面
1.画面にフォームが表示される
2.インチを入力し送信を押すとインチをセンチに変換した値を表示する。
なお、1インチは2.54センチである。
作例
フォルダ構成
model
●model.InchCm.java
package model;
import java.io.Serializable;
public class InchCm implements Serializable{
private double inch;
private double cm;
public InchCm() {}
public InchCm(double inch) {
this.inch=inch;
}
public double getInch() {
return inch;
}
public void setInch(double inch) {
this.inch = inch;
}
public double getCm() {
return cm;
}
public void setCm(double cm) {
this.cm = cm;
}
}
●model.InchCmLogic.java
package model;
public class InchCmLogic {
public void execute(InchCm ic) {
double inch=ic.getInch();
double cm=inch*2.54;
ic.setCm(cm);
}
}
controller
●controller.Main.java
package controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 model.InchCm;
import model.InchCmLogic;
@WebServlet("/Main")
public class Main extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd=request.getRequestDispatcher("/WEB-INF/view/form.jsp");
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Double inch=Double.parseDouble(request.getParameter("inch"));
InchCm ic=new InchCm(inch);
InchCmLogic icl=new InchCmLogic();
icl.execute(ic);
request.setAttribute("ic", ic);
RequestDispatcher rd=request.getRequestDispatcher("/WEB-INF/view/result.jsp");
rd.forward(request, response);
}
}
view
●/WEB-INF/view/form.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/inch/Main" method="Post">
<p>インチを入力<input type="number" name="inch" step="0.01" min="0.0">
<input type="submit" value="送信"></p>
</form>
</body>
</html>
●/WEB-INF/view/result.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="model.InchCm"%>
<%
InchCm ic=(InchCm)request.getAttribute("ic");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p><%=ic.getInch() %>inchは<%=ic.getCm() %>cmです。</p>
<a href="/inch/Main">戻る</a>
</body>
</html>
コメント