Libraries


Libraries


Created on June 26, 2017
Updated on September 11, 2021

tutorial java server libraries

So far, you’ve learned how to write your own Java server code using servlets and JSP.

Remember from the Java libraries tutorial that you can use libraries to expand what your code can do. This tutorial shows you how to use Java libraries in your server code.

Example Web App

Let’s start with an example web app that takes input from a user and then displays it.

The index.html file contains a form that submits user data as a POST request.

<!DOCTYPE html>
<html>
  <head>
    <title>Form</title>
  </head>
  <body>
    <h1>Enter some input:</h1>
    <form action="/user-input-unsanitized/form" method="POST">
      <input type="text" name="data" value="<h1>oh no</h1>">
      <br><br>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

The FormServlet class takes the user input and prints it as the response.

package io.happycoding.servlets;

import java.io.IOException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/form")
public class FormServlet extends HttpServlet {

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    String data = request.getParameter("data");

    response.setContentType("text/html");
    response.getWriter().println("You entered: " + data);
  }
}

You can view or download this project here:

What happens if the user enters some HTML content?

entering html

Try entering something like <h1>oh no</h1> into the text input and clicking the Submit button. You’ll see that that your HTML is rendered in the page:

html rendered in page

This happens because the servlet code outputs the text directly into the response on this line:

response.getWriter().println("You entered: " + data);

So if text is <h1>oh no</h1>, then the response that gets sent to the client is You entered: <h1>oh no</h1>. When the browser renders that content, it parses the HTML and shows an h1 heading.

That might not seem like a big deal, but letting users input arbitrary HTML can cause problems on your site. It can lead to bad formatting, or even worse, exploits like cross-site scripting.

One way to fix that is by replacing HTML characters in the text with character entities so that it renders as text instead of HTML. This is called escaping.

For this specific example, you could probably write some logic that encodes < as &lt; and > as &gt;, but let’s use a library instead!

Step 0: Find a Library

With so many libraries available, how do you know what’s out there, or which one to choose?

Start by opening your favorite search engine and entering “Java library” plus the problem you’re trying to solve. For example, “Java library escape html” returns quite a few suggestions you could try out.

If you have a few options, peruse each library’s homepage and documentation. Is the library still being updated? Is its documentation readable?

Try writing small “hello world” programs that test out each library, and see which one you like the best!

Commons Text

The Apache Commons Text library provides a bunch of utility classes and functions, including a StringEscapeUtils class that helps escape HTML text.

I’m using this library as an example, but the steps you follow to use this library apply to most libraries.

Step 1: Add the Library to your Classpath

Your classpath is where Java looks for classes. By default, that includes every Java class that comes with the Java Runtime Environment, and because you’re using Jakarta EE, your classpath also includes the Jakarta EE classes.

To use a library, the first thing you need to do is add it to your classpath.

Maven Dependency

I highly recommend using Maven, because it means you don’t have to deal with .jar files yourself.

Most Java libraries have a Maven dependency. To find the library’s Maven dependency, read through the library’s docs, or try typing the library’s name followed by “Maven dependency” into your favorite search engine.

Here’s the Maven dependency for the Apache Commons Text library:

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-text</artifactId>
   <version>1.9</version>
</dependency>

Add this to your pom.xml file, which tells Maven to add the library to your classpath.

Downloading Library Jars

I recommend using Maven as described above, but if for some reason you can’t use Maven, you can manually add the library to your classpath.

Go to the library download page and download the library. Unzip the file, and find the common-text-1.9.jar file inside.

Then you can add that file to the -cp argument if you’re compiling via the command line, or to your Eclipse classpath if you’re using Eclipse. If you’re manually creating your web app directory, put the .jar file inside your web app directory’s WEB-INF/lib/ folder.

Step 2: Use the Library in Your Code

Now that the Apache Commons Text library is on your classpath, you can use it in your code.

First, find the class you want to use- in this case, it’s the StringEscapeUtils class. Import it, and then use it!

package io.happycoding.servlets;

import java.io.IOException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.text.StringEscapeUtils;

@WebServlet("/form")
public class FormServlet extends HttpServlet {

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    String userInput = request.getParameter("data");
    String escapedUserInput = StringEscapeUtils.escapeHtml4(userInput);

    response.setContentType("text/html");
    response.getWriter().println("You entered: " + escapedUserInput);
    
  }
}

This servlet now calls the StringEscapeUtils.escapeHtml4() function to escape the user input.

Step 3: Compile and Run Your Code

Compile and run your server using the approach you chose in anatomy of a web app.

  • If you’re using Maven, execute mvn package and then move the .war file into your server’s webapps directory.
  • If you’re using the command line without Maven, use javac to compile your classes, and use the -cp argument to provide the library’s .jar file.
  • If you’re using Eclipse, add your project to your server and then run your server.

Navigate to index.html and enter some input. Now if you try to enter HTML into the text box, you’ll see this:

html escaped in page

That’s because the Commons Text library escapes the HTML, which renders it as text instead of HTML content.

You can view or download this example here:

This example used a particular library, but all of the above will work for any library you want to use.

Homework

  • Use a library like JSoup to let users enter some HTML, but no harmful HTML.
  • Use a JSON library to convert Java objects to JSON that you can use in JavaScript.
  • Find a machine learning library and do something cool!

Examples

Comments

Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!

Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!