Search

Creating Your First JSP

0 views

Writing Your First JSP: Scriptlets, Expressions, and the Request Object

When you first glance at a JSP file, it looks a lot like an ordinary HTML page. Hidden beneath the markup, however, are Java blocks that can execute logic, interact with the client, and produce dynamic output. Those Java blocks are called scriptlets and expressions, and they sit inside special tags that the servlet container recognizes. In this section we’ll walk through the syntax of each construct, show you practical examples, and explain how to pull data from the client using the request object.

Scriptlets – Tiny Windows Into Java

A scriptlet lets you drop plain Java statements directly into the JSP. The syntax is simple: wrap your statements in <% … %>`. Inside, you write full Java code, just as you would inside a method body. Each statement ends with a semicolon. Because scriptlets run on the server before the page is sent to the browser, you can use them to declare variables, perform calculations, or call helper methods.

Here’s a straightforward example that reads a form field named firstName and stores it in a Java String variable:

Prompt
<%</p> <p> String firstName = request.getParameter("firstName");</p> <p>%>

Notice the semicolons after the declaration and the closing of the scriptlet. The request object is one of the implicit objects automatically available to every JSP. It represents the HTTP request that triggered the page, and it gives you access to parameters, headers, session data, and more.

Expressions – Quick Output in the Flow of HTML

Expressions are a more concise way to embed a single value in the output stream. Their syntax is <%= … %>`. Inside, you place any Java expression that resolves to a value that can be converted to a string - primitives like int and double, objects that override toString(), or even the result of a method call.

Because an expression is an expression, not a statement, you never end it with a semicolon. The container automatically prints the result of the expression into the HTML that the browser receives.

Here’s the expression form of the example above, which prints the first name directly:

Prompt
The first name is <%= request.getParameter("firstName") %>.

This single line replaces the scriptlet that stored the value and the separate <%= firstName %> that printed it. Use expressions when you only need to show a value and you don’t need to keep it for later use in the page.

Combining Scriptlets and Expressions for Loops and Counters

When you need to repeat a block of HTML multiple times or maintain a counter, scriptlets come back into play. Below is a concise example that prints an HTML line five times, incrementing a counter each iteration. Notice how the scriptlet starts the loop, the expression displays the counter, and another scriptlet closes the loop:

Prompt
<%</p> <p> int counter = 1;</p> <p> while (counter <= 5) {</p> <p>%></p> <p> <div>Line <%= counter %> of text</div></p> <p><%</p> <p> counter++;</p> <p> }</p> <p>%>

In this pattern, the scriptlet before the <div> opens the loop. The expression inside the <div> prints the current counter value. The second scriptlet increments the counter and closes the loop block. The JSP container rewrites this into a servlet that runs the loop and writes the repeated HTML to the response buffer.

The Request Object – Pulling Data from the Client

Beyond just retrieving a single form field, the request object offers several handy methods for working with form data. Three of the most frequently used are getParameter, getParameterValues, and getParameterNames. Understanding each one lets you handle simple inputs, multi‑select lists, and even iterate over all parameters in a request.

getParameter(String name)

This method returns the value of a single parameter as a String. If the parameter does not exist, it returns null. It works for text fields, radio buttons, checkboxes, dropdowns, and any control that sends a single value.

Prompt
<%</p> <p> String rockCheck = request.getParameter("Rock");</p> <p> if (rockCheck != null) {</p> <p>%></p> <p> You checked Rock music!</p> <p><%</p> <p> }</p> <p>%>

In this snippet, if the checkbox named Rock is ticked, rockCheck receives the string "on" (unless a custom value attribute was set). The check for null ensures that the message only appears when the box is selected.

getParameterValues(String name)

When a form control can send multiple values - like a <select multiple> or a group of checkboxes sharing the same name - use getParameterValues. It returns an array of Strings, or null if no values were sent.

Prompt
<%</p> <p> String[] chosenCountries = request.getParameterValues("country");</p> <p> for (int i = 0; i < chosenCountries.length; i++) {</p> <p>%></p> <p> <li><%= chosenCountries[i] %></li></p> <p><%</p> <p> }</p> <p>%>

The loop walks through each selected country and prints it as a list item. This pattern keeps the JSP tidy and ensures that any number of selections is handled gracefully.

getParameterNames()

Sometimes you need to know every parameter that arrived in a request, especially when you’re debugging or building a generic handler. getParameterNames returns an Enumeration of the names. You can then use hasMoreElements() and nextElement() to iterate.

Prompt
<%</p> <p> Enumeration names = request.getParameterNames();</p> <p> while (names.hasMoreElements()) {</p> <p> String param = (String) names.nextElement();</p> <p> String value = request.getParameter(param);</p> <p>%></p> <p> <p>Parameter <strong><%= param %></strong> has value <%= value %></p></p> <p><%</p> <p> }</p> <p>%>

Because this loop prints each parameter and its value, it can help you spot unexpected input or verify that all expected fields are present. The Enumeration interface is a bit older style, but it remains in use across many legacy systems.

Putting It All Together – A Complete Example

Below is a compact yet functional JSP that collects a user’s name, favorite country, and music preference, then displays the data back to the visitor. Notice how each piece of logic lives in its own scriptlet or expression, keeping the page readable.

Prompt
<%-- GreetingForm.jsp --></p> <p><html><body></p> <p> <h2>Welcome to the Fun Survey!</h2></p> <p> <form action="GreetingForm.jsp" method="get"></p> <p> First name: <input type="text" name="firstName" /><br /></p> <p> Favorite country:<br /></p> <p> <select name="country"></p> <p> <option value="France">France</option></p> <p> <option value="Spain">Spain</option></p> <p> <option value="Japan">Japan</option></p> <p> </select><br /></p> <p> Music preference:<br /></p> <p> <input type="checkbox" name="Rock" value="Rock" />Rock<br /></p> <p> <input type="checkbox" name="Jazz" value="Jazz" />Jazz<br /></p> <p> <input type="submit" value="Submit" /></p> <p> </form></p> <p> <%-- Process and display submitted data --></p> <p> <% if (request.getParameter("firstName") != null) { %></p> <p> <p>Hello, <%= request.getParameter("firstName") %>!</p></p> <p> <p>Your favorite country is <%= request.getParameter("country") %>.</p></p> <p> <p>You liked:</p> <p> <%= request.getParameter("Rock") != null ? "Rock" : "" %></p> <p> <%= request.getParameter("Jazz") != null ? "Jazz" : "" %></p> <p> </p></p> <p> <% } %></p> <p></body></html>

When you first run this JSP, the form appears. After submitting, the page refreshes, showing a personalized greeting and the user’s selections. All the logic resides in the same file, and the code remains easy to read because we separate the form markup from the processing scriptlets and keep expressions short.

Deploying and Testing Your JSP: File Placement, URLs, and HTTP Methods

Building a JSP is just the beginning. To make it available to users, you must place it in the correct directory of your servlet container, point browser requests to it correctly, and choose the right HTTP method for data transfer. This section walks through each of those steps, focusing on a Tomcat environment but leaving the concepts general enough to apply to any Java web server.

Where to Save a JSP – Keeping Your Project Organized

In a Tomcat installation, the root of the web‑application space is the webapps folder. Inside, each application gets its own subdirectory. For instance, the Murach examples live under c:/tomcat/webapps/murach, and the email list module resides in c:/tomcat/webapps/murach/email4. If you’re using a different server, locate its equivalent root folder.

When you create a new JSP, save it in the same directory that contains the HTML files for the module. This keeps related files together and lets the container resolve relative paths easily. If you open a plain text editor that isn’t aware of JSP syntax, you may need to enclose the filename in quotes - e.g., "show_email_entry.jsp" - so the editor preserves the .jsp extension instead of truncating it.

Optionally, you can organize JSPs into subfolders to separate logic from view, but that introduces the need for correct action paths when linking or forwarding. A flat structure is simplest for beginners and keeps the learning curve gentle.

Requesting a JSP – Through Links, Forms, and Direct URLs

Once the file is in place, you must send the user’s browser a request that hits the JSP. There are three common ways to do this: a hyperlink, a form submission, or a direct URL typed into the address bar. Each approach behaves slightly differently, so understanding the distinctions helps you choose the best method for a given scenario.

Hyperlinks – <a> Tags

Embedding a hyperlink in an HTML page is the simplest way to route a user to a JSP. The href attribute points to the relative or absolute path of the JSP. For example:

Prompt
<a href="show_email_entry.jsp">Enter Your Email</a>

Because the link uses a relative path, the container automatically resolves it against the current directory. If the link and JSP reside in different folders, provide a relative path like ../email4/show_email_entry.jsp or an absolute path beginning with a slash, such as /murach/email4/show_email_entry.jsp

Forms – <form> Tags

Forms allow you to gather user input before dispatching to a JSP. The action attribute points to the JSP file, while the method attribute dictates whether the data travels in the URL (get) or in the request body (post). For a quick example:

Prompt
<form action="show_email_entry.jsp" method="get"></p> <p> <input type="text" name="firstName" /></p> <p> <input type="submit" value="Submit" /></p> <p></form>

When the user clicks the submit button, the browser sends a GET request, attaching the form data as query parameters in the URL. If you use post, the data travels in the body, and the URL stays clean.

Direct URLs – Typing into the Address Bar

Testing a JSP quickly often involves entering its full URL manually. Suppose your Tomcat instance runs on localhost with the default port and your application is in the murach/email4 directory. The URL looks like this:

Prompt
http://localhost:8080/murach/email4/show_email_entry.jsp

You can append query parameters directly to the URL. Start with a question mark, then list name-value pairs separated by ampersands. For instance:

Prompt
http://localhost:8080/murach/email4/show_email_entry.jsp?firstName=John&lastName=Smith

When the browser requests the page, the container parses the parameters and makes them available through request.getParameter(). This technique is handy for debugging or for demonstration purposes when you want to skip the form step.

Choosing Between GET and POST – Speed, Visibility, and Size

Both GET and POST transport data from client to server, but they differ in a few key respects. These differences influence when you should prefer one over the other.

GET – Quick, Visible, and Bookmarkable

If the form submits a small amount of data - typically less than 4 KB - and you don’t mind the parameters appearing in the URL, GET is a natural choice. It’s slightly faster because the data travels in the URL, and users can bookmark the resulting page. For example, a search query or a simple filter often uses GET

POST – Hidden, Secure, and Large

When you need to protect sensitive information - such as passwords or credit card numbers - or transmit more than 4 KB of data, POST is preferable. The data is placed in the request body, so it never appears in the browser’s address bar or in server logs. Additionally, POST requests are not cached by most browsers, offering an extra layer of privacy.

Remember that you can still test a POST form by appending parameters to the URL, but the servlet will ignore them because it expects the data in the body. Likewise, you can inspect the network traffic in developer tools to verify that the body contains the correct values.

Practical Decision Guide

• If you’re sending a single search term or a small set of choices and you’d like the URL to reflect the state, choose GET

• If the user is submitting a registration form, a payment gateway, or any data that is sensitive or large, choose POST

• For administrative or internal forms where privacy isn’t a concern and data size is trivial, GET keeps things simple.

Testing the JSP – From Development to Production

After you’ve saved the JSP in the correct location and ensured your action paths are correct, start the servlet container. In Tomcat, run the catalina.bat run (Windows) or ./catalina.sh run (Unix). Watch the console for a startup banner; once it says “Tomcat started,” your application is live.

Open a browser and navigate to the URL you constructed earlier. If you see the expected form, try submitting it. Watch the output; the JSP should render the user’s data. Check the console for any errors - unclosed tags, missing semicolons in scriptlets, or null pointers can cause runtime exceptions. The Tomcat log files (catalina.out or logs/catalina.log) are a good place to look for stack traces.

When the page works locally, you can package the whole directory into a WAR file and deploy it to a production server. Tomcat automatically scans the webapps folder for new or updated WARs, extracts them, and makes the application available at the context root corresponding to the WAR name.

During this transition, double‑check that all file paths remain relative and that the JSP can still access any required resources (images, CSS, JavaScript). A common pitfall is hard‑coding absolute URLs that only work on the development machine.

Once the deployment succeeds, users can access the JSP by visiting the public URL. If you need to support multiple environments - development, staging, production - consider externalizing configuration values, such as the server name or port, into context parameters or environment variables.

By following these steps - organizing files, pointing requests correctly, and choosing the right HTTP method - you’ll turn a simple JSP into a functional, secure, and maintainable part of your web application. Happy coding!

Suggest a Correction

Found an error or have a suggestion? Let us know and we'll review it.

Share this article

Comments (0)

Please sign in to leave a comment.

No comments yet. Be the first to comment!

Related Articles