Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Configuring HTTPS for Use With Servlets [Snippet]

DZone's Guide to

Configuring HTTPS for Use With Servlets [Snippet]

Getting HTTPS up and running for your Java EE app is as simple as adding some XML. Let's look at configuring your app for more secure communication.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

Configuring your Java EE application to communicate over HTTPS requires a few lines of XML in the web.xml file.

The web.xml file is located in the WEB-INF directory of your project and is usually created automatically when your IDE generates a Java EE web application. If it is not, you can create it yourself.

Motivation for HTTPS

The reasons for configuring a secure connection for your web application is to allow secure communication between your application and the user of your application. Beyond this consideration, if you want your application to communicate with the client using the HTTP 2 protocol, then a secure connection over HTTPS is required.

Configure a Secure Connection

A secure connection is configured in the web.xml file within the <security-constraint> element. The following code snippet shows a simple example of how to do this.

<security-constraint>
    <web-resource-collection>
        <web-resource-name>Servlet4Push</web-resource-name>
        <url-pattern>/*</url-pattern>
        <http-method>GET</http-method>
    </web-resource-collection>

    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>

</security-constraint>


Let’s look at each element in turn:

  • <web-resource-name> is the name of the web resource you want to secure. This is likely to match the context root of your application.
  • <url-pattern>/*</url-pattern> is the URL to be protected.
  • <http-method> is the HTTP method to protect. If you omit this line, then all HTTP method calls are protected.
  • <transport-guarantee> specifies the security constraint to use. CONFIDENTIAL means that HTTPS should be used. NONE means HTTP should be used.

This is the simplest example of how to implement HTTPS in a Java EE application.

Source Code

The source code for this example can be found in the ReadLearnCode GitHub repository.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. 

Topics:
java ,web.xml ,https ,java ee ,servlets

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}