Java Tutorial/JSP/Scriptlet

Материал из Java эксперт
Перейти к: навигация, поиск

All Scripting Elements

<%@ page language="java" contentType="text/html" %>
<%@ page import="java.util.Date" %>
<%!
  private String getGreeting() {
    Date now = new Date();
    String greeting = null;
    if (now.getHours() < 12) {
      greeting = "Good morning";
    }
    else if (now.getHours() < 18) {
      greeting = "Good day";
    }
    else {
      greeting = "Good evening";
    }
    return greeting;
  }
%>
<html>
  <head>
    <title>All Scripting Elements</title>
  </head>
  <body bgcolor="white">
    <%= getGreeting() %>
    <% if (request.getParameter("name") == null) { %>
      stranger!
    <% } else { %>
      partner!
    <% } %>
    How are you?
  </body>
</html>





Call function in jsp page

<%--
  Copyright (c) 2002 by Phil Hanna
  All rights reserved.
  
  You may study, use, modify, and distribute this
  software for any purpose provided that this
  copyright notice appears in all copies.
  
  This software is provided without warranty
  either expressed or implied.
--%>
<%!
   public int sum(int a, int b)
   {
      return a + b;
   }
%>
2 + 2 = <%= sum(2, 2) %>





Count to 10 Example using JSP Scriptlet

<html>
  <head>
    <title>Count to 10 Example(using JSP Scriptlet)</title>
  </head>
  <body>
    <%
    for(int i=1;i<=10;i++)
    {
    %><%=i%>
    <br />
    <%
    }
    %>
  </body>
</html>





Scriptlet Example

<%--
  Copyright (c) 2002 by Phil Hanna
  All rights reserved.
  
  You may study, use, modify, and distribute this
  software for any purpose provided that this
  copyright notice appears in all copies.
  
  This software is provided without warranty
  either expressed or implied.
--%>
<%@ page import="java.text.*" session="false"%>
<html>
<head>
<title>Scriptlet Example</title>
</head>
<body>
<table border="0" cellpadding="3">
<tr>
   <TH>Fahrenheit</th>
   <TH>Celsius</th>
</tr>
<%
   NumberFormat fmt = new DecimalFormat("###.000");
   for (int f = 32; f <= 212; f += 20) {
      double c = ((f - 32) * 5) / 9.0;
      String cs = fmt.format(c);
%>
   <tr>
      <td align="RIGHT"><%= f %></td>
      <td align="RIGHT"><%= cs %></td>
   </tr>
<%
   }
%>
</table>
</body>
</html>





This scriptlet checks a hidden field to see whether or not to throw an exception

<%-- This scriptlet checks a hidden field to see whether or not to throw an exception --%>
<%
  String hiddenField = request.getParameter("hiddenValue");
  if ( hiddenField == null || hiddenField.equals(""))
    throw new java.lang.NullPointerException();
%>
<HTML>
  <HEAD><TITLE>Generate Error</TITLE></HEAD>
  <BODY>
    This page generates an error when you click the button.<P>
    <FORM METHOD="POST" ACTION="generateErrorNoHandler.jsp">
      <INPUT TYPE="HIDDEN" NAME="hiddenValue" VALUE="Bang!">
      <INPUT TYPE="SUBMIT" VALUE="Generate exception!">
    </FORM>
  </BODY>
</HTML>