Sunday, December 14, 2025

Java spring notes9

 Handson

1. Create spring boot appl to display string message 

2. Create Spring Boot MVC appl, to display employee details like name, age, salary in employee.jsp

 

Developing Spring boot appl - 3 ways

1. Using Spring Initialzr - https://start.spring.io/

2. Using STS(Spring Tool Sutie) - IDE for springboot appl

3. Using Spring CLI(Command Line Interface)

 

 

SpringBoot annotations - 3 types

1. Spring Core annotation

      1. @Bean

      2. @Configuration

      3. @Autowired

      4. @Qualifier

      5. @Primary

      6. @Scope

      7. @Component

      8. @Controller, @Service, @Repository

 

2. Spring MVC annotation

client request - Controller prg(used to handle request and response using @Controller/@RestController) - service prg(write business logic using @Service) - Repository(@Repository) - Database

 

1. @Controller - return response in view page (ie) JSP or Thymeleaf

 

2. @RestController = @Controller + @ResponseBody - return response in the form of String or JSON format

 

3. @RequestMapping - used to map the request to particular method logic (class level or method level)

@RequestMapping(value="/fetchEmployee",method=RequestMethod.GET) - used to give GET request

@RequestMapping(value="/insertEmployee",method=RequestMethod.POST) - used to give POST request

@RequestMapping(value="/updateEmployee/{empid}",method=RequestMethod.PUT) - used to give PUT request

@RequestMapping(value="/deleteEmployee/{empid}",method=RequestMethod.DELETE) - used to give DELETE request

 

4. @GetMapping,@PostMapping,@PutMapping, @DeleteMapping - only method level

 

5. @RequestBody - used to read entire input data in JSON format (ie) employee info

 

{

   "empid":"100",

   "name":"Ram",

   "age":25,

   "salary":20000.0

}

 

6. @PathVariable - used to get value from the request url

 

@RequestMapping(value="/updateEmployee/{empid}",method=RequestMethod.PUT) - used to give PUT request

 

http://localhost:9090/project/updateEmployee/1000

 

7. @RequestParam - used to get value from the parameter that is passed between ? and & which is called as query string

 

http://localhost:9090/project/updateEmployee?empid=1000&age=20

 

8. @ResponseBody - return response in JSON format

 

9. @ResponseEntity - return JSON response along with HTTP status code, header etc

 

3. SpringBoot annotation

@SpringBootApplication = @EnableAutoConfiguration + @Configuration + @ComponentScan

 

 

1. Create spring boot project using Spring Initialzr - https://start.spring.io/

 

Project: Maven

Language: Java

SpringBoot version: 3.4.5

 

Group id: com.pack

Artifact id: SpringBoot1

Packaging: jar

Java: 21

 

Click "Add Dependencies"

 

Spring Web - Build web, including RESTful, applications using Spring MVC. Uses Apache Tomcat as the default embedded container.

 

Click Generate

 

2. Extract project into eclipse workspace

 

3. Import extracted project into eclipse

 

4. Open cmd prompt

>mvn clean install

 

5. Update the project

 

6. Create controller prg

 

@RestController

@RequestMapping("/api")

public class ExampleController {

 

              @RequestMapping(value="/msg",method=RequestMethod.GET)

              public String getMessage() {

                             return "Welcome to SpringBoot";

              }

             

              @GetMapping(value="/msg1")

              public String getMessage1() {

                             return "Welcome to Springboot framework";

              }

}

 

7. Start the appl

 

http://localhost:8080/api/msg

http://localhost:8080/api/msg1

 

8. By default Springboot will read all configuration from application.properties or application.yml present in src/main/resources folder

 

server.port=9090

 

- Start the appl

 

http://localhost:9090/api/msg

http://localhost:9090/api/msg1

 

9. We have to set context path in application.properties

 

[http://localhost:portno/contextpath/urlpattern]http://localhost:portno/contextpath/urlpattern

 

server.port=9090

server.servlet.context-path=/appl

 

- Start the appl

 

http://localhost:9090/appl/api/msg

http://localhost:9090/appl/api/msg1

 

10. If we provide some wrong url request other than /api/msg and /api/msg1, then we will get whitelabel errorpage, instead we want to print some error message then we have to implement ErrorController interface and override getErrorPath()

 

@RestController

//@RequestMapping("/api")

public class ExampleController implements ErrorController {

 

              private static final String PATH="/error";

             

              @RequestMapping(value="/msg",method=RequestMethod.GET)

              public String getMessage() {

                             return "Welcome to SpringBoot";

              }

             

              @GetMapping(value="/msg1")

              public String getMessage1() {

                             return "Welcome to Springboot framework";

              }

             

              @GetMapping(value=PATH)

              public String getErrorInfo() {

                             return "Requested resource does not found";

              }

             

              public String getErrorPath() {

                             return PATH;

              }

}

 

11. When we create any program in springboot appl, it should be always present as subpackage of main package, if we create outside the main package then we have to use @ComponentScan which is used to scan all ur base package and execute the program

 

@RestController

public class IndexController {

 

            @RequestMapping(value="/msg3",method=RequestMethod.GET)

              public String getMessage() {

                             return "SpringBoot framework";

              }

}

 

@SpringBootApplication

@ComponentScan(basePackages = {"com.hcl","com.pack.SpringBoot1"})

public class SpringBoot1Application {

 

              public static void main(String[] args) {

                             SpringApplication.run(SpringBoot1Application.class, args);

              }

 

}

 

12. Spring Boot DevTools - Provides fast application restarts, LiveReload, and configurations for enhanced development experience.

     - No need to restart the server each and every time, when we make changes in the appl, the server will be automatically restarted

 

<dependency>

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-devtools</artifactId>

      <scope>runtime</scope>

      <optional>true</optional>

    </dependency>

 

 

13. CommandLineRunner interface

        - used to execute any code after the Springboot appl is started

        - public void run(String...s) {

          }

 

@Component

@Order(value=3)

public class CommandLineRunner1 implements CommandLineRunner{

 

              protected final static Log log=LogFactory.getLog(CommandLineRunner1.class);

             

              @Override

              public void run(String... args) throws Exception {

                             log.info("Inside CommandLineRunner1");

              }

 

}

 

@Component

@Order(value=1)

public class CommandLineRunner2 implements CommandLineRunner{

 

              protected final static Log log=LogFactory.getLog(CommandLineRunner2.class);

             

              @Override

              public void run(String... args) throws Exception {

                             log.info("Inside CommandLineRunner2");

              }

 

}

 

@SpringBootApplication

@ComponentScan(basePackages = {"com.hcl","com.pack.SpringBoot1"})

@Order(value=2)

public class SpringBoot1Application implements CommandLineRunner{

 

              protected final static Log log=LogFactory.getLog(SpringBoot1Application.class);

             

              public static void main(String[] args) {

                             SpringApplication.run(SpringBoot1Application.class, args);

                             log.info("Inside main method");

              }

 

              @Override

              public void run(String... args) throws Exception {

                             log.info("Inside run method");

              }

 

}

 

ApplicationRunner interface

      - used to execute any code after the Springboot appl is started

      - public void run(ApplicationArgument a) {

          }

 

14. Spring MVC - where we return response in the view page (ie) JSP or Thymeleaf

 

a. Create Springboot project with spring web, dev tool dependency with war packaging

 

Since springboot dosent know about JSP page, we have to configure JSP dependency

 

<dependency>

                                           <groupId>org.apache.tomcat.embed</groupId>

                                           <artifactId>tomcat-embed-jasper</artifactId>

                                           <scope>provided</scope>

                             </dependency>

 

b. Create controller prg

 

@Controller

public class MainController {

 

              @GetMapping("/view")

              public String getInfo() {

                             return "index";  //name of jsp page

              }

}

 

c. Create index.jsp as per the return value, inside webapp - WEB-INF - views(anyname)- create jsp file

 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

<h2>SpringBoot using MVC</h2>

</body>

</html>

 

d. Configure jsp info in application.properties

 

spring.application.name=SpringBootWeb1

server.port=3434

server.servlet.context-path=/mvc

spring.mvc.view.prefix=/WEB-INF/views/

spring.mvc.view.suffix=.jsp

#prefix+viewname+suffix=/WEB-INF/views/index.jsp

 

e. Start the appl

 

http://localhost:3434/mvc/view

 

f. Now we pass value from controller prg to JSP page, we can use either ModelMap class or Model class or Map interface

 

@Controller

public class MainController {

 

              @GetMapping("/view")

              public String getInfo() {

                             return "index";  //name of jsp page

              }

             

              @GetMapping("/view1")

              public String getInfo1(ModelMap m1, Model m2, Map m3) {

                             m1.addAttribute("name", "Ram");

                             m2.addAttribute("place", "Chennai");

                             m3.put("company", "HCL");

                             return "employee";  //name of jsp page

              }

}

 

h. Using JSP Expression Language we can display the attributes in jsp

 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

<h2>Employee Information</h2>

<h3>Employee name is ${name} lives in ${place} and works in ${company}</h3>

</body>

</html>

 

g. Start the appl

 

http://localhost:3434/mvc/view1

 

15. Springboot Jetty

1. Exclude tomcat server from web dependency

 

<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>

 

2. Comment tomcat server and jsp related to tomcat

 

3. Add Jetty and jsp related jetty dependency

 

<dependency>

                                           <groupId>org.springframework.boot</groupId>

                                           <artifactId>spring-boot-starter-jetty</artifactId>

                             </dependency>

                             <dependency>

                                           <groupId>org.eclipse.jetty</groupId>

                                           <artifactId>apache-jsp</artifactId>

                                           <version>11.0.21</version>

                             </dependency>

 

4. Start the appl

No comments:

Post a Comment