Install node js on your computer if you haven’t done so. Here is the link.
Create your project by using this command:
npx create-react-app your-app-name For example: npx create-react-app pizza
Go into your app using this command:
cd your-app-name
Start your application using this command:
npm start
Congratulations! You have just set up your react project.
August 6, 2019Thymeleaf is a template language that helps serve static files.
Add dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
Controller methods
Use Model class to pass data to html files
@Api(value = "home", tags = "HomeController") @Slf4j @Controller public class HomeController { @GetMapping public String showHome(Model model, @RequestParam String name) { log.info("home"); model.addAttribute("name", name); return "index"; } }
Static files
HTML files
<!DOCTYPE HTML> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Spring Boot Thymeleaf Hello World Example</title> <!-- CSS only --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <link rel="stylesheet" href="/css/style.css"> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top"> <a class="navbar-brand" href="#">folaukaveinga.org</a> </nav> <main role="main" class="container"> <div class="starter-template"> <h1>Spring Boot Web Thymeleaf Example</h1> <h2> Hello, <span id="name" th:text="${name}"></span> </h2> </div> </main> <!-- /.container --> <!-- JS, Popper.js, and jQuery --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> </body> </html>
CSS files
resources/static/css/style.css
#name{ color: blue; }
Js files
resources/static/js/index.js
$(function() { $("#sayHiBtn").click(function() { alert("Hello World!"); }); });
Swagger is an open source project used to generate the REST API documents for RESTful web services.
Add swagger and swagger-ui dependencies
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
Add Swagger Config class
@PropertySource("classpath:swagger.properties") @Configuration @EnableSwagger2 public class SwaggerConfig { private Logger log = LoggerFactory.getLogger(this.getClass()); @Bean public Docket api() { log.info("setting up Docket.."); Docket docket = new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.folaukaveinga")) .paths(PathSelectors.any()).build().apiInfo(getApiInfo()); log.info("docket setup!"); return docket; } private ApiInfo getApiInfo() { Contact contact = new Contact("Folau Kaveinga", "folaukaveinga.org", "folaukaveinga@gmail.com"); return new ApiInfoBuilder() .title("Spring Data Tutorial") .description("Spring Data API") .version("1.0.0") .contact(contact) .build(); } }
Anotate controller classes
@Api(value = "users", produces = "Rest API for User operations", tags = "User Controller") @RestController @RequestMapping("/users") public class UserController { private Logger log = LoggerFactory.getLogger(this.getClass()); @Autowired private UserService userService; @ApiOperation(value = "Get Member By Id") @GetMapping("/{id}") public ResponseEntity<User> getUserById(@ApiParam(name = "id", required = true, value = "id of member") @PathVariable("id") Long id) { log.info("get user by id: {}", id); return new ResponseEntity<>(userService.getById(id), HttpStatus.OK); } }
A Data Transfer Object(DTO) is an object that is used to encapsulate data or domain model, and send it from one subsystem of an application to another. DTOs are most commonly used by the Services layer in an N-Tier application to transfer data between itself and the UI layer.Mapstruct is by far the best DTO generator I have worked with for many reasons. Here is the official site.
... <properties> <org.mapstruct.version>1.3.1.Final</org.mapstruct.version> </properties> ... <dependencies> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> <version>${org.mapstruct.version}</version> </dependency> </dependencies> ... <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <!-- or newer version --> <configuration> <source>1.8</source> <!-- depending on your project --> <target>1.8</target> <!-- depending on your project --> <annotationProcessorPaths> <path> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>${org.mapstruct.version}</version> </path> <!-- other annotation processors --> </annotationProcessorPaths> </configuration> </plugin> </plugins> </build>
Create a Mapper interface
@Mapper(componentModel = "spring", nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS, unmappedTargetPolicy = ReportingPolicy.IGNORE) public interface CarMapper { CarMapper INSTANCE = Mappers.getMapper( CarMapper.class ); @Mapping(source = "numberOfSeats", target = "seatCount") CarDto carToCarDto(Car car); }
Model
public class Car { private String make; private int numberOfSeats; private CarType type; //constructor, getters, setters etc. }
DTO
public class CarDto { private String make; private int seatCount; private String type; //constructor, getters, setters etc. }
.... Car car = new Car( "Morris", 5, CarType.SEDAN ); //when CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
You can use Springboot to send out emails. All you need is access SMTP server. You can then use the JavaMailSender interface to send emails out.
Add dependency
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
Add email SMTP server configuration settings to application.properties
#mail spring.mail.host=smtp.gmail.com spring.mail.username=username spring.mail.password=password spring.mail.port=587 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.debug=true spring.mail.properties.mail.sender=senderEmail@gmail.com
EmailService
import java.io.IOException; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; @Service public class EmailServiceImp implements EmailService { @Autowired private JavaMailSender mailSender; // This is for aws ses mail. Sender email needs to be verified first before using it as a sender email. @Value("${spring.mail.properties.mail.sender}") private String sender; @Override public boolean sendSimpleMail(String to, String subject, String msg) { SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); simpleMailMessage.setTo(to); simpleMailMessage.setSubject(subject); simpleMailMessage.setText(msg); simpleMailMessage.setFrom(sender); try { mailSender.send(simpleMailMessage); return true; } catch (Exception e) { System.out.println("Exception, send. msg: " + e.getMessage()); return false; } } @Override public boolean sendAttachmentMail(String to, String subject, String msg, String attachmentPath) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); helper.setText(msg); helper.setFrom(sender); ClassPathResource attachment = new ClassPathResource(attachmentPath); helper.addAttachment(attachment.getFile().getName(), attachment.getFile()); mailSender.send(message); return true; } catch (MessagingException e) { System.out.println("Exception, send. msg: " + e.getMessage()); return false; } catch (IOException e) { System.out.println("Exception, send. msg: " + e.getMessage()); return false; } } /* * It's recommended that when sending html emails that you use table to structure and style * your email. * */ @Override public boolean sendHtmlMail(String to, String subject, String msg) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); helper.setText(msg, true); helper.setFrom(sender); mailSender.send(message); return true; } catch (MessagingException e) { System.out.println("Exception, send. msg: " + e.getMessage()); return false; } } /* * It's recommended that when sending html emails that you use table to structure and style * your email. * */ @Override public boolean sendHtmlWithInlineImageMail(String to, String subject, String msg, String logoPath) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); helper.setText(msg,true); helper.setFrom(sender); // cid:log helper.addInline("logo", new ClassPathResource(logoPath)); mailSender.send(message); return true; } catch (MessagingException e) { System.out.println("Exception, send. msg: " + e.getMessage()); return false; } } }