#jsp上でのbool値の判定について
- jsp上でifでbool値の判定を行うプログラムを作成しました。
Test.java
package boolCheck;
public class Test {
private boolean bool;
public boolean isBool() {
return bool;
}
public void setBool(boolean bool) {
this.bool = bool;
}
@Override
public String toString() {
return "Test [bool=" + bool + "]";
}
}
BoolCheckServlet.java
package boolCheck;
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;
/**
* Servlet implementation class BoolCheckServlet
*/
@WebServlet("/BoolCheckServlet")
public class BoolCheckServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public BoolCheckServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
Test bean = new Test();
bean.setBool(false); //falseをセット
request.setAttribute("bean", bean);
//JSPに遷移する
RequestDispatcher disp = request.getRequestDispatcher("boolCheck.jsp");
disp.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
boolCheck.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<jsp:useBean
id="bean"
class="boolCheck.Test"
scope="request" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%= bean.toString() %>
<% System.out.println(bean);%>
<% System.out.println(bean.isBool());%>
<!-- false -->
<% if(bean.isBool()){ %>
<h1>this is true</h1>
<%}else{ %>
<h1>this is false </h1>
<% } %>
<!-- false -->
<script>
if(<%= bean.isBool()%>){
alert("this is true");
}else{
alert("this is false");
}
</script>
<!-- ''で囲むと文字列となり、結果trueとなる -->
<script>
if('<%= bean.isBool()%>'){
alert("this is true");
}else{
alert("this is false");
}
</script>
</body>
</html>