onlinetutorialspoint http://www.onlinetutorialspoint.com Wed, 21 Feb 2018 09:02:39 +0000 en hourly 1 https://wordpress.org/?v=4.9.4 http://www.onlinetutorialspoint.com/wp-content/uploads/2016/01/cropped-apple-icon-152x152-32x32.png onlinetutorialspoint http://www.onlinetutorialspoint.com 32 32 How to set Spring Boot SetTimeZone http://www.onlinetutorialspoint.com/spring-boot/how-to-set-spring-boot-settimezone.html http://www.onlinetutorialspoint.com/spring-boot/how-to-set-spring-boot-settimezone.html#respond Wed, 21 Feb 2018 09:02:39 +0000 http://www.onlinetutorialspoint.com/?p=5372 In this tutorials, I am going to show how to set/change time zone in spring boot application. Spring Boot SetTimeZone : JVM will take the defalttime zone as server’s time zone. If the server is runingon IST, JVM takes the IST time one as default. In Spring boot we can easyly change/set this defalt timezone …

The post How to set Spring Boot SetTimeZone appeared first on onlinetutorialspoint.

]]>
In this tutorials, I am going to show how to set/change time zone in spring boot application.

Spring Boot SetTimeZone :

JVM will take the defalttime zone as server’s time zone. If the server is runingon IST, JVM takes the IST time one as default.

In Spring boot we can easyly change/set this defalt timezone using java.util.TimeZone class like below.

Application.java

package com.onlinetutorialspoint.SpringBoot_Custom_ErrorPage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.TimeZone;

@SpringBootApplication
public class Application {
  @PostConstruct
  public void init(){
    // Setting Spring Boot SetTimeZone
    TimeZone.setDefault(TimeZone.getTimeZone("IST"));
  }
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

Run Application :

[INFO] --- spring-boot-maven-plugin:1.5.10.RELEASE:run (default-cli) @ SpringBoot_Custom_ErrorPage ---

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v1.5.10.RELEASE)

2018-02-17 20:43:21.353  INFO 10356 --- [           main] c.o.S.Application                        : Starting Application on DESKTOP-RN4SMHT with PID 10356 (E:\work\SpringBoot_Custom
_ErrorPage\target\classes started by Lenovo in E:\work\SpringBoot_Custom_ErrorPage)
2018-02-17 20:43:21.353  INFO 10356 --- [           main] c.o.S.Application                        : No active profile set, falling back to default profiles: default
2018-02-17 20:43:21.462  INFO 10356 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebA
pplicationContext@62f32a29: startup date [Sat Feb 17 20:43:21 IST 2018]; root of context hierarchy
2018-02-17 20:43:24.572  INFO 10356 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)

You can see the updated time zone while  running application (highlighted) above.

Happy Learning 🙂

The post How to set Spring Boot SetTimeZone appeared first on onlinetutorialspoint.

]]>
http://www.onlinetutorialspoint.com/spring-boot/how-to-set-spring-boot-settimezone.html/feed 0
How to Set Spring Boot Custom Banner http://www.onlinetutorialspoint.com/spring-boot/how-to-set-spring-boot-custom-banner.html http://www.onlinetutorialspoint.com/spring-boot/how-to-set-spring-boot-custom-banner.html#respond Tue, 20 Feb 2018 01:42:10 +0000 http://www.onlinetutorialspoint.com/?p=5399 While running the Spring Boot application we can see the below default banner. . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | …

The post How to Set Spring Boot Custom Banner appeared first on onlinetutorialspoint.

]]>
While running the Spring Boot application we can see the below default banner.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v1.5.10.RELEASE)

If we want to replace your application’s name instead default spring banner, we can do that, here I am going to show how to set Spring Boot Custom Banner.

 _   _  _____  _      _      ___
| | | || ____|| |    | |    / _ \
| |_| ||  _|  | |    | |   | | | |
|  _  || |___ | |___ | |___| |_| |
|_| |_||_____||_____||_____|\___/

Spring Boot Custom Banner :

Create your custom banner using ASCII art and paste banner.txt file under resources folder like below.

Spring Boot Custom Banner

banner.txt

 _   _  _____  _      _      ___  
| | | || ____|| |    | |    / _ \ 
| |_| ||  _|  | |    | |   | | | |
|  _  || |___ | |___ | |___| |_| |
|_| |_||_____||_____||_____|\___/

Run Application :

By running the application you can see the updated banner.

Spring Boot Custom Banner Out

Happy Learning 🙂

The post How to Set Spring Boot Custom Banner appeared first on onlinetutorialspoint.

]]>
http://www.onlinetutorialspoint.com/spring-boot/how-to-set-spring-boot-custom-banner.html/feed 0
How to set Spring boot favicon image http://www.onlinetutorialspoint.com/spring-boot/how-to-set-spring-boot-favicon-image.html http://www.onlinetutorialspoint.com/spring-boot/how-to-set-spring-boot-favicon-image.html#respond Mon, 19 Feb 2018 02:07:05 +0000 http://www.onlinetutorialspoint.com/?p=5363 In this tutorials I am going to show how to set Spring boot favicon .ico in Spring boot application. Spring boot favicon : In spring boot it is very easy to set favicon.ico, here I am giving simple to steps to achieve this. Step 1 : Generate your favicon.ico file, if you do not have …

The post How to set Spring boot favicon image appeared first on onlinetutorialspoint.

]]>
In this tutorials I am going to show how to set Spring boot favicon .ico in Spring boot application.

Spring boot favicon :

In spring boot it is very easy to set favicon.ico, here I am giving simple to steps to achieve this.

Step 1 : Generate your favicon.ico file, if you do not have here.

Step 2 : And place the created favicon.ico file under class path location. Spring boot checks for the default/classpath location to set the favicon.ico file.

We should place the favicon.ico file in appropriate location like below resources/static/.

 

Spring Boot Favicon

 

Step 3 : Run the application

Refresh web page (Ctrl+f5)

Spring Boot Favicon output

Reference :

spring boot favicon docs

Happy Learning 🙂

The post How to set Spring boot favicon image appeared first on onlinetutorialspoint.

]]>
http://www.onlinetutorialspoint.com/spring-boot/how-to-set-spring-boot-favicon-image.html/feed 0
How to set Spring Boot Tomcat session timeout http://www.onlinetutorialspoint.com/spring-boot/how-to-set-spring-boot-tomcat-session-timeout.html http://www.onlinetutorialspoint.com/spring-boot/how-to-set-spring-boot-tomcat-session-timeout.html#respond Sun, 18 Feb 2018 03:36:55 +0000 http://www.onlinetutorialspoint.com/?p=5359 In this tutorials, I am going to show how to set/change Tomcat session timeout in Spring boot application. Spring Boot Tomcat session timeout : We should be able to set the server.session.timeout in application.properties or application.yml file. server.session.timeout = 5000 // Session timeout in seconds Most of the cases the above configuration will work, If …

The post How to set Spring Boot Tomcat session timeout appeared first on onlinetutorialspoint.

]]>
In this tutorials, I am going to show how to set/change Tomcat session timeout in Spring boot application.

Spring Boot Tomcat session timeout :

We should be able to set the server.session.timeout in application.properties or application.yml file.

server.session.timeout = 5000 // Session timeout in seconds

Most of the cases the above configuration will work, If not you should set the cookie max age along with session time out like below.

server.session.cookie.max-age=5000
server.session.timeout=5000

Reference :

Spring boot config

Happy Learning 🙂

The post How to set Spring Boot Tomcat session timeout appeared first on onlinetutorialspoint.

]]>
http://www.onlinetutorialspoint.com/spring-boot/how-to-set-spring-boot-tomcat-session-timeout.html/feed 0
How to Create own Spring Boot Error Page http://www.onlinetutorialspoint.com/spring-boot/create-spring-boot-error-page.html http://www.onlinetutorialspoint.com/spring-boot/create-spring-boot-error-page.html#respond Fri, 16 Feb 2018 03:34:43 +0000 http://www.onlinetutorialspoint.com/?p=5341 In this tutorials I am going to show how to create our own custom Spring Boot Error Page instead of showing generic error pages like while label error. Custom Spring Boot Error Page : Technologies : Spring_Boot_1.5.10.RELEASE Java8 IntelliJ Idea Project Structure : pom.xml <?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>com.onlinetutorialspoint</groupId> <artifactId>SpringBoot_Custom_ErrorPage</artifactId> …

The post How to Create own Spring Boot Error Page appeared first on onlinetutorialspoint.

]]>
In this tutorials I am going to show how to create our own custom Spring Boot Error Page instead of showing generic error pages like while label error.

Custom Spring Boot Error Page :

Technologies :

  • Spring_Boot_1.5.10.RELEASE
  • Java8
  • IntelliJ Idea

Project Structure :

Spring Boot Error Page

pom.xml

<?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>com.onlinetutorialspoint</groupId>
  <artifactId>SpringBoot_Custom_ErrorPage</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>SpringBoot_Custom_ErrorPage</name>
  <description>Demo project for Spring Boot</description>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.10.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-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

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


</project>

Spring Boot Custom Error Page Example :

Creating Error pages like 404 (Page Not Found) and 500 (Internal Server) and Etc..

Note : These pages should be available in classpath (resources).

400.html :

<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>404 Page no found</title>
    <meta name="viewport" content="width=device-width">
    <style>
        #error {
            border-color: darkred;
            background-color: aliceblue;
        }
        h2 {
            color: green;
        }
    </style>

</head>
<body>
<div class="error-page-wrap">
    <div id="error">
        <h2>oops! Requested page not found</h2>
    </div>
</div>
</body>
</html>

500.html

<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>500 Page</title>
    <meta name="viewport" content="width=device-width">
    <style>
        #error {
            border-color: darkred;
            background-color: aliceblue;
        }

        h3 {
            color: darkred;
        }
    </style>

</head>
<body>
<div class="error-page-wrap">
    <div id="error">
        <h3>Something went wrong ! Please try again later or contact our support @ 123456789</h3>
    </div>
</div>
</body>
</html>

Create Rest Controller :

Create your Spring Boot rest controller to access end points.

package com.onlinetutorialspoint.SpringBoot_Custom_ErrorPage;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MainController {
    @RequestMapping("/hello")
    public String sayHello() {
        int i = 5 / 0;
        return "hello Greetings !";
    }

    @RequestMapping("/user")
    public String user() {
        return "Hello user Greetings !";
    }
}

Application.java

package com.onlinetutorialspoint.SpringBoot_Custom_ErrorPage;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

Run It :

mvn clean install 
mvn spring-boot:run


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v1.5.10.RELEASE)

2018-02-16 21:45:30.060  INFO 11240 --- [           main] c.o.S.Application                        : Starting Application on DESKTOP-RN4SMHT with PID 11240 (E:\work\SpringBoot_Custom
_ErrorPage\target\classes started by Lenovo in E:\work\SpringBoot_Custom_ErrorPage)
2018-02-16 21:45:30.060  INFO 11240 --- [           main] c.o.S.Application                        : No active profile set, falling back to default profiles: default
2018-02-16 21:45:30.169  INFO 11240 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebA
pplicationContext@1738bc53: startup date [Fri Feb 16 21:45:30 IST 2018]; root of context hierarchy
2018-02-16 21:45:32.794  INFO 11240 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-02-16 21:45:32.825  INFO 11240 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-02-16 21:45:32.825  INFO 11240 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.27
2018-02-16 21:45:32.997  INFO 11240 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-02-16 21:45:32.997  INFO 11240 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2844 ms
2018-02-16 21:45:33.294  INFO 11240 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2018-02-16 21:45:33.310  INFO 11240 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-02-16 21:45:33.310  INFO 11240 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-02-16 21:45:33.310  INFO 11240 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-02-16 21:45:33.310  INFO 11240 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-02-16 21:45:33.825  INFO 11240 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.Annotati
onConfigEmbeddedWebApplicationContext@1738bc53: startup date [Fri Feb 16 21:45:30 IST 2018]; root of context hierarchy
2018-02-16 21:45:33.935  INFO 11240 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/user]}" onto public java.lang.String com.onlinetutorialspoint.SpringBo
ot_Custom_ErrorPage.MainController.user()
2018-02-16 21:45:33.950  INFO 11240 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello]}" onto public java.lang.String com.onlinetutorialspoint.SpringB
oot_Custom_ErrorPage.MainController.sayHello()
2018-02-16 21:45:33.950  INFO 11240 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util
.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-02-16 21:45:33.950  INFO 11240 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=}" onto public org.springframework.web.serv
let.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-02-16 21:45:34.013  INFO 11240 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web
.servlet.resource.ResourceHttpRequestHandler]
2018-02-16 21:45:34.013  INFO 11240 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet
.resource.ResourceHttpRequestHandler]
2018-02-16 21:45:34.075  INFO 11240 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework
.web.servlet.resource.ResourceHttpRequestHandler]

Access application :

Accessing unknown end point :

http://localhost:8080/unknown

Spring Boot Error Page 404

Internal Server Error handling :

http://localhost:8080/hello

Spring Boot Error Page 500

Accessing valid endpoint :

http://localhost:8080/user

Spring Boot Error Page Success

Happy Learning 🙂

The post How to Create own Spring Boot Error Page appeared first on onlinetutorialspoint.

]]>
http://www.onlinetutorialspoint.com/spring-boot/create-spring-boot-error-page.html/feed 0
Spring Form Custom Validation Example http://www.onlinetutorialspoint.com/spring/spring-form-custom-validation-example.html http://www.onlinetutorialspoint.com/spring/spring-form-custom-validation-example.html#respond Fri, 26 Jan 2018 05:05:20 +0000 http://www.onlinetutorialspoint.com/?p=5313 In this tutorial, I am going to show you how to validate Spring Form with Custom validations. In the previous tutorial, we had a discussion about a simple and basic form validation of spring form. For this Spring Form Custom Validation I am going to take the basic form to some extent. Technologies : Spring Framework …

The post Spring Form Custom Validation Example appeared first on onlinetutorialspoint.

]]>
In this tutorial, I am going to show you how to validate Spring Form with Custom validations.

In the previous tutorial, we had a discussion about a simple and basic form validation of spring form. For this Spring Form Custom Validation I am going to take the basic form to some extent.

Technologies :

  • Spring Framework 3.1.1.RELEASE
  • Hibernate Validator 4.2.0.Final
  • Jstl 1.2
  • Java 8

Spring Form Custom Validation :

Project Structure :

 

Spring MVC Custom Form Validation Project-min

Create your own annotation for custom validation.

Recommended : Spring Boot Login From Validation Example

CouponCode.java

I am going to create CouponCode anotation which validates whether provided coupon code valid or not.

package com.spring.customannotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Constraint(validatedBy = CouponCodeValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CouponCode {

	public String value() default "OTP";
	public String message() default "Coupon Code must starts with OTP";
	public Class<?>[] groups() default {};
	public Class<? extends Payload>[] payload() default{};
	
}

Applying Constraint validation using validation framework.

CouponCodeValidator.java


package com.spring.customannotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class CouponCodeValidator implements ConstraintValidator<CouponCode, String> {

	private String couponCodePrefix;

	public void initialize(CouponCode couponCode) {
		couponCodePrefix = couponCode.value();

	}
/*
* You can write your own validation logic here. For now I am doing simple validation here like 
* checking whether coupon code startes with "OTP" or not.
*/
	public boolean isValid(String couponCode, ConstraintValidatorContext constraintValidatorContext) {
		if (couponCode != null) {
			return couponCode.startsWith(couponCodePrefix);
		} else {
			return true;
		}
	}

}

Coupon code is valid iff, it startes with “OTP” otherwise it will throw default message like “Coupon Code must starts with OTP”.

RegistrationBean.java


package com.spring.controller;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import com.spring.customannotation.CouponCode;

public class RegistrationBean {

	@NotNull
	@Size(min = 1, message = "You can't leave this empty.")
	private String firstName;

	@NotNull
	@Size(min = 1, message = "You can't leave this empty.")
	private String lastName;

	@NotNull(message = "You can't leave this empty.")
	@Min(value = 13, message = "You must be greater than or equal to 13")
	@Max(value = 19, message = "You must be less than or equal to 19")
	private Integer age;

	@Pattern(regexp = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$", message = "Invalid email")
	private String email;
	
	@CouponCode
	private String couponCode;

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getCouponCode() {
		return couponCode;
	}

	public void setCouponCode(String couponCode) {
		this.couponCode = couponCode;
	}

}

RegistrationController.java


package com.spring.controller;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class RegistrationController {

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String showForm(Model model) {
		model.addAttribute("registration", new RegistrationBean());
		return "register";
	}

	@RequestMapping(value = "/processForm", method = RequestMethod.POST)
	public String processForm(@Valid @ModelAttribute("registration") RegistrationBean register,
			BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return "register";
		} else {
			return "success";
		}

	}
}

register.jsp

</pre>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring MVC Form Validation</title>
<style>
.error {
color: red
}
</style>
</head>
<body>
<form:form action="processForm" modelAttribute="registration">

<div align="center">
<h2>Register Here</h2>
<table>
<tr>
<td>First name</td>
<td><form:input type="text" path="firstName" /></td>
<td><form:errors path="firstName" cssClass="error" /></td>
</tr>
<tr>
<td>Last name (*)</td>
<td><form:input type="text" path="lastName" /></td>
<td><form:errors path="lastName" cssClass="error" /></td>
</tr>
<tr>
<td>Age </td>
<td><form:input type="text" path="age" /></td>
<td><form:errors path="age" cssClass="error" /></td>
</tr>
<tr>
<td>Email </td>
<td><form:input type="text" path="email" /></td>
<td><form:errors path="email" cssClass="error" /></td>
</tr>
<tr>
<td>Coupon Code </td>
<td><form:input type="text" path="couponCode" /></td>
<td><form:errors path="couponCode" cssClass="error" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</div>
</form:form>
</body>
</html>
<pre>

success.jsp :


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Registration Confirmation</title>
</head>
<body>
	Hello <font color="green">${registration.firstName} ${registration.lastName} </font> you have successfully registered with us.
</body>
</html>

Test your Application :

http://localhost:8080/Spring-MVC-Custom-Form-Validation/register

Spring Custom Validation 2

Giving valid coupon code.

Spring Custom Validation 2 min

Success.jsp

Spring Custom Validation 3-min

Happy Learning 🙂

The post Spring Form Custom Validation Example appeared first on onlinetutorialspoint.

]]>
http://www.onlinetutorialspoint.com/spring/spring-form-custom-validation-example.html/feed 0
Spring MVC Form Validation Example http://www.onlinetutorialspoint.com/spring/spring-mvc-form-validation-example.html http://www.onlinetutorialspoint.com/spring/spring-mvc-form-validation-example.html#respond Sun, 21 Jan 2018 14:37:19 +0000 http://www.onlinetutorialspoint.com/?p=5286 Here I am going show a simple Spring MVC Form Validation Example. Technologies : Spring Framework 3.1.1.RELEASE Hibernate Validator 4.2.0.Final Jstl 1.2 Java 8 Spring MVC Form Validation : Here we are going to validate registration form with different fields like firstName, lastName, age, email by using simple spring validation framework. Project Structure :   …

The post Spring MVC Form Validation Example appeared first on onlinetutorialspoint.

]]>
Here I am going show a simple Spring MVC Form Validation Example.

Technologies :

  • Spring Framework 3.1.1.RELEASE
  • Hibernate Validator 4.2.0.Final
  • Jstl 1.2
  • Java 8

Spring MVC Form Validation :

Here we are going to validate registration form with different fields like firstName, lastName, age, email by using simple spring validation framework.

Project Structure :

Spring MVC Form Validation

 

Spring MVC Form Validation Example :

Dependencies : pom.xml


	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>4.2.0.Final</version>
		</dependency>

		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>

RegistrationBean.java

package com.spring.controller;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

public class RegistrationBean {

	@NotNull
	@Size(min = 1, message = "You can't leave this empty.")
	private String firstName;

	@NotNull
	@Size(min = 1, message = "You can't leave this empty.")
	private String lastName;

	@NotNull(message = "You can't leave this empty.")
	@Min(value = 13, message = "You must be greater than or equal to 13")
	@Max(value = 19, message = "You must be less than or equal to 19")
	private Integer age;

	@Pattern(regexp = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$", message = "Invalid email")
	private String email;

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

}

@NotNull : It won’t allow the null values.
@Min(13) : Won’t allow if the age is min of 13
@Max(19) : Won’t allow if the age is max of 19
@Pattern : Applyed given regex patten on specified field (our case it is email)

Registration Form : register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring MVC Form Validation</title>
<style>
.error {
color: red
}
</style>
</head>
<body>
<form:form action="processForm" modelAttribute="registration">

<div align="center">
<h2>Register Here</h2>
<table>
<tr>
<td>First name</td>
<td><form:input type="text" path="firstName" /></td>
<td><form:errors path="firstName" cssClass="error" /></td>
</tr>
<tr>
<td>Last name (*)</td>
<td><form:input type="text" path="lastName" /></td>
<td><form:errors path="lastName" cssClass="error" /></td>
</tr>
<tr>
<td>Age </td>
<td><form:input type="text" path="age" /></td>
<td><form:errors path="age" cssClass="error" /></td>
</tr>
<tr>
<td>Email </td>
<td><form:input type="text" path="email" /></td>
<td><form:errors path="email" cssClass="error" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</div>
</form:form>
</body>
</html>

Registration Controller : RegistrationController.java

package com.spring.controller;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class RegistrationController {

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String showForm(Model model) {
		model.addAttribute("registration", new RegistrationBean());
		return "register";
	}

	@RequestMapping(value = "/processForm", method = RequestMethod.POST)
	public String processForm(@Valid @ModelAttribute("registration") RegistrationBean register,
			BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return "register";
		} else {
			return "success";
		}

	}
}

properties file :

typeMismatch.registration.age=Invalid Number

Success page : success.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Registration Confirmation</title>
</head>
<body>
Hello <font color="green">${registration.firstName} ${registration.lastName} </font> you have successfully registered with us.
</body>
</html>

Run the application :

http://localhost:8080/Spring-MVC-Form-Validation/register

Spring MVC Form Validation

Invalid Form Fields :

Leaving all form fields empty.

Spring MVC Form Validation Error

Invalid Age :

Using @Max and @Min validations on age attribute.

Spring MVC Form Validation 3

Invalid Age Format :

Giving invalid age (Not a number) validation

Spring MVC Form Validation 5

Success Form :

Spring MVC Form Validation Success

Success Page :

Spring MVC Form Validation successpage

Happy Learning 🙂

The post Spring MVC Form Validation Example appeared first on onlinetutorialspoint.

]]>
http://www.onlinetutorialspoint.com/spring/spring-mvc-form-validation-example.html/feed 0
How to Send Mail Spring Boot Example http://www.onlinetutorialspoint.com/spring-boot/how-to-send-spring-boot-mail-example.html http://www.onlinetutorialspoint.com/spring-boot/how-to-send-spring-boot-mail-example.html#respond Mon, 01 Jan 2018 11:27:50 +0000 http://www.onlinetutorialspoint.com/?p=5247 In this tutorial, I am going to show you how to send mail with Spring Boot rest service. Technologies used : Spring_Boot_1.5.9.RELEASE Spring-Boot-Starter-Mail Java 8 Spring Boot Mail Dependency : To send a mail from spring boot application we should add the below dependency in pom.xml Spring Boot Mail Example : Here I am going …

The post How to Send Mail Spring Boot Example appeared first on onlinetutorialspoint.

]]>
In this tutorial, I am going to show you how to send mail with Spring Boot rest service.

Technologies used :

  • Spring_Boot_1.5.9.RELEASE
  • Spring-Boot-Starter-Mail
  • Java 8

Spring Boot Mail Dependency :

To send a mail from spring boot application we should add the below dependency in pom.xml


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

Spring Boot Mail Example :

Here I am going to implement a Simple Spring Boot Example to send a mail and also to send attachments through the mail.

Project Structure :

Spring Boot Mail Example

pom.xml


<?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>com.onlinetutorilspoint</groupId>
    <artifactId>SpringBoot_Mail_Example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>SpringBoot_Mail_Example</name>
    <description>Spring Boot Mail Example</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath />
    </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-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

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

Configure SMTP Properties in Spring Boot application.properties

application.properties :


spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=Your-Mail@gmail.com
spring.mail.password=password (App-Password generated from google tool)
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000

Note : The above-mentioned password for application is not ordinary password it is app specific password, you should generate your own application password from google here. And you should mention that App Password here. For more details on Gmail SMTP go through this document.

Create Spring Rest Controller to implement send mail logic :

SimpleMailController :


package com.onlinetutorilspoint;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SimpleMailController {
    @Autowired
    private JavaMailSender sender;

    @RequestMapping("/sendMail")
    public String sendMail() {
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);

        try {
            helper.setTo("demo@gmail.com");
            helper.setText("Greetings :)");
            helper.setSubject("Mail From Spring Boot");
        } catch (MessagingException e) {
            e.printStackTrace();
            return "Error while sending mail ..";
        }
        sender.send(message);
        return "Mail Sent Success!";
    }
}

Application.java


package com.onlinetutorilspoint;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Run the Application :

D:\> mvnw spring-boot:run

Or (Ubuntu)

$ mvn spring-boot:run

Now you can access the below endpoint URL for send Mail :

http://localhost:8080/sendMail

If everything done well yo can see the Mail Sent Success! message on your browser. And check your mail inbox.

Spring Boot Mail Example 2

Spring Boot Mail With Attachment :

We can also send the email with attachments like below. Add the below method to Controller and run the aapplication.


    @RequestMapping("/sendMailAtt")
    public String sendMailAttachment() throws MessagingException {
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,true);
        try {
            helper.setTo("demo@gmail.com");
            helper.setText("Greetings :)\n Please find the attached docuemnt for your reference.");
            helper.setSubject("Mail From Spring Boot");
            ClassPathResource file = new ClassPathResource("document.PNG");
            helper.addAttachment("document.PNG", file);
        } catch (MessagingException e) {
            e.printStackTrace();
            return "Error while sending mail ..";
        }
        sender.send(message);
        return "Mail Sent Success!";
    }

Use the MimeMessageHelper(MimeMessage mimeMessage, boolean multipart) to enable multipart mode.

Note : To make this example as simple as possible, I am passing the attachment by reading from classpath itself. Actually, these attachments can be uploaded from client (Browser) by using file upload functionality. I have discussed how to upload files from spring boot in previous tutorials. You can integrate these two examples and make a real-time scenario.

Access the below endpoint URL to send mail with attachments :

http://localhost:8080/sendMailAt

Spring Boot Mail Example 3

Happy Learning 🙂

The post How to Send Mail Spring Boot Example appeared first on onlinetutorialspoint.

]]>
http://www.onlinetutorialspoint.com/spring-boot/how-to-send-spring-boot-mail-example.html/feed 0
C Program – Bubble Sort Program in C http://www.onlinetutorialspoint.com/c-program/c-program-bubble-sort-program-in-c.html http://www.onlinetutorialspoint.com/c-program/c-program-bubble-sort-program-in-c.html#respond Sat, 30 Dec 2017 09:54:45 +0000 http://www.onlinetutorialspoint.com/?p=5212 In this tutorials, I am going to show how to implement Bubble Sort Program in C Language. Bubble Sort Program in C: As we all know that Bubble Sort is a most commonly used and easiest sorting algorithm among all sorting techniques. Bubble sort compares each element with its adjacent element and exchange (swap) them …

The post C Program – Bubble Sort Program in C appeared first on onlinetutorialspoint.

]]>
In this tutorials, I am going to show how to implement Bubble Sort Program in C Language.

Bubble Sort Program in C:

As we all know that Bubble Sort is a most commonly used and easiest sorting algorithm among all sorting techniques. Bubble sort compares each element with its adjacent element and exchange (swap) them if they are not in order.

Input : 8 4 1 6 5

Output :

PASS 1 – :

Elements are in phase – 1 : 8 4 1 6 5
Comparing 8 and 4 : Since 8 > 4, Exchange (Swap) them
Elements are in phase – 1 : 4 8 1 6 5
Comparing 8 and 1 : Since 8 > 1, Exchange (Swap) them
Elements are in phase – 1 : 4 1 8 6 5
Comparing 8 and 6 : Since 8 > 6, Exchange (Swap) them
Elements are in phase – 1 : 4 1 6 8 5
Comparing 8 and 5 : Since 8 > 5, Exchange (Swap) them
After Pass 1 elements are :
4 1 6 5 ___8

PASS 2 – :

Elements are in phase – 2 : 4 1 6 5 ___8
Comparing 4 and 1 : Since 4 > 1, Exchange (Swap) them
Elements are in phase – 2 : 1 4 6 5 ___8
Comparing 4 and 6 : Since 4 < 6, No Need to exchange
Elements are in phase – 2 : 1 4 6 5 ___8
Comparing 6 and 5 : Since 6 > 5, Exchange (Swap) them
After Pass 2 elements are :
1 4 5 ___6 8

PASS 3 – :

Elements are in phase – 3 : 1 4 5 ___6 8
Comparing 1 and 4 : Since 1 < 4, No Need to exchange
Elements are in phase – 3 : 1 4 5 ___6 8
Comparing 4 and 5 : Since 4 < 5, No Need to exchange
No exchanges in this pass, so the list is sorted

Sorted list is :
1 4 5 6 8

Bubble Sort Program :

 
#include <stdio.h> 
#define MAX_SIZE 100 
 
int main() 
{ 
    int array[MAX_SIZE],i,j,k,temp,n,xchanges; 
     
    printf("Enter the number of elements : "); 
    scanf("%d",&n); 
     
    for(i=0; i<n; i++) 
    { 
        printf("Enter element %d : ",i+1); 
        scanf("%d",&array[i]); 
    } 
 
    printf("Unsorted Elemets :\n"); 
    for(i=0; i<n; i++) 
        printf("%d ", array[i]); 
     printf("\n"); 
 
    /*Bubble sort logic begins here !*/ 
    for(i=0; i<n-1; i++) 
    { 
        printf("PASS %d - : \n\n",i+1); 
        xchanges=0; 
        for(j=0; j<n-1-i; j++) 
        { 
            printf("Elements are in phase - %d : ",i+1); 
            for(k=0; k<n; k++) 
            { 
                printf("%d ",array[k]); 
                if(k==n-i-1 && k!=n-1) 
                    printf("___"); 
            } 
            printf("\n"); 
            printf("Comparing %d and %d  :  ", array[j], array[j+1]); 
                         
            if( array[j] > array[j+1] ) 
            { 
                printf("Since %d > %d, Exchange (Swap) them\n",array[j],array[j+1]); 
                temp = array[j]; 
                array[j] = array[j+1]; 
                array[j+1] = temp; 
                xchanges++; 
            } 
            else  
                printf("Since %d < %d, No Need to exchange\n",array[j], array[j+1]); 
        } 
 
        if(xchanges==0) /*If list is sorted*/ 
        { 
            printf("No exchanges in this pass, so the list is sorted\n\n"); 
            break; 
        } 
         
        printf("After Pass %d elements are :  \n",i+1); 
        for(k=0; k<n; k++) 
        { 
            printf("%d ", array[k]); 
                if(k==n-i-2) 
                    printf("___"); 
        } 
        printf("\n"); 
    } 
 
    printf("Sorted list is :\n"); 
    for (i = 0; i < n; i++) 
        printf("%d ", array[i]); 
    printf("\n\n"); 
     
}

Output :

Enter the number of elements : 6
Enter element 1 : 9
Enter element 2 : 7
Enter element 3 : 5
Enter element 4 : 4
Enter element 5 : 3
Enter element 6 : 2
Unsorted Elements : 9 7 5 4 3 2

PASS 1 – :

Elements are in phase – 1 : 9 7 5 4 3 2
Comparing 9 and 7  :  Since 9 > 7, Exchange (Swap) them
Elements are in phase – 1 : 7 9 5 4 3 2
Comparing 9 and 5  :  Since 9 > 5, Exchange (Swap) them
Elements are in phase – 1 : 7 5 9 4 3 2
Comparing 9 and 4  :  Since 9 > 4, Exchange (Swap) them
Elements are in phase – 1 : 7 5 4 9 3 2
Comparing 9 and 3  :  Since 9 > 3, Exchange (Swap) them
Elements are in phase – 1 : 7 5 4 3 9 2
Comparing 9 and 2  :  Since 9 > 2, Exchange (Swap) them
After Pass 1 elements are :
7 5 4 3 2 ___9

PASS 2 – :

Elements are in phase – 2 : 7 5 4 3 2 ___9
Comparing 7 and 5  :  Since 7 > 5, Exchange (Swap) them
Elements are in phase – 2 : 5 7 4 3 2 ___9
Comparing 7 and 4  :  Since 7 > 4, Exchange (Swap) them
Elements are in phase – 2 : 5 4 7 3 2 ___9
Comparing 7 and 3  :  Since 7 > 3, Exchange (Swap) them
Elements are in phase – 2 : 5 4 3 7 2 ___9
Comparing 7 and 2  :  Since 7 > 2, Exchange (Swap) them
After Pass 2 elements are :
5 4 3 2 ___7 9

PASS 3 – :

Elements are in phase – 3 : 5 4 3 2 ___7 9
Comparing 5 and 4  :  Since 5 > 4, Exchange (Swap) them
Elements are in phase – 3 : 4 5 3 2 ___7 9
Comparing 5 and 3  :  Since 5 > 3, Exchange (Swap) them
Elements are in phase – 3 : 4 3 5 2 ___7 9
Comparing 5 and 2  :  Since 5 > 2, Exchange (Swap) them
After Pass 3 elements are :
4 3 2 ___5 7 9

PASS 4 – :

Elements are in phase – 4 : 4 3 2 ___5 7 9
Comparing 4 and 3  :  Since 4 > 3, Exchange (Swap) them
Elements are in phase – 4 : 3 4 2 ___5 7 9
Comparing 4 and 2  :  Since 4 > 2, Exchange (Swap) them
After Pass 4 elements are :
3 2 ___4 5 7 9
PASS 5 – :

Elements are in phase – 5 : 3 2 ___4 5 7 9
Comparing 3 and 2  :  Since 3 > 2, Exchange (Swap) them
After Pass 5 elements are :
2 ___3 4 5 7 9
Sorted list is :
2 3 4 5 7 9

Happy Learning 🙂

The post C Program – Bubble Sort Program in C appeared first on onlinetutorialspoint.

]]>
http://www.onlinetutorialspoint.com/c-program/c-program-bubble-sort-program-in-c.html/feed 0
Spring Boot Validation Login Form Example http://www.onlinetutorialspoint.com/spring-boot/spring-boot-validation-login-form-example.html http://www.onlinetutorialspoint.com/spring-boot/spring-boot-validation-login-form-example.html#respond Wed, 27 Dec 2017 05:00:14 +0000 http://www.onlinetutorialspoint.com/?p=5201 In this tutorials, I am going to show you how to work with Spring Boot Validation framework. Technologies : SpringBoot_1.5.9.RELEASE Java 8 spring-boot-thymeleaf Apache Tomcat Embed Hibernate Validator Spring Boot Validation : I am going to create a simple Spring Boot Login form using thymeleaf template and validate username and passwords. Project Structure : Project …

The post Spring Boot Validation Login Form Example appeared first on onlinetutorialspoint.

]]>
In this tutorials, I am going to show you how to work with Spring Boot Validation framework.

Technologies :

  • SpringBoot_1.5.9.RELEASE
  • Java 8
  • spring-boot-thymeleaf
  • Apache Tomcat Embed
  • Hibernate Validator

Spring Boot Validation :

I am going to create a simple Spring Boot Login form using thymeleaf template and validate username and passwords.

Project Structure :

Spring Boot Validation

Project Dependencies :

pom.xml


<?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>com.onlinetutorialspoint.springbootvalidation</groupId>
    <artifactId>springbootvalidation</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-el</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>
</project>

Login Controller :


package com.onlinetutorialspoint.login;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Controller
public class LoginController extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
    }

    @GetMapping("/")
    public String showForm(LoginForm loginForm) {
        return "login";
    }

    @PostMapping("/")
    public String validateLoginInfo(Model model, @Valid LoginForm loginForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return "login";
        }
        model.addAttribute("user", loginForm.getuserName());
        return "home";
    }
}

LoginForm.java


package com.onlinetutorialspoint.login;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class LoginForm {
    @NotNull
    @Size(min = 2, max = 30)
    private String userName;

    @NotNull
    @Min(5)
    private String password;

    public String getuserName() {
        return this.userName;
    }

    public void setuserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String toString() {
        return "LoginForm(UserName: " + this.userName + ", Password: " + this.password + ")";
    }
}

Login.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Spring Boot Validation Login Form Example</title>
<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
    <div class="login-form">
        <form action="#" th:action="@{/}" th:object="${loginForm}"
            method="post">
            <h2 class="text-center">Sign in</h2>
            <div class="form-group">
                <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-user"></i></span> <input
                        type="text" class="form-control" th:field="*{userName}"
                        placeholder="Username" />

                </div>
                <span class="red" th:if="${#fields.hasErrors('userName')}"
                    th:errors="*{userName}"></span>
            </div>
            <div class="form-group">
                <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-lock"></i></span> <input
                        type="password" class="form-control" th:field="*{password}"
                        placeholder="Password" />

                </div>
                <span class="red" th:if="${#fields.hasErrors('password')}"
                    th:errors="*{password}"></span>
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary login-btn btn-block">Sign
                    in</button>
            </div>
        </form>
    </div>
</body>
</html>

home.html


<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1"/>
<title>Spring Boot Validation Home</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
</head>
<body>
<div class="alert alert-success">
  <strong>Success!</strong> Hello <span th:text="${user}" /> !
</div>
</body>

</html>

Application.java

package com.onlinetutorialspoint.login;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Run Application :

mvn spring-boot:run

Access : http://localhost:8080/

Spring Boot Validation Login 1

Success :

Spring Boot Validation Login

Error Validation :

Spring Boot Validation Login Error

Happy Learning 🙂

The post Spring Boot Validation Login Form Example appeared first on onlinetutorialspoint.

]]>
http://www.onlinetutorialspoint.com/spring-boot/spring-boot-validation-login-form-example.html/feed 0