Java Tutorial/JSP/Scriptlet

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

All Scripting Elements

   <source lang="java">

<%@ 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></source>





Call function in jsp page

   <source lang="java">

<%--

 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) %></source>





Count to 10 Example using JSP Scriptlet

   <source lang="java">

<html>

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

</html></source>





Scriptlet Example

   <source lang="java">

<%--

 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>

<% 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); %> <% } %>
Fahrenheit Celsius
<%= f %> <%= cs %>

</body> </html></source>





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

   <source lang="java">

<%-- 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.

<FORM METHOD="POST" ACTION="generateErrorNoHandler.jsp"> <INPUT TYPE="HIDDEN" NAME="hiddenValue" VALUE="Bang!"> <INPUT TYPE="SUBMIT" VALUE="Generate exception!"> </FORM> </BODY> </HTML></source>