Category: Uncategorized

Spring Boot – Deploy WAR file to External Tomcat

http://www.javaguides.net/2018/09/spring-boot-deploy-war-file-to-external-tomcat.html

In this article, we will discuss how to deploy a Spring Boot web application WAR file to the external Tomcat servlet container.

It’s very simple to configure and deploy the Spring web application war file to an external Tomcat servlet container.

Please follow below three simple steps to configure and deploy the Spring web application war file to the externalTomcat servlet container.

Three steps for Spring Boot WAR deployment

  1. Change the packaging type.
<packaging>war</packaging>
  1. Add spring-boot-starter-tomcat as the provided scope
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <scope>provided</scope>
  </dependency>
  1. Spring Boot Application or Main class extends SpringBootServletInitializer
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class Springboot2WebappJspApplication extends SpringBootServletInitializer{

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Springboot2WebappJspApplication.class);
    }
 
    public static void main(String[] args) {
        SpringApplication.run(Springboot2WebappJspApplication.class, args);
    }
}

Let’s develop complete step by step Spring Boot 2 Web application using JSP as View.

Table of Contents

  1. What we’ll build
  2. Tools and Technologies Used
  3. Creating and Importing a Project
  4. Packaging Structure
  5. The pom.xml File
  6. The Springboot2WebappJspApplication.java File
  7. Create a JPA Entity called User.java
  8. Create Spring Data JPA Repository – UserRepository.java
  9. Create Spring Controller – UserController.java
  10. Configuring MySQL Database and JSP View Resolver
  11. Insert SQL Script
  12. Create a JSP View – users.jsp
  13. Running the Application

1. What we’ll build

We are building a simple Spring MVC web application and JSP as a view and we will deploy this application in an external servlet container that is Tomcat.

2. Tools and Technologies Used

  • Spring Boot – 2.0.4.RELEASE
  • JDK – 1.8 or later
  • Spring Framework – 5.0.8 RELEASE
  • Hibernate – 5.2.17.Final
  • Maven – 3.2+
  • IDE – Eclipse or Spring Tool Suite (STS)
  • Tomcat – 8.5+
  • JSP
  • Bootstrap 3+

3. Creating and Importing a Project

There are many ways to create a Spring Boot application. The simplest way is to use Spring Initializr at http://start.spring.io/, which is an online Spring Boot application generator.

Look at the above diagram, we have specified following details:

  • Generate: Maven Project
  • Java Version: 1.8 (Default)
  • Spring Boot:2.0.4
  • Group: net.guides.springboot2
  • Artifact: springboot2webappjsp
  • Name: springboot2webappjsp
  • Package Name : net.guides.springboot2.springboot2webappjsp
  • Packaging: jar (This is the default value)
  • Dependencies: Web, JPA, MySQL, DevTools

Once, all the details are entered, click on Generate Project button will generate a spring boot project and downloads it. Next, Unzip the downloaded zip file and import it into your favorite IDE.

4. Packaging Structure

Once we will import generated spring boot project in IDE, we will see some auto-generated files.

  1. pom.xml
  2. resources
  3. Springboot2WebappJspApplication.java
  4. Springboot2WebappJspApplicationTests.java

5. The pom.xml File

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>net.guides.springboot2</groupId>
    <artifactId>springboot2-webapp-jsp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>springboot2-webapp-jsp</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

         <!-- JSTL for JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <!-- Need this to compile JSP -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- Optional, test for static content, bootstrap CSS -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

Note that is above pom.xml, we have packaging type as war and tomcat starter as provided scope.

6. The Springboot2WebappJspApplication.java File

This class provides an entry point with the public static void main(String[] args) method, which you can run to start the application.Note that SpringBootServletInitializer run a SpringApplication from a traditional WAR deployment

package net.guides.springboot2.springboot2webappjsp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class Springboot2WebappJspApplication extends SpringBootServletInitializer{

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Springboot2WebappJspApplication.class);
    }
 
    public static void main(String[] args) {
        SpringApplication.run(Springboot2WebappJspApplication.class, args);
    }
}

7. Create a JPA Entity called User.java

package net.guides.springboot2.springboot2webappjsp.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User {
    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    private String name;
 
    public User()
    {
    }

    public User(Integer id, String name)
    {
        this.id = id;
        this.name = name;
    }

    public Integer getId()
    {
        return id;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }
}

8. Create Spring Data JPA Repository – UserRepository.java

package net.guides.springboot2.springboot2webappjsp.repositories;

import org.springframework.data.jpa.repository.JpaRepository;

import net.guides.springboot2.springboot2webappjsp.domain.User;

public interface UserRepository extends JpaRepository<User, Integer>
{

}

9. Create Spring Controller – UserController.java

package net.guides.springboot2.springboot2webappjsp.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import net.guides.springboot2.springboot2webappjsp.repositories.UserRepository;

@Controller
public class UserController {
    @Autowired
    UserRepository userRepo;

    @RequestMapping("/users")
    public String home(Model model) {
        model.addAttribute("users", userRepo.findAll());
        return "index";
    }
}

10. Configuring MySQL Database and JSP View Resolver

Configure application.properties to connect to your MySQL database. Let’s open an application.properties file and add following database configuration to it.

spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp

logging.level.org.springframework=INFO

################### DataSource Configuration ##########################
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/users_database
spring.datasource.username=root
spring.datasource.password=root

################### Hibernate Configuration ##########################

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

11. Insert SQL Script

Once you will run this application will create users table in a database and use below insert SQL script to populate a few records in users table.

INSERT INTO `users_database`.`user` (`id`, `name`) VALUES ('1', 'Salman');
INSERT INTO `users_database`.`user` (`id`, `name`) VALUES ('2', 'SRK');
INSERT INTO `users_database`.`user` (`id`, `name`) VALUES ('3', 'AMIR');
INSERT INTO `users_database`.`user` (`id`, `name`) VALUES ('4', 'Tiger');
INSERT INTO `users_database`.`user` (`id`, `name`) VALUES ('5', 'Prabhas');

12. Create a JSP View – users.jsp

Let’s create a users.jsp view to show the list of users. Locate under webapp/WEB-INF/jsp folder.

<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<head>

<link rel="stylesheet" type="text/css"
 href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" />
<c:url value="/css/main.css" var="jstlCss" />
<link href="${jstlCss}" rel="stylesheet" />

</head>
<body>
    <div class="container">
        <header>
           <h1>Spring MVC + JSP + JPA + Spring Boot 2</h1>
        </header>
        <div class="starter-template">
           <h1>Users List</h1>
            <table class="table table-striped table-hover table-condensed table-bordered">
                <tr>
                   <th>Id</th>
                   <th>Name</th>
                </tr>
                <c:forEach var="user" items="${users}">
                   <tr>
                        <td>${user.id}</td>
                        <td>${user.name}</td>
                   </tr>
                 </c:forEach>
            </table>
        </div>

    </div>
 <script type="text/javascript"
  src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

13. Running the Application

  1. It is a maven project so create a war file using the following command:
mvn clean install or mvn clean package
  1. Once maven builds success then WAR file is generated under a target folder.

Just copy war file to external tomcat webapps folder and start the tomcat server.

  1. Hit this link to a browser – http://localhost:8080/springboot2-webapp-jsp/users

Note that you can change the context name from springboot2-webapp-jsp-0.0.1-SNAPSHOT to springboot2-webapp-jsp or as per your requirement.

GitHub Repository

The source code of this article available on my GitHub repository – https://github.com/RameshMF/spring-boot-tutorial/tree/master/springboot2-webapp-jsp-WAR

Spring Boot and WordPress CMS Integration

https://kamranzafar.org/2016/08/08/spring-boot-and-wordpress-integration/

 

There are a lot of excellent open source content management systems available today,  WordPress being one of them, which is widely used. WordPress is a PHP based CMS so not a lot of cohesion is available with other technologies like Java, and is simply ignored as a viable content management option just for being non-Java.

In this post I will demonstrate how WordPress can be integrated with Spring Boot applications, all made possible with WordPress REST plugin and a Spring client. Both of these are open source and available for free. Below is a simple design diagram that explains how this integration works. This post assumes that the reader has prior knowledge of WordPress and Spring Boot.


spring-wpapi-simple
First install and activate WP-API v2 plugin on the WordPress site. After activation, you could verify that the plugin is working by accessing http://yoursite/wp-json/wp/v2/posts, which should display all the posts in JSON format.In the spring boot application add the following dependency in order to include the Spring WP-API client.

Below is a sample configuration we need in the application.properties file, so that we can connect our Spring Boot application to our WordPress site.

The Spring WP-API client needs the RestTemplate so lets create a bean in our Application and autowire the Spring client. We also need to add component scan annotation so that Spring finds and autowires all the required dependencies.

Now our spring boot application is all setup to connect to out WordPress site in order to retrieve and create content. So lets try and lookup all the posts having the keyword “Spring”, below is how we can do this.

The complete test application is available with the Spring WP-API client on Github.

This is just a small example of how we can integrate Spring Boot and WordPress. We can take this further by properly integrating WordPress in the Spring web applications platform, e.g. by enabling Single Sign On using the CAS plugin.


spring-wpapi-cas
And we can evolve this design even further by having a second-level content storage, like a database or an in-memory caching solution etc. This storage can serve as a cache and can also be used for additional configuration, so that we display relevant content faster in our Spring applications.

spring-wpapi-cas-db
For more information please see the documentation of the WordPress REST plugin and Spring WP-API client.

How to Create Spring Boot Application Step by Step

http://www.adeveloperdiary.com/java/spring-boot/create-spring-boot-application-step-step/

 

How to Create Spring Boot Application Step by Step

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPrint this pageShare on TumblrShare on Reddit

Spring Boot had been built for Rapid Application Development. In this tutorial we will learn How to Create Spring Boot Application using some easy examples. We will also focus on How to deploy spring boot application in different application servers.

Here are the following topics that we will cover in this series:

  1. Create Spring Boot Application using
    • start.spring.io
    • Eclipse STS
    • IntelliJ IDEA STS
  2. Run Spring Boot Application using
    • Java CLI
    • Eclipse/IntelliJ IDEA
  3. Create a Basic Spring Boot application using REST
  4. How to use Spring Actuator
  5. Deploy Spring Boot application in
    • IBM Liberty Profile
    • IBM Application Server 8.5

If you need an introduction of Spring Boot please find my previous post below.

Create Spring Boot Application using start.spring.io

The best way of bootstrapping Spring Boot application is by using Spring Initializr. Let’s first start by opening http//start.spring.io.As you already know, you can use either Maven or Gradle to build, however we will use Maven in this tutorial. Click on Switch to the full Version and you will be able to see the below screen.

Software Needed

  • JDK 1.8 (You can use 1.7 or 1.6)
  • Maven 3.x

Steps :

  • Select Maven Project
  • If you want, change the Group/Package name. We will use com.adeveloperdiary
  • Change the Artifact to SpringBoot, Name will automatically change to the same
  • Leave the packaging to Jar, Java Version to 1.8 (Make sure you have JDK 1.8 in your local or use 1.7 )
  • Either type the Dependencies or select them below. We will add Web and Actuator here
  • Click on Generate Project button to download the zip file

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Now Extract the zip and you will have the following files.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Open Terminal and navigate to the above folder. Type mvn clean packageand press enter. The Build will start now.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Once the build has been completed, you will have the SpringBoot-0.0.1-SNAPSHOT.jar created inside the target folder.

The Size of the jar would be around 13MB since it will have the embedded Tomcat server in it.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Create Spring Boot Application using Eclipse

We will use STS Toolkit to bootstrap when using eclipse. I am using eclipse MARS .1 version. We will first install the STS (SpringSource Tools Suite). Open Eclipse Marketplace, Type STS in Find and install the STS.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Then open Spring perspective.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Create a New -> Spring Starter Project.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Enter the following details. Click Next.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Select Web and Actuator. Click on Next.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Click on Finish.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

This should create the Spring Boot Project in Eclipse.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Create Spring Boot Application using IntelliJ IDEA

We will now use IntelliJ IDEA to create our Spring Boot Application.I recommend to use the latest version of IntelliJ. Create a New Project. Select Spring Initializr. Click on Next.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Enter the following details. Click Next.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Select Web and Actuator. Click Next.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Enter the project Name and click Finish.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Your Spring Boot Project has been created now.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Run Spring Boot Application using CLI

We had created the jar file, now we will run it from Command Line by executing this line

You should be able to see Spring Boot in the Command Line.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

The server should have started and the default port number will also be displayed as below.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Run Spring Boot Application in Eclipse

Its much easier to run the Spring Boot app in eclipse. Select the project, Right Click and, move to Run As and click on Spring Boot App. Again, remember you need to select the project to get this option, not the pom file.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Here is the output.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Run Spring Boot Application in IntelliJ IDEA

Its probably most easy, click on the run icon.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

You should be able to see the logs that the application has started.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Conclusion

Hope this Step by Step approach will help you. Next we will learn how to create RESTServices and use Actuator in Spring Boot. Later we will also learn how to deploy Spring Boot Application in IBM Liberty Profile and IBM WAS 8.5 Server.

This is the 2nd part of Getting Started with Spring Boot Series. Find all the parts here.

  1. An Introduction to Spring Boot
  2. How to Create Spring Boot Application Step by Step
  3. How to create RESTFul Webservices using Spring Boot
  4. How to deploy Spring Boot application in IBM Liberty and WAS 8.5

Step-by-step Spring Boot RESTful web services example in Java using STS

https://www.theserverside.com/video/Step-by-step-Spring-Boot-RESTful-web-services-example-in-Java

In a previous article about important RESTful principles and how to create a beautiful RESTful API, I used the example of a web service that kept track of an ongoing, global score for an online rock-paper-scissors application. In this step-by-step Spring Boot RESTful web services example, we’ll implement that scenario using the Spring Web APIs and the Eclipse based SpringSource Tool Suite (STS) as the IDE.

Review of the RESTful API

The RESTful score service will provide the following functions:

RESTful clients can find out the current number of wins, losses and ties through a GET request to the following URL:

www.mcnz.com/rps/score | GET

This invocation will return a JSON string in the following format:

{ "wins":"5", "losses":"3", "ties": "0"}

RESTful clients can update the score by invocating the same URL through a PUT invocation while also passing query parameters. Again, the program will return a JSON-based representation of the score after the update. A better design would be to use JSON as the payload, but query parameters are used here for the sake of simplicity.

www.mcnz.com/rps/score?wins=1&losses=2&ties=3 | PUT

With the RESTful API, the user cannot directly set the number of wins, losses or ties. The client can only use a POST invocation to increment values one at a time. This is not an idempotent function, so it is handled through a POST. In this case, a simple number is returned to the program as opposed to a JSON string.

You can use a simple GET invocation on the appropriate resource locator to obtain the number of wins, losses or ties:

www.mcnz.com/rps/score/wins | GET

www.mcnz.com/rps/score/ties | GET

www.mcnz.com/rps/score/losses | GET

This step-by-step Spring Boot RESTful web services example in Java has very few prerequisites, but it does assume that you have the SpringSource Tool Suite (STS) installed. If that’s the case, you are ready to jump on the fast track to developing RESTful web services with Spring.

Step 1. Create the RESTful Spring Boot project

The first step in this exercise is to create a new Spring Boot project named restful-spring-example that uses both the Web and DevTools features. This is accomplished by kicking off the Spring Starter Project wizard in Eclipse. Select the Spring Web and DevTools options and click Finish on the Spring Boot project wizard.

Spring Boot project wizard
How to start a Spring Boot RESTful web services project

Step 2: Create the Java classes

The next step is to open the restful-spring-example project and create two classes: Score.java and ScoreService.java.

Right click on the com.mcnz.restful.spring.boot package and choose to create a new class named Score. The Score class is used to keep track of the global number of wins, losses and ties that occur in the online rock-paper-scissors game. The Score class will maintain the number of wins, losses and ties as static variables of type int. State should never be held within a RESTful web service, so this class represents the externalization of state.

package com.mcnz.restful.spring.boot;

public class Score {
  public static int WINS, LOSSES, TIES;
}

After you code the Score class, create a second Java component named ScoreService. We’ll use the ScoreService class to provide access to — and the ability to manipulate — the Score. The first iteration of the class used in this Spring Boot web service example will have getter methods that return the number of wins, losses and ties, along with update methods that can increment the number of wins, losses and ties by one.

Create the RESTful Spring Boot ScoreService class
How to create the ScoreService class for the step-by-step RESTful web services example

Here is the first iteration of the ScoreService class before we decorate it with RESTful annotations and subsequently configure it as a Spring Boot web service.

package com.mcnz.restful.spring.boot;
/* Spring Boot web service example class */
public class ScoreService {
   
   public String updateScore(int wins, int losses, int  ties) {
      Score.WINS = wins;
      Score.TIES = ties;
      Score.LOSSES = losses;
      /* to be updated to return JSON */
      return this.toString();
   }

   public int increaseWins()   { return ++Score.WINS;   }
   public int increaseTies()   { return ++Score.TIES;   }
   public int increaseLosses() { return ++Score.LOSSES; }

   public int getWins()   { return Score.WINS;   }
   public int getTies()   { return Score.TIES;   }
   public int getLosses() { return Score.LOSSES; }
}

/* End of Spring Boot web service example class. */

Step 3: Annotate the Spring Boot example class

With the first iteration of the ScoreService component coded, the next step is to transform it into a Spring Boot RESTful web service by decorating the class declaration with the @RestController annotation. The @RestController annotation informs the Spring Boot framework that the class contains methods that will be invoked through a web-based resource URL.

@RestController
public class ScoreService { … }

Step 4: Annotate RESTful Spring methods

Step four is to add @RequestMapping annotations to methods. These annotations define the HTTP method used along with the structure of the resource URLs that will be used to invoke them. In the previous tutorial about how to create beautiful RESTful APIs, we established that we would invoke the update methods through a POST, and all getter methods sensibly through a GET invocation. The URLs are all resource based, so use of the URL path is /score/wins to get information about the number of wins and the path /score/ties to increase the number of ties.

Fully decorated with Spring Boot RESTful web service annotations, the next iteration of the ScoreService class looks as follows:

/* Spring Boot web service example class */
@RestController
public class ScoreService {

  @RequestMapping(value="/score", method=RequestMethod.PUT, )
  public String updateScore(int wins, int losses, int ties) {
     Score.WINS = wins;
     Score.TIES = ties;
     Score.LOSSES = losses;
     return this.toString(); /* to be updated to return JSON */
   }
   @RequestMapping(value="/score/wins", method=RequestMethod.POST)
   public int increaseWins()   { return ++Score.WINS;   }
  
   @RequestMapping(value="/score/ties", method=RequestMethod.POST)
   public int increaseTies()   { return ++Score.TIES;   }

   @RequestMapping(value="/score/losses", method=RequestMethod.POST)
   public int increaseLosses() { return ++Score.LOSSES; }

   @RequestMapping(value="/score/wins", method=RequestMethod.GET)
   public int getWins()   { return Score.WINS;   }

   @RequestMapping(value="/score/ties", method=RequestMethod.GET)
   public int getTies()   { return Score.TIES;   }

   @RequestMapping(value="/score/losses", method=RequestMethod.GET)
   public int getLosses() { return Score.LOSSES; }
}
/* End of Spring Boot web service example class */

Step 5: Generate RESTful JSON responses

This step-by-step Spring Boot RESTful web services example needs to generate a JSON-based response for the client. There are excellent frameworks like Jackson and GSON, which you should use in larger projects, but for this simple RESTful web services example, we will simply employ some Java String manipulation to generate the JSON.

The getScore() method needs to return a JSON string formatted in the following manner:

{ "wins":"5", "losses":"3", "ties": "0"}

Here is how the un-annotated getScore() method looks when coded to return a JSON string:

public String getScore() {
  String pattern = 
     "{ \"wins\":\"%s\", \"losses\":\"%s\", \"ties\": \"%s\"}";
  return String.format(pattern,Score.WINS, Score.LOSSES, Score.TIES);
}

Note that you’ll use this same pattern match and String format approach again to return a JSON-based representation of the score in the updateScore method.

Since the getScore() method now returns JSON, you need to add a new produces attribute to the @RequestMapping annotation. The fully annotated getScore() method that indicates that JSON will be returned to the calling program looks as follows:

@RequestMapping(value="/score", 
            method=RequestMethod.GET, 
                  produces=MediaType.APPLICATION_JSON_VALUE)
public String getScore() {
  String pattern = 
       "{ \"wins\":\"%s\", \"losses\":\"%s\", \"ties\": \"%s\"}";
  return String.format(pattern,  Score.WINS, Score.LOSSES, Score.TIES);
}

In order to generate JSON, the updateScore method follows a similar pattern of updated annotations and String manipulation within the code:

@RequestMapping(value="/score", 
    method=RequestMethod.PUT, 
       produces=MediaType.APPLICATION_JSON_VALUE)

public String updateScore(int wins, int losses, int ties) {
  Score.WINS = wins;
  Score.TIES = ties;
  Score.LOSSES = losses;
 String pattern = 
     "{ \"wins\":\"%s\", \"losses\":\"%s\", \"ties\": \"%s\"}";
  return String.format(pattern,Score.WINS, Score.LOSSES, Score.TIES);     
}

QueryParam to method signature mapping

To update the ScoreService, the client will use the /score path while it passes query parameters to represent the number of wins, losses and ties. For example, a request to update the number of wins to 99, ties to 88 and losses to 7 would look like this:

http://www.mcnz.com/score?wins=99&ties=88&losses=7

As long as the updateScore method has method parameters that match the names of the query parameters, the Spring Boot web services framework will assign the queryParam values to the correspondingly named method signature parameter.

http://www.mcnz.com/score?wins=99&ties=88&losses=7

public String updateScore(int wins, int losses, int ties) { … }

The updateScore method will take the values passed into the method and assign them to the corresponding properties of the ScoreService class. An updated JSON string will be sent to the client indicating the new, updated value of the score. You’ll use the same process used to generate JSON in the getScore()method here. The full method implementation is as follows:

@RequestMapping(value="/score", 
     method=RequestMethod.PUT, 
        produces=MediaType.APPLICATION_JSON_VALUE)

public String updateScore(int wins, int losses, int ties) {
  Score.WINS = wins;
  Score.TIES = ties;
  Score.LOSSES = losses;
  String pattern = 
     "{ \"wins\":\"%s\", \"losses\":\"%s\", \"ties\": \"%s\"}";
  return String.format(pattern, Score.WINS, Score.LOSSES, Score.TIES);
}

With the updateScore method coded, the step-by-step Spring Boot RESTful web services example is code complete, and the only steps left are to test and deploy.

Step 6:  Run the Spring Boot RESTful web service

To run the application, simply right click on the restful-spring-example project and choose Run As → Spring Boot App and Maven will package the application and deploy it to the STS server. When the console window indicates the Tomcat-based server has finished starting, open a browser window and go to localhost:8080/score/wins. A value of zero will appear.

Step 7: Test the RESTful Spring Boot service

To test the increaseWins method, run the following two CURL command in a Bash shell:

$ curl -X POST "http://localhost:8080/score/wins"
$ curl -X GET "http://localhost:8080/score/"

The output of the second command is:

{ "wins":"1", "losses":"0", "ties": "0"}

Now trigger a PUT invocation, with query parameters being used to carry the payload:

$ curl -X PUT "http://localhost:8080/score?wins=31&losses=11&ties=22"

This results in an output of:

{ "wins":"31", "losses":"11", "ties": "22"}

And that’s it, a complete, step-by-step Spring Boot RESTful web services example that creates a fully functional Spring Boot application.

How to improve the RESTful Spring example

Now there is plenty of room for improvement and expansion when it comes to this step-by-step Spring Boot RESTful web services example.

Obviously, using the static variables in the Score class is a poor way to manage state, so at the very least we should offload the job of state management to a JavaBean with an ObjectOutputStream. And neither a JavaBeans or RESTful web service should be responsible for data persistence, so there will be opportunities to integrate Hibernate, JPA and Spring Boot web services. We could also invoke the Spring Boot RESTful web service example through a Spring MVC app or a Spring RestTemplate instead of CURL, and of course, it would be nice to package this app in an executable JAR file with an embedded Tomcat or embedded WebSphere Liberty server and deploy it as a microservice. But all of those things would complicate the example and distract from the core purpose, which is to demonstrate just how easy it is to develop a RESTful Spring web service using the Spring Boot framework.

These aforementioned issues will be addressed in subsequent tutorials. The source code for this step-by-step Spring Boot RESTful web services example can be found on GitHub.

Spring Boot and Embedded Servers – Tomcat, Jetty and Undertow

http://www.springboottutorial.com/spring-boot-with-embedded-servers-tomcat-jetty

 


This guide will help you understand why embedded servers are gaining popularity. We will discuss the different options that Spring Boot supports – Tomcat, Jetty and Undertow.

You will learn

  • What is an embedded server?
  • Why are embedded servers getting popular?
  • What are the different embedded servers that Spring Boot supports?
  • How do you switch from one embedded server to another?

What is an Embedded Server?

Think about what you would need to be able to deploy your application (typically) on a virtual machine.

  • Step 1 : Install Java
  • Step 2 : Install the Web/Application Server (Tomcat/Websphere/Weblogic etc)
  • Step 3 : Deploy the application war

What if we want to simplify this?

How about making the server a part of the application?

You would just need a virtual machine with Java installed and you would be able to directly deploy the application on the virtual machine. Isn’t it cool?

This idea is the genesis for Embedded Servers.

When we create an application deployable, we would embed the server (for example, tomcat) inside the deployable.

For example, for a Spring Boot Application, you can generate an application jar which contains Embedded Tomcat. You can run a web application as a normal Java application!

Embedded server implies that our deployable unit contains the binaries for the server (example, tomcat.jar).

Creating an Embedded Server Project with Spring Initializr

Spring Initializr http://start.spring.io/ is great tool to bootstrap your Spring Boot projects.

Image

As shown in the image above, following steps have to be done

  • Launch Spring Initializr and choose the following
    • Choose com.in28minutes.springboot.tutorial.basics.example as Group
    • Choose spring-boot-tutorial-basics as Artifact
    • Choose following dependencies
      • Web
      • DevTools
  • Click Generate Project.
  • Import the project into Eclipse. File -> Import -> Existing Maven Project.

Default Embedded Server with Spring Boot – Tomcat

We have included Spring Boot Starter Web in our dependencies when creating the spring boot project.

Let’s take a quick look at the dependencies for spring-boot-starter-web

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-tomcat</artifactId>
  <version>2.0.0.RELEASE</version>
  <scope>compile</scope>
</dependency>

You can see that by default Starter Web includes a dependency on starter tomcat.

Starter Tomcat has the following dependencies.

<dependency>
  <groupId>org.apache.tomcat.embed</groupId>
  <artifactId>tomcat-embed-core</artifactId>
  <version>8.5.23</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.apache.tomcat.embed</groupId>
  <artifactId>tomcat-embed-el</artifactId>
  <version>8.5.23</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.apache.tomcat.embed</groupId>
  <artifactId>tomcat-embed-websocket</artifactId>
  <version>8.5.23</version>
  <scope>compile</scope>
</dependency>

Starter Tomcat brings in all the dependencies need to run Tomcat as an embedded server.

Run the web application using an Embedded Server

When you run SpringBootTutorialBasicsApplication.java as a Java Application, you would see that the server would start up and start serving requests.

An extract from the log

o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)

You can see that tomcat has started by default on port 8080.

You can customize the port in application.properties

server.port=9080

When you do a ‘mvn clean install’ on the project, a jar artifact named spring-boot-tutorial-basics-0.0.1-SNAPSHOT.jar is generated.

This jar can be used to run the application on any machine where Java 8 is installed.

The tomcat embedded server is also packaged inside this jar

Using Jetty as Embedded Server with Spring Boot

Remove the existing dependency on spring-boot-starter-web and add these in.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

Using Undertow as Embedded Server with Spring Boot

Remove the existing dependency on spring-boot-starter-web and add these in.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>

Embedded Server Spring Boot Configuration

Spring Boot provides a number of options to configure the embedded server through application.properties

# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.compression.enabled=false # If response compression is enabled.
server.context-path= # Context path of the application.
server.display-name=application # Display name of the application.
server.error.include-stacktrace=never # When to include a "stacktrace" attribute.
server.error.path=/error # Path of the error controller.
server.error.whitelabel.enabled=true # Enable the default error page displayed in browsers in case of a server error.
server.port=8080 # Server HTTP port.
server.server-header= # Value to use for the Server response header (no header is sent if empty)
server.servlet-path=/ # Path of the main dispatcher servlet.

Here are a few Jetty specific options

server.jetty.acceptors= # Number of acceptor threads to use.
server.jetty.max-http-post-size=0 # Maximum size in bytes of the HTTP post or put content.
server.jetty.selectors= # Number of selector threads to use.

You can also configure ssl on the embedded server

server.ssl.ciphers= # Supported SSL ciphers.
server.ssl.client-auth= # Whether client authentication is wanted ("want") or needed ("need"). Requires a trust store.
server.ssl.enabled= # Enable SSL support.
server.ssl.enabled-protocols= # Enabled SSL protocols.
server.ssl.key-alias= # Alias that identifies the key in the key store.
server.ssl.key-password= # Password used to access the key in the key store.
server.ssl.key-store= # Path to the key store that holds the SSL certificate (typically a jks file).
server.ssl.key-store-password= # Password used to access the key store.
server.ssl.key-store-provider= # Provider for the key store.
server.ssl.key-store-type= # Type of the key store.
server.ssl.protocol=TLS # SSL protocol to use.
server.ssl.trust-store= # Trust store that holds SSL certificates.
server.ssl.trust-store-password= # Password used to access the trust store.
server.ssl.trust-store-provider= # Provider for the trust store.
server.ssl.trust-store-type= # Type of the trust store.

A few tomcat specific properties are listed below

server.tomcat.accept-count= # Maximum queue length for incoming connection requests when all possible request processing threads are in use.
server.tomcat.accesslog.directory=logs # Directory in which log files are created. Can be relative to the tomcat base dir or absolute.
server.tomcat.accesslog.enabled=false # Enable access log.
server.tomcat.basedir= # Tomcat base directory. If not specified a temporary directory will be used.
server.tomcat.max-connections= # Maximum number of connections that the server will accept and process at any given time.
server.tomcat.max-threads=0 # Maximum amount of worker threads.
server.tomcat.uri-encoding=UTF-8 # Character encoding to use to decode the URI.

For complete list options refer spring documentation – https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

Tutorial: Use Spring Boot to Build and Deploy WAR Files

https://stormpath.com/blog/tutorial-spring-boot-war-files

Spring Boot makes it easy to create stand-alone Java web applications. However in production environments, a web container often already exists. How do we deploy our apps in these situations and have them run side-by-side with other servlets? In this tutorial, we’ll walk through how to use WAR files to do just that.

Getting Started with With Spring Boot, Tomcat, and WAR Files

In a previous tutorial, we built a simple RESTful web app using Spring Boot. I’m going to use this as a base and show how to deploy it into a container. You can grab the code for this tutorial on GitHub.

To ensure an existing Spring Boot app is container-ready one needs do three things
– Renaming the embedded Tomcat libraries
– Repackage the output file as a WAR
– Wire the application up as a servlet

Tomcat Libraries

Building a Spring Boot application produces a runnable jar file by default. If your app includes server functionality, then Tomcat will be bundled with it. We need to ensure the Tomcat libraries don’t clash with an existing container (since the container will include the same libraries).

When we do a clean clone of our repo (grab the code on GitHub if you haven’t yet) and do an mvn clean package we end up with a target directory containing our runnable jar.

This jar contains Tomcat libraries. To confirm this, we can rename it to .zip and look at the lib directory.
LIB Tomcat

You’ll see various .jar files starting with tomcat-. Some of these will clash with a running instance of Tomcat. We need to tell Spring Boot to move them.

To WAR! AKA: Build Your WAR Files

First, we must tell Spring Boot we want a WAR file as output. This is as easy as adding one line to our pom.xml.

Now when we build the package with

we will see a .war file inside our target directory:
WAR file in target directory

As before we can rename the file to .zip to see what’s inside. Everything is basically the same, just slightly re-ordered. Now lib is inside of WEB-INF anddemo` (where our project code sits) is in WEB-INF/classes.
Web INF Files

Renaming Tomcat

Next, we tell Spring Boot to move our Tomcat libraries out of this folder. In our previous pom.xml we included three dependencies for our project – one for REST, one for data access, and another for the database.

Now we append the Spring Boot Tomcat Starter to this (which links to the Tomcat libraries you need when embedding) and set the scope of the dependency to provided.

This will still include the .jar files as before but will put them in a new folder called lib-provided.

We can see this if we follow the same procedure as before. Once we mvn clean package and rename our .war to .zip we’ll see inside WEB-INF the new folder has appeared. Inside are all the embedded Tomcat libraries (and you’ll see they are no longer in lib).
Embedded Tomcat Libraries

Now our application will happily reside in a servlet container without clashing with its libraries.

Setting Up a Servlet

The only other thing we need to do is wire our application up to start as a servlet. And to do this we need to modify our application definition.

In the REST app mentioned our Application.java used the SpringBootApplication annotation on the main class and defined a main method.

To set the app up as a servlet we extend the main class with SpringBootServletInitializer and override the configure method using SpringApplicationBuilder.

And that’s it! This application will now happily run inside a Tomcat container!

Installing Tomcat

Deploying WAR files to Tomcat is as easy as copying the file to Tomcat’s webapps directory. But first, you need to install Tomcat. On Ubuntu, you can use apt-get.

This will install and start the server automatically on port 8080.

On Windows it’s just as easy – download and extract the binary distribution .zip file and run startup.bat in the bin directory. This will open up a console window showing the output of Catalina.
Tomcat Console

In both cases, you can check to see if everything is running by browsing to localhost:8080. You should see the Tomcat default homepage.
Tomcat

(Who knew Tomcat was so easy to use?!)

Copy the WAR File

The last step is copying the WAR to webapps. Here the name is important – whatever filename we choose will be used to map HTTP requests to our application. (All done automatically! I think this is amazing.) In an attempt to be more URL-friendly, I’m going to use demo.war.

On Ubuntu, this can be done with:

In Windows, use Explorer for the copy and then wait for the console window to show deployment messages.
WAR Deployment Message

And that’s it! Just by copying one file across our app is automatically booted and running side-by-side with the default Tomcat servlet.

Test Your WAR File Deployment

As before we test this by making calls using curl. Normally we called get on localhost but now our application is mapped to /demo/.

This shows you available URLs. To see what people objects are available you can use:

Or, create new ones with:

Note: In my testing I found the deploy on Windows to be somewhat brittle. Sometimes I needed to close and rerun startup.bat.

Run as a Standalone Application

One last thing – because our Tomcat libraries are still there (just moved) we are able to run this application on it’s own. So mvn spring-boot:run still works !

How To Set Up LAMP on Ubuntu 14.04

How To Set Up an Apache, MySQL, and Python (LAMP) Server Without Frameworks on Ubuntu 14.04

Introduction

This article will walk you through setting up a server with Python 3, MySQL, and Apache2, sans the help of a framework. By the end of this tutorial, you will be fully capable of launching a barebones system into production.

Django is often the one-shop-stop for all things Python; it’s compatible with nearly all versions of Python, comes prepackaged with a custom server, and even features a one-click-install database. Setting up a vanilla system without this powerful tool can be tricky, but earns you invaluable insight into server structure from the ground up.

This tutorial uses only package installers, namely apt-get and Pip. Package installers are simply small programs that make code installations much more convenient and manageable. Without them, maintaining libraries, modules, and other code bits can become an extremely messy business.

Prerequisites

To follow this tutorial, you will need:

  • One Ubuntu 14.04 Droplet.
  • A sudo non-root user, which you can set up by following this tutorial.

Step 1 — Making Python 3 the Default

In this step, we will set Python 3 as the default for our python command.

First, check your current Python version.

  • python –version

On a fresh Ubuntu 14.04 server, this will output:

Python 2.7.6

We would like to have python run Python 3. So first, let’s remove the old 2.7 binary.

  • sudo rm /usr/bin/python

Next, create a symbolic link to the Python 3 binary in its place.

  • sudo ln -s /usr/bin/python3 /usr/bin/python

If you run python --version again, you will now see Python 3.4.0.

Step 2 — Installing Pip

In this section, we will install Pip, the recommended package installer for Python.

First, update the system’s package index. This will ensure that old or outdated packages do not interfere with the installation.

  • sudo apt-get update

Pip allows us to easily manage any Python 3 package we would like to have. To install it, simply run the following:

  • sudo apt-get install python3-pip

For an overview of Pip, you can read this tutorial.

Step 3 — Installing MySQL

In this section, we will install and configure MySQL.

Installing SQL is simple:

  • sudo apt-get install mysql-server

Enter a strong password for the MySQL root user when prompted, and remember it, because we will need it later.

The MySQL server will start once installation completes. After installation, run:

  • mysql_secure_installation

This setup will take you through a series of self-explanatory steps. First, you’ll need to enter the root password you picked a moment ago. The first question will ask if you want to change the root password, but because you just set it, enter n. For all other questions, press ENTER to accept the default response.

Python 3 requires a way to connect with MySQL, however. There are a number of options, like MySQLclient, but for the module’s simplicity, this tutorial will use pymysql. Install it using Pip:

  • sudo pip3 install pymysql

Step 4 — Installing Apache 2

In this section, we will install Apache 2, and ensure that it recognizes Python files as executables.

Install Apache using apt-get:

  • sudo apt-get install apache2

Like MySQL, the Apache server will start once the installation completes.

Note: After installation, several ports are open to the internet. Make sure to see the conclusion of this tutorial for resources on security.

We want to place our website’s root directory in a safe location. The server is by default at /var/www/html. To keep convention, we will create a new directory for testing purposes, called test, in the same location.

  • sudo mkdir /var/www/test

Finally, we must register Python with Apache. To start, we disable multithreading processes.

  • sudo a2dismod mpm_event

Then, we give Apache explicit permission to run scripts.

  • sudo a2enmod mpm_prefork cgi

Next, we modify the actual Apache configuration, to explicitly declare Python files as runnable file and allow such executables. Open the configuration file using nano or your favorite text editor.

  • sudo nano /etc/apache2/sites-enabled/000-default.conf

Add the following right after the first line, which reads <VirtualHost *:80\>.

<Directory /var/www/test>
    Options +ExecCGI
    DirectoryIndex index.py
</Directory>
AddHandler cgi-script .py

Make sure that your <Directory> block is nested inside the <VirtualHost> block, like so. Make sure to indent correctly with tabs, too.

/etc/apache2/sites-enabled/000-default.conf

<VirtualHost *:80>
    <Directory /var/www/test>
        Options +ExecCGI
        DirectoryIndex index.py
    </Directory>
    AddHandler cgi-script .py

    ...

This Directory block allows us to specify how Apache treats that directory. It tells Apache that the /var/www/test directory contains executables, considers index.py to be the default file, then defines the executables.

We also want to allow executables in our website directory, so we need to change the path for DocumentRoot, too. Look for the line that reads DocumentRoot /var/www/html, a few lines below the long comment at the top of the file, and modify it to read /var/www/test instead.

DocumentRoot /var/www/test

Your file should now resemble the following.

/etc/apache2/sites-enabled/000-default.conf

<VirtualHost *:80>
        <Directory /var/www/test>
                Options +ExecCGI
                DirectoryIndex index.py
        </Directory>
        AddHandler cgi-script .py

        ...

        DocumentRoot /var/www/test

        ...

Save and exit the file. To put these changes into effect, restart Apache.

  • sudo service apache2 restart

Note: Apache 2 may throw a warning which says about the server’s fully qualified domain name; this can be ignored as the ServerName directive has little application as of this moment. They are ultimately used to determine subdomain hosting, after the necessary records are created.

If the last line of the output reads [ OK ], Apache has restarted successfully.

Step 5 — Testing the Final Product

In this section, we will confirm that individual components (Python, MySQL, and Apache) can interact with one another by creating an example webpage and database.

First, let’s create a database. Log in to MySQL. You’ll need to enter the MySQL root password you set earlier.

  • mysql -u root -p

Add an example database called example.

  • CREATE DATABASE example;

Switch to the new database.

  • USE example;

Add a table for some example data that we’ll have the Python app add.

  • CREATE TABLE numbers (num INT, word VARCHAR(20));

Press CTRL+D to exit. For more background on SQL, you can read this MySQL tutorial.

Now, create a new file for our simple Python app.

  • sudo nano /var/www/test/index.py

Copy and paste the following code in. The in-line comments describe what each piece of the code does. Make sure to replace the passwd value with the root MySQL password you chose earlier.

#!/usr/bin/python

# Turn on debug mode.
import cgitb
cgitb.enable()

# Print necessary headers.
print("Content-Type: text/html")
print()

# Connect to the database.
import pymysql
conn = pymysql.connect(
    db='example',
    user='root',
    passwd='your_root_mysql_password',
    host='localhost')
c = conn.cursor()

# Insert some example data.
c.execute("INSERT INTO numbers VALUES (1, 'One!')")
c.execute("INSERT INTO numbers VALUES (2, 'Two!')")
c.execute("INSERT INTO numbers VALUES (3, 'Three!')")
conn.commit()

# Print the contents of the database.
c.execute("SELECT * FROM numbers")
print([(r[0], r[1]) for r in c.fetchall()])

Save and exit.

Next, fix permissions on the newly-created file. For more information on the three-digit permissions code, see the tutorial on Linux permissions.

  • sudo chmod 755 /var/www/test/index.py

Now, access your server’s by going to http://your_server_ip using your favorite browser. You should see the following:

your_server_ip’>http://your_server_ip
[(1, 'One!'), (2, 'Two!'), (3, 'Three!')]

Congratulations! Your server is now online.

Conclusion

You now have a working server that can run Python 3 with a robust, SQL database. The server is now also configured for easy maintenance, via well-documented and established package installers.

However, in its current state, the server is vulnerable to outsiders. Whereas elements like SSL encryption are not essential to your server’s function, they are indispensable resources for a reliable, safe server. Learn more by reading about how to configure Apachehow to create an Apache SSL certificate and how to secure your Linux server.

https://www.digitalocean.com/community/tutorials/how-to-set-up-an-apache-mysql-and-python-lamp-server-without-frameworks-on-ubuntu-14-04

Stack & Heap Memory

What is the difference between the stack and the heap?

This question is likely related to wanting a better understanding of how local variables are stored versus explicitly dynamically allocated variables.

Function parameters and local variables are generally allocated on a stack. A stack, in computer terms, is basically a linear structure in memory where information (values for variables, for example) are stored sequentially with the most recently added value at the “top” or the end of the memory structure from which values are also read and removed. This allows a function to call itself recursively, and have separate copies of all its parameters and local variables retained separately for each call. The variable values are all “pushed” onto the stack, and then execution begins with a new set of values in the new call. When the function returns, the variable values are restored by “popping” the values from the “top” of the stack in reverse order, thus restoring the previous values of all the variables.

A heap is generally used for larger data structures or memory that the programmer wants to explicitly manage. Whenever “new” or “malloc” is used in C++ or C respectively, the memory for that request is allocated on a heap, and then it’s up to the coder to make sure that is gets freed at the appropriate time with “delete” or “free”. Whereas stack data is usually easy to manage because the compiler allocates and frees the space, heap data is easy to mess up because it often requires manually written code to determine when it gets allocated and freed. But it’s appropriate if you want to manage large long-lived blocks of memory independently of the scope of a function. And although all memory in a computer is linear at some level, a heap is less linear in the way it’s managed because it maintains pointers to different areas of memory making it easier to allocate and free blocks of memory in an arbitrary sequence instead of strictly in reverse order.

 

Stack and heap differ in the following ways:

  1. Memory Allocation: Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer’s RAM .
  2. Variables: Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it’s allocation is dealt with when the program is compiled. When a function or a method calls another function which in turns calls another function etc., the execution of all those functions remains suspended until the very last function returns its value. Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory.
  3. Access: The stack is always reserved in a LIFO order, the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack, freeing a block from the stack is nothing more than adjusting one pointer. Element of the heap have no dependencies with each other and can always be accessed randomly at any time. You can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time.

When to use stack and when to use heap?

You can use the stack if you know exactly how much data you need to allocate before compile time and it is not too big. You can use heap if you don’t know exactly how much data you will need at runtime or if you need to allocate a lot of data.

In a multi-threaded situation each thread will have its own completely independent stack but they will share the heap. Stack is thread specific and Heap is application specific. The stack is important to consider in exception handling and thread executions.

 

https://www.quora.com/What-is-the-difference-between-the-stack-and-the-heap

https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap

Show Buttons
Hide Buttons