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 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> 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 for this example can be found in the ReadLearnCode GitHub repository.
Leave a Reply