Mixing Client-Side and Server-Side Code

I touched on the differences between server-side code and client-side code in Chapter 3. JSP is a server-side technology, so all JSP elements such as actions and scriptlets execute on the server before the resulting page is sent to the browser. A page can also contain client-side code, such as JavaScript code or Java applets. This code is executed by the browser itself. There is no way that a JavaScript event handler such as onClick or onSelect can directly invoke a JSP element such as an action, a scriptlet, or a Java method declared with a JSP declaration.

However, a JSP page can generate JavaScript code dynamically the same way it generates HTML, WML, or any type of text content. Therefore, you can add client-side scripting code to your JSP pages to provide a more interactive user interface. You can also use applets on your pages to provide a more interesting and easier to use interface than what’s possible with pure HTML.

Generating JavaScript Code

Example 12.10 shows a modified version of the User Info page used in the examples in Chapter 5.

Example 12-10. Input Form with Client-Side Validation Code (clientscript.jsp)

<%@ page language="java" contentType="text/html" %>
<%@ page import="com.ora.jsp.util.*" %>

<script language="JavaScript">
  <!-- Hide from browsers without JavaScript support

  function isValidForm(theForm) {
    if (isEmpty(theForm.userName.value)) {
      theForm.userName.focus( );
      return false;
    }
    if (!isValidDate(theForm.birthDate.value)) ...

Get Java Server Pages now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.