Enterprise Java

Configuring HTTPS for use with Servlets

To configure 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 between <security-constraint> elements. The following code snippet show 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> this 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> this is the URL to be protected
  • <http-method> this is the HTTP method to protect. If you omit this line then all HTTP method calls are protected.
  • <transport-guarantee> specified 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

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

Published on Java Code Geeks with permission by Alex Theedom, partner at our JCG program. See the original article here: Configuring HTTPS for use with Servlets

Opinions expressed by Java Code Geeks contributors are their own.

Alex Theedom

Alex Theedom is a Senior Java Developer and has recently played a pivotal role in the architectural design and development of a microservice based, custom built lottery and instant win game platform. Alex has experience of Java web application development in a diverse range of fields including finance, e-learning, lottery and software development. He is the co-author of Professional Java EE Design Patterns and many articles.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button