Partner – Microsoft – NPI (cat= Spring)
announcement - icon

Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.

And, the Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.

>> Learn more and deploy your first Spring Boot app to Azure.

You can also ask questions and leave feedback on the Azure Spring Apps GitHub page.

Course – LS (cat=REST)

Get started with Spring and Spring Boot, through the reference Learn Spring course:


1. Overview

In this tutorial, we’ll keep improving the simple Reddit application that we’re building as part of this public case study.

2. Better Tables for Admin

First, we’ll bring the tables in the Admin pages to the same level as the tables in the user facing application – by using the jQuery DataTable plugin.

2.1. Get Users Paginated – the Service Layer

Let’s add the pagination enabled operation in the service layer:

public List<User> getUsersList(int page, int size, String sortDir, String sort) {
    PageRequest pageReq = new PageRequest(page, size, Sort.Direction.fromString(sortDir), sort);
    return userRepository.findAll(pageReq).getContent();
public PagingInfo generatePagingInfo(int page, int size) {
    return new PagingInfo(page, size, userRepository.count());

2.2. A User DTO

Next – let’s now make sure that we’re cleanly returning DTOs to the client consistently.

We’re going to need a User DTO because – up until now – the API was returning the actual User entity back to the client:

public class UserDto {
    private Long id;

    private String username;

    private Set<Role> roles;

    private long scheduledPostsCount;

2.3. Get Users Paginated – in the Controller

Now, let’s implement this simple operation in the controller layer as well:

public List<UserDto> getUsersList(
  @RequestParam(value = "page", required = false, defaultValue = "0") int page, 
  @RequestParam(value = "size", required = false, defaultValue = "10") int size,
  @RequestParam(value = "sortDir", required = false, defaultValue = "asc") String sortDir, 
  @RequestParam(value = "sort", required = false, defaultValue = "username") String sort, 
  HttpServletResponse response) {
    response.addHeader("PAGING_INFO", userService.generatePagingInfo(page, size).toString());
    List<User> users = userService.getUsersList(page, size, sortDir, sort);

      user -> convertUserEntityToDto(user)).collect(Collectors.toList());

And here’s the DTO conversion logic:

private UserDto convertUserEntityToDto(User user) {
    UserDto dto =, UserDto.class);
    return dto;

2.4. Front-end

Finally, on the client side, let’s use this new operation and re-implement our admin users page:

<th>Username</th><th>Scheduled Posts Count</th><th>Roles</th><th>Actions</th>

    $('table').dataTable( {
        "processing": true,
        "columnDefs": [
            { "name": "username",   "targets": 0},
            { "name": "scheduledPostsCount",   "targets": 1,"orderable": false},
            { "targets": 2, "data": "roles", "width":"20%", "orderable": false, 
                function ( data, type, full, meta ) { return extractRolesName(data); } },
            { "targets": 3, "data": "id", "render": function ( data, type, full, meta ) {
                return '<a onclick="showEditModal('+data+',\'' + 
                  extractRolesName(full.roles)+'\')">Modify User Roles</a>'; }}
        "columns": [
            { "data": "username" },
            { "data": "scheduledPostsCount" }
        "serverSide": true,
        "ajax": function(data, callback, settings) {
            $.get('admin/users', {
                size: data.length, 
                page: (data.start/data.length), 
                sortDir: data.order[0].dir, 
                sort: data.columns[data.order[0].column].name
            }, function(res,textStatus, request) {
                var pagingInfo = request.getResponseHeader('PAGING_INFO');
                var total = pagingInfo.split(",")[0].split("=")[1];
                    recordsTotal: total,recordsFiltered: total,data: res

3. Disable a User

Next we’re going to build out a simple admin feature – the ability to disable a user.

The first thing we need is the enabled field in the User entity:

private boolean enabled;

Then, we can use that in our UserPrincipal implementation to determine if the principal is enabled or not:

public boolean isEnabled() {
    return user.isEnabled();

Here the API operation that deals with disabling/enabling users:

@RequestMapping(value = "/users/{id}", method = RequestMethod.PUT)
public void setUserEnabled(@PathVariable("id") Long id, 
  @RequestParam(value = "enabled") boolean enabled) {
    userService.setUserEnabled(id, enabled);

And here’s the simple service layer implementation:

public void setUserEnabled(Long userId, boolean enabled) {
    User user = userRepository.findOne(userId);

4. Handle Session Timeout

Next, let’s configure the app to handle a session timeout – we will add a simple SessionListener to our context to control session timeout:

public class SessionListener implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        event.getSession().setMaxInactiveInterval(5 * 60);

And here is the Spring Security configuration:

protected void configure(HttpSecurity http) throws Exception {


  • We configured our session timeout to be 5 minutes.
  • When session expire the user will be redirected to login page.

5. Enhance Registration

Next, we’ll enhance the registration flow by adding some functionality that was previously missing.

We’re going to only illustrate the main points here; to go deep into registration – check out the Registration series.

5.1. Registration Confirmation Email

One of these features missing from registration was that users weren’t promoted to confirm their email.

We’ll now make users confirm their email address first before they’re activated in the system:

public void register(HttpServletRequest request, 
  @RequestParam("username") String username, 
  @RequestParam("email") String email, 
  @RequestParam("password") String password) {
    String appUrl = 
      "http://" + request.getServerName() + ":" + 
       request.getServerPort() + request.getContextPath();
    userService.registerNewUser(username, email, password, appUrl);

The service layer also needs a bit of work – basically making sure that the user is disabled initially:

public void registerNewUser(String username, String email, String password, String appUrl) {
    eventPublisher.publishEvent(new OnRegistrationCompleteEvent(user, appUrl));

Now for the confirmation:

@RequestMapping(value = "/user/regitrationConfirm", method = RequestMethod.GET)
public String confirmRegistration(Model model, @RequestParam("token") String token) {
    String result = userService.confirmRegistration(token);
    if (result == null) {
        return "redirect:/?msg=registration confirmed successfully";
    model.addAttribute("msg", result);
    return "submissionResponse";
public String confirmRegistration(String token) {
    VerificationToken verificationToken = tokenRepository.findByToken(token);
    if (verificationToken == null) {
        return "Invalid Token";

    Calendar cal = Calendar.getInstance();
    if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) {
        return "Token Expired";

    User user = verificationToken.getUser();
    return null;

5.2. Trigger a Password Reset

Now, let’s see how to allow users to reset their own password in case they forget it:

@RequestMapping(value = "/users/passwordReset", method = RequestMethod.POST)
public void passwordReset(HttpServletRequest request, @RequestParam("email") String email) {
    String appUrl = "http://" + request.getServerName() + ":" + 
      request.getServerPort() + request.getContextPath();
    userService.resetPassword(email, appUrl);

Now, the service layer will simply send an email to the user – with the link where they can reset their password:

public void resetPassword(String userEmail, String appUrl) {
    Preference preference = preferenceRepository.findByEmail(userEmail);
    User user = userRepository.findByPreference(preference);
    if (user == null) {
        throw new UserNotFoundException("User not found");

    String token = UUID.randomUUID().toString();
    PasswordResetToken myToken = new PasswordResetToken(token, user);;
    SimpleMailMessage email = constructResetTokenEmail(appUrl, token, user);

5.3. Reset Password

Once the user clicks on the link in the email, they can actually perform the reset password operation:

@RequestMapping(value = "/users/resetPassword", method = RequestMethod.GET)
public String resetPassword(
  Model model, 
  @RequestParam("id") long id, 
  @RequestParam("token") String token) {
    String result = userService.checkPasswordResetToken(id, token);
    if (result == null) {
        return "updatePassword";
    model.addAttribute("msg", result);
    return "submissionResponse";

And the service layer:

public String checkPasswordResetToken(long userId, String token) {
    PasswordResetToken passToken = passwordResetTokenRepository.findByToken(token);
    if ((passToken == null) || (passToken.getUser().getId() != userId)) {
        return "Invalid Token";

    Calendar cal = Calendar.getInstance();
    if ((passToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) {
        return "Token Expired";

    UserPrincipal userPrincipal = new UserPrincipal(passToken.getUser());
    Authentication auth = new UsernamePasswordAuthenticationToken(
      userPrincipal, null, userPrincipal.getAuthorities());
    return null;

Finally, here’s the update password implementation:

@RequestMapping(value = "/users/updatePassword", method = RequestMethod.POST)
public void changeUserPassword(@RequestParam("password") String password) {
    userService.changeUserPassword(userService.getCurrentUser(), password);

5.4. Change Password

Next, we’re going to implement a similar functionality – changing your password internally:

@RequestMapping(value = "/users/changePassword", method = RequestMethod.POST)
public void changeUserPassword(@RequestParam("password") String password, 
  @RequestParam("oldpassword") String oldPassword) {
    User user = userService.getCurrentUser();
    if (!userService.checkIfValidOldPassword(user, oldPassword)) {
        throw new InvalidOldPasswordException("Invalid old password");
    userService.changeUserPassword(user, password);
public void changeUserPassword(User user, String password) {

6. Bootify the Project

Next, let’s convert/upgrade the project over to Spring Boot; first, we will modify the pom.xml:



And also provide a simple Boot application for startup:

public class Application {

    public SessionListener sessionListener() {
        return new SessionListener();

    public RequestContextListener requestContextListener() {
        return new RequestContextListener();

    public static void main(String... args) {, args);

Note that the new base URL will now be http://localhost:8080 instead of the old http://localhost:8080/reddit-scheduler.

7. Externalize Properties

Now that we have Boot in, we can use @ConfigurationProperties to externalize our Reddit properties:

@ConfigurationProperties(prefix = "reddit")
public class RedditProperties {

    private String clientID;
    private String clientSecret;
    private String accessTokenUri;
    private String userAuthorizationUri;
    private String redirectUri;

    public String getClientID() {
        return clientID;

We can now cleanly use these properties in a type-safe manner:

private RedditProperties redditProperties;

public OAuth2ProtectedResourceDetails reddit() {
    AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
    return details;

8. Conclusion

This round of improvements was a very good step forward for the application.

We’re not adding any more major features, which makes architectural improvements the next logical step – this is what this article is all about.

Course – LS (cat=Spring)

Get started with Spring and Spring Boot, through the Learn Spring course:

Course – LS (cat=REST)

Get started with Spring and Spring Boot, through the Learn Spring course :

res – REST (eBook) (cat=REST)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.