diff --git a/docs/java/Spring-and-Spring-Boot/_category_.json b/docs/java/Spring-and-Spring-Boot/_category_.json new file mode 100644 index 000000000..aec111a48 --- /dev/null +++ b/docs/java/Spring-and-Spring-Boot/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Spring and Spring-boot", + "position": 10, + "link": { + "type": "generated-index", + "description": "In this section, you will learn about very famous frameworks of core jaava spring and springboot" + } + } \ No newline at end of file diff --git a/docs/java/Spring-and-Spring-Boot/aspect-oriented-programming.md b/docs/java/Spring-and-Spring-Boot/aspect-oriented-programming.md new file mode 100644 index 000000000..2c2b191e8 --- /dev/null +++ b/docs/java/Spring-and-Spring-Boot/aspect-oriented-programming.md @@ -0,0 +1,253 @@ +--- +id: aspect oriented programming +title: Aspect oriented programming(AOP) +sidebar_label: Spring AOP Tutorial +sidebar_position: 4 +tags: [java, spring,core-java, programming, java core, java spring, java web, AOP, aspect oriented] +description: in thi tutorial you will learn about aspect oriented programming and how aspect6s are working and when to use it and how to use it. +--- +### Spring AOP Tutorial + +**Aspect-Oriented Programming (AOP)** complements Object-Oriented Programming (OOP) by providing modularity, with aspects as the key unit of modularity rather than classes. + +AOP breaks the program logic into distinct parts called concerns, increasing modularity by addressing cross-cutting concerns. + +### Why Use AOP? + +AOP offers a pluggable way to dynamically add additional concerns before, after, or around the actual logic. For instance, consider a class `A` with multiple methods: + +```java +class A { + public void m1() { ... } + public void m2() { ... } + public void m3() { ... } + public void m4() { ... } + public void m5() { ... } + public void n1() { ... } + public void n2() { ... } + public void p1() { ... } + public void p2() { ... } + public void p3() { ... } +} +``` + +To maintain logs and send notifications after calling methods starting with `m`, you would traditionally have to write this logic in each method. However, if the client decides to change the notification requirement, you would need to update all methods, leading to maintenance problems. + +With AOP, you define additional concerns like logging and notification separately and manage them via configuration. This makes maintenance easier, as changes can be made in a single place. + +### Where to Use AOP? + +AOP is mainly used for: + +1. Declarative enterprise services such as transaction management. +2. Implementing custom aspects. + +### AOP Concepts and Terminology + +**Join Point**: A point in the program such as method execution, exception handling, etc. Spring supports only method execution join points. + +**Advice**: An action taken by an aspect at a join point. Types of advice include: +- **Before Advice**: Executes before a join point. +- **After Returning Advice**: Executes after a join point completes normally. +- **After Throwing Advice**: Executes if a method exits by throwing an exception. +- **After (finally) Advice**: Executes after a join point regardless of its exit. +- **Around Advice**: Executes before and after a join point. + +**Pointcut**: An expression language of AOP that matches join points. + +**Introduction**: Introduction of additional methods and fields for a type, allowing new interfaces for advised objects. + +**Target Object**: The object being advised by one or more aspects, also known as the proxied object. + +**Aspect**: A class containing advices, join points, etc. + +**Interceptor**: An aspect containing only one advice. + +**AOP Proxy**: Implements aspect contracts, created by the AOP framework. In Spring, it can be a JDK dynamic proxy or a CGLIB proxy. + +**Weaving**: The process of linking aspects with other application types to create an advised object, done at compile time, load time, or runtime. Spring AOP performs weaving at runtime. + +### AOP Implementations + +1. **AspectJ** +2. **Spring AOP** +3. **JBoss AOP** + +### Spring AOP Usage + +Spring AOP can be used in three ways, with the most common being the Spring AspectJ Annotation Style: + +1. By Spring 1.2 Old style (DTD based) +2. By AspectJ annotation style +3. By Spring XML configuration style + +### Spring AOP AspectJ Annotation Example + +**Annotations:** +- `@Aspect`: Declares the class as an aspect. +- `@Pointcut`: Declares the pointcut expression. +- **Advice Annotations:** + - `@Before`: Applied before the actual method. + - `@After`: Applied after the actual method and before returning the result. + - `@AfterReturning`: Applied after the method completes, allows access to the return value. + - `@Around`: Applied before and after the actual method. + - `@AfterThrowing`: Applied if the method throws an exception. + +**Example:** + +```java title="Operation.java" +package com.javatpoint; + +public class Operation { + public void msg() { System.out.println("msg method invoked"); } + public int m() { System.out.println("m method invoked"); return 2; } + public int k() { System.out.println("k method invoked"); return 3; } +} +``` + +(Aspect with Before Advice) +```java title="TrackOperation.java" +package com.javatpoint; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; + +@Aspect +public class TrackOperation { + @Pointcut("execution(* Operation.*(..))") + public void k() {} // Pointcut name + + @Before("k()") // Applying pointcut on before advice + public void myadvice(JoinPoint jp) { // This is advice + System.out.println("additional concern"); + // System.out.println("Method Signature: " + jp.getSignature()); + } +} +``` + +(Spring Configuration) +```xml title="applicationContext.xml" + + + + + + + + +``` + +(Main Class) +```java title="Test.java" +package com.javatpoint; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class Test { + public static void main(String[] args) { + ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); + Operation e = (Operation) context.getBean("opBean"); + System.out.println("calling msg..."); + e.msg(); + System.out.println("calling m..."); + e.m(); + System.out.println("calling k..."); + e.k(); + } +} +``` + +**Output:** +``` +calling msg... +additional concern +msg() method invoked +calling m... +additional concern +m() method invoked +calling k... +additional concern +k() method invoked +``` + +The additional concern is printed before each method invocation. + +### Other Examples + +#### @After Example + +```java title="TrackOperation.java" +@After("k()") // Applying pointcut on after advice +public void myadvice(JoinPoint jp) { + System.out.println("additional concern"); + // System.out.println("Method Signature: " + jp.getSignature()); +} +``` + +#### @AfterReturning Example +```java title="TrackOperation.java" +@AfterReturning(pointcut = "execution(* Operation.*(..))", returning = "result") +public void myadvice(JoinPoint jp, Object result) { + System.out.println("additional concern"); + System.out.println("Method Signature: " + jp.getSignature()); + System.out.println("Result in advice: " + result); + System.out.println("end of after returning advice..."); +} +``` + +#### aop:before Example (XML Configuration) +```java title="TrackOperation.java" +package com.javatpoint; +import org.aspectj.lang.JoinPoint; +public class TrackOperation { + public void myadvice(JoinPoint jp) { // It is advice + System.out.println("additional concern"); + // System.out.println("Method Signature: " + jp.getSignature()); + } +} +``` + + +```xml title="applicationContext.xml" + + + + + + + +``` + +#### aop:after Example (XML Configuration) +```xml + + + + + + + +``` + +#### aop:after-returning Example (XML Configuration) +```xml + + + + + + + +``` + +### Summary +Spring AOP helps in separating cross-cutting concerns like logging, transaction management, etc., from the business logic. This modular approach makes maintenance and evolution of the codebase easier and more manageable. \ No newline at end of file diff --git a/docs/java/Spring-and-Spring-Boot/dependency-injection.md b/docs/java/Spring-and-Spring-Boot/dependency-injection.md new file mode 100644 index 000000000..b6db59ea7 --- /dev/null +++ b/docs/java/Spring-and-Spring-Boot/dependency-injection.md @@ -0,0 +1,243 @@ +--- +id: dependency injection +title: dependency injection +sidebar_label: dependency injection in spring +sidebar_position: 3 +tags: [java, spring,core-java, programming, java core, java spring, java web] +description: in thi tutorial you will learn about how to injetch dependencies in classe and objects which is core concept of java +--- +### IoC Container + +The IoC container in the Spring Framework is responsible for managing the lifecycle and configuration of application objects. It instantiates, configures, and assembles the dependencies between objects based on the configuration provided (usually in an XML file or through annotations). The IoC container performs three main tasks: +1. Instantiates the application classes. +2. Configures the objects. +3. Assembles the dependencies between the objects. + +There are two types of IoC containers in Spring: + +1. **BeanFactory** +2. **ApplicationContext** + +#### Difference between BeanFactory and ApplicationContext + +Both `org.springframework.beans.factory.BeanFactory` and `org.springframework.context.ApplicationContext` act as IoC containers. However, the `ApplicationContext` interface extends the `BeanFactory` interface and adds additional functionality such as integration with Spring's AOP, message resource handling (for internationalization), event propagation, and application-layer specific contexts like `WebApplicationContext` for web applications. Therefore, using `ApplicationContext` is generally preferred over `BeanFactory`. + +### Using BeanFactory + +The `XmlBeanFactory` is an implementation of the `BeanFactory` interface. To use `BeanFactory`, create an instance of `XmlBeanFactory` as shown below: + +```java +Resource resource = new ClassPathResource("applicationContext.xml"); +BeanFactory factory = new XmlBeanFactory(resource); +``` + +The constructor of `XmlBeanFactory` takes a `Resource` object, so you need to pass a `Resource` object to create an instance of `BeanFactory`. + +### Using ApplicationContext + +The `ClassPathXmlApplicationContext` class is an implementation of the `ApplicationContext` interface. To use `ApplicationContext`, instantiate `ClassPathXmlApplicationContext` as shown below: + +```java +ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); +``` + +The constructor of `ClassPathXmlApplicationContext` takes a string representing the name of the XML file to create an instance of `ApplicationContext`. + +### Dependency Injection in Spring + +Dependency Injection (DI) is a design pattern that reduces tight coupling between objects by injecting their dependencies from external sources, making the code easier to manage and test. Spring supports DI through two main methods: +1. **Constructor Injection** +2. **Setter Injection** + +#### Constructor Injection + +Constructor injection is done using the `` sub-element within the `` element in the XML configuration file. Here's an example: + + + +```java title="Employee.java" +package com.codeharborehub; + +public class Employee { + private int id; + private String name; + + public Employee() { System.out.println("default constructor"); } + + public Employee(int id) { this.id = id; } + + public Employee(String name) { this.name = name; } + + public Employee(int id, String name) { + this.id = id; + this.name = name; + } + + void show() { + System.out.println(id + " " + name); + } +} +``` +```xml title="applicationContext.xml" + + + + + + + +``` + + +```java title="Test.java" +package com.codeharborehub; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.xml.XmlBeanFactory; +import org.springframework.core.io.*; + +public class Test { + public static void main(String[] args) { + Resource r = new ClassPathResource("applicationContext.xml"); + BeanFactory factory = new XmlBeanFactory(r); + + Employee e = (Employee) factory.getBean("e"); + e.show(); + } +} +``` + +#### Setter Injection + +Setter injection is done using the `` element within the `` element in the XML configuration file. Here's an example: + +```java title="Employee.java" +package com.codeharborehub; + +public class Employee { + private int id; + private String name; + private String city; + + public int getId() { return id; } + public void setId(int id) { this.id = id; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getCity() { return city; } + public void setCity(String city) { this.city = city; } + + void display() { + System.out.println(id + " " + name + " " + city); + } +} +``` +```xml title="applicationContext.xml" + + + + + + 20 + + + Arun + + + ghaziabad + + + +``` + +```java title="Test.java" +package com.codeharborehub; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.xml.XmlBeanFactory; +import org.springframework.core.io.*; + +public class Test { + public static void main(String[] args) { + Resource r = new ClassPathResource("applicationContext.xml"); + BeanFactory factory = new XmlBeanFactory(r); + + Employee e = (Employee) factory.getBean("obj"); + e.display(); + } +} +``` + +### Difference between Constructor and Setter Injection + +1. **Partial Dependency**: Partial dependencies can be injected using setter injection but not with constructor injection. +2. **Overriding**: Setter injection overrides constructor injection. +3. **Changes**: Setter injection allows for more flexibility in changing the values without creating a new instance, unlike constructor injection. + +### Dependency Injection with Factory Method in Spring + +Spring allows for the injection of beans using factory methods. This can be done by specifying `factory-method` and optionally `factory-bean` attributes in the `` element. + +**Example:** + +```java title="A.java" +package com.codeharborehub; + +public class A { + private static final A obj = new A(); + private A() { System.out.println("private constructor"); } + + public static A getA() { + System.out.println("factory method"); + return obj; + } + + public void msg() { + System.out.println("hello user"); + } +} +``` + +```xml title="applicationContext.xml" + + + + + +``` + +```java title="Test.java" +package com.codeharborehub; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class Test { + public static void main(String[] args) { + ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); + A a = (A) context.getBean("a"); + a.msg(); + } +} +``` + +**Output:** + +``` +private constructor +factory method +hello user +``` \ No newline at end of file diff --git a/docs/java/Spring-and-Spring-Boot/introduction-to-spring.md b/docs/java/Spring-and-Spring-Boot/introduction-to-spring.md new file mode 100644 index 000000000..f263d911c --- /dev/null +++ b/docs/java/Spring-and-Spring-Boot/introduction-to-spring.md @@ -0,0 +1,121 @@ +--- +id: introduction-to-spring +title: Introduction to Spring +sidebar_label: Introduction to Spring +sidebar_position: 1 +tags: [java, spring,core-java, programming, java core, java spring, java web] +description: in thi tutorial you will learn about what is spring framework and why it is required and how to use it +--- + + + +This spring tutorial provides in-depth concepts of the Spring Framework with simplified examples. It was developed by Rod Johnson in 2003. The Spring framework makes the easy development of JavaEE applications. + +It is helpful for beginners and experienced persons. + +![Spring Framework](https://static.javatpoint.com/images/spimages/spring1.png) + +## Why Learn Spring? + +Spring is the most popular application development framework for enterprise Java. Millions of developers around the world use the Spring Framework to create high-performing, easily testable, and reusable code. + +Spring framework is an open-source Java platform. It was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003. + +Spring is lightweight when it comes to size and transparency. The basic version of the Spring framework is around 2MB. + +The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. The Spring framework aims to make J2EE development easier to use and promotes good programming practices by enabling a POJO-based programming model. + +## Spring Framework + +Spring is a lightweight framework. It can be thought of as a framework of frameworks because it provides support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF, etc. The framework, in a broader sense, can be defined as a structure where we find solutions to various technical problems. + +The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM, WEB MVC, etc. We will learn these modules on the next page. Let's understand the IOC and Dependency Injection first. + +## Advantages of Spring Framework + +There are many advantages of the Spring Framework. They are as follows: + +1. **Predefined Templates**: Spring framework provides templates for JDBC, Hibernate, JPA, etc. technologies. So there is no need to write too much code. It hides the basic steps of these technologies. For example, with JdbcTemplate, you don't need to write code for exception handling, creating connections, creating statements, committing transactions, closing connections, etc. You only need to write the code for executing queries. Thus, it saves a lot of JDBC code. + +2. **Loose Coupling**: Spring applications are loosely coupled because of dependency injection. + +3. **Easy to Test**: Dependency Injection makes it easier to test applications. EJB or Struts applications require a server to run, but the Spring framework doesn't require a server. + +4. **Lightweight**: The Spring framework is lightweight because of its POJO implementation. The Spring Framework doesn't force the programmer to inherit any class or implement any interface, making it non-invasive. + +5. **Fast Development**: The Dependency Injection feature of the Spring Framework and its support for various frameworks make JavaEE application development easy. + +6. **Powerful Abstraction**: It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA, and JTA. + +7. **Declarative Support**: + +## Applications of Spring + +The benefits of using the Spring Framework include: + +- **POJO Based**: Spring enables developers to develop enterprise-class applications using POJOs. This means you do not need an EJB container product such as an application server; you can use a robust servlet container such as Tomcat. + +- **Modular**: Spring is organized in a modular fashion. Although there are many packages and classes, you only need to worry about the ones you need. + +- **Integration with Existing Frameworks**: Spring does not reinvent the wheel; it uses existing technologies like ORM frameworks, logging frameworks, JEE, Quartz, JDK timers, and other view technologies. + +- **Testability**: Testing a Spring application is simple because environment-dependent code is moved into this framework. Using JavaBean-style POJOs makes it easier to use dependency injection for injecting test data. + +- **Web MVC**: Spring's web framework is a well-designed web MVC framework, providing a great alternative to web frameworks like Struts. + +- **Central Exception Handling**: Spring provides a convenient API to translate technology-specific exceptions (e.g., JDBC, Hibernate, JDO) into consistent, unchecked exceptions. + +- **Lightweight**: Lightweight IoC containers are beneficial for developing and deploying applications on computers with limited memory and CPU resources. + +- **Transaction Management**: Spring provides a consistent transaction management interface that can scale from local to global transactions. + +## Spring Modules + +The Spring framework comprises many modules such as core, beans, context, expression language, AOP, Aspects, Instrumentation, JDBC, ORM, OXM, JMS, Transaction, Web, Servlet, Struts, etc. These modules are grouped into Test, Core Container, AOP, Aspects, Instrumentation, Data Access/Integration, and Web (MVC/Remoting). + +![Spring Modules](https://static.javatpoint.com/images/sp/spmodules.jpg) + +### Test + +This layer provides support for testing with JUnit and TestNG. + +### Spring Core Container + +The Spring Core container contains core, beans, context, and expression language (EL) modules. + +#### Core and Beans + +These modules provide IOC and Dependency Injection features. + +#### Context + +This module supports internationalization (I18N), EJB, JMS, and Basic Remoting. + +#### Expression Language + +It is an extension to the EL defined in JSP. It provides support for setting and getting property values, method invocation, accessing collections and indexers, named variables, logical and arithmetic operators, retrieval of objects by name, etc. + +### AOP, Aspects, and Instrumentation + +These modules support aspect-oriented programming implementation where you can use Advices, Pointcuts, etc., to decouple the code. + +The Aspects module provides support for integration with AspectJ. + +The Instrumentation module provides support for class instrumentation and classloader implementations. + +### Data Access/Integration + +This group comprises JDBC, ORM, OXM, JMS, and Transaction modules. These modules provide support for interacting with databases. + +### Web + +This group comprises Web, Web-Servlet, Web-Struts, and Web-Portlet modules. These modules provide support for creating web applications. +Sure! Here’s a conclusion section for the Spring tutorial: + +## Conclusion + +The Spring Framework is a powerful, versatile, and comprehensive platform for developing Java applications. Its modular architecture allows developers to focus on specific aspects of application development without being bogged down by unnecessary complexity. The benefits of using Spring, such as its lightweight nature, robust transaction management, and ease of integration with other technologies, make it an excellent choice for both beginners and experienced developers. + +By leveraging Spring's core features, like dependency injection and aspect-oriented programming, developers can create maintainable, testable, and high-performing applications. Whether you're building a simple web application or a complex enterprise system, Spring provides the tools and frameworks necessary to streamline development and promote best practices. + +As you continue to explore and learn more about Spring, you'll discover how its flexibility and extensive ecosystem can help you tackle a wide range of development challenges efficiently. diff --git a/docs/java/Spring-and-Spring-Boot/object-relational-model.md b/docs/java/Spring-and-Spring-Boot/object-relational-model.md new file mode 100644 index 000000000..e936c1887 --- /dev/null +++ b/docs/java/Spring-and-Spring-Boot/object-relational-model.md @@ -0,0 +1,286 @@ +--- +id: object-relational-model +title: Spring with ORM Frameworks +sidebar_label: Spring with ORM Frameworks +sidebar_position: 5 +tags: [java, spring,core-java, programming, java core, java spring, java web,ORM,hibernate] +description: in thi tutorial you will learn about object relational model which will tell that how spring work with tables inspite of being object oriented. +--- + + + +### Spring with ORM Frameworks + +Spring provides an API to seamlessly integrate with ORM frameworks such as Hibernate, JPA (Java Persistence API), JDO (Java Data Objects), Oracle Toplink, and iBATIS. Leveraging ORM frameworks with Spring offers several advantages: + +#### Advantages of Spring Framework with ORM Frameworks: + +1. **Reduced Coding**: Spring eliminates the need to write boilerplate code for tasks like managing database connections, transactions, etc. + +2. **Easy Testing**: Spring's Inversion of Control (IoC) approach facilitates easier testing of applications. + +3. **Enhanced Exception Handling**: Spring provides its own API for exception handling when used with ORM frameworks. + +4. **Integrated Transaction Management**: Spring allows wrapping mapping code with an explicit template wrapper class or using AOP-style method interceptors for transaction management. + +#### Hibernate and Spring Integration: + +Integrating Hibernate with Spring is straightforward. Instead of configuring database information in a `hibernate.cfg.xml` file, you can provide all the necessary information in the `applicationContext.xml` file. This simplifies configuration and reduces the amount of code required. + +#### Advantages of Spring Framework with Hibernate: + +Spring provides the `HibernateTemplate` class, which streamlines the interaction with Hibernate. This eliminates the need for many manual steps such as creating configurations, building session factories, managing sessions, transactions, etc. + +Consider the comparison between traditional Hibernate usage and Spring with Hibernate: + +**Traditional Hibernate:** +```java +Configuration cfg = new Configuration(); +cfg.configure("hibernate.cfg.xml"); +SessionFactory factory = cfg.buildSessionFactory(); +Session session = factory.openSession(); +Transaction t = session.beginTransaction(); +Employee e1 = new Employee(111, "arun", 40000); +session.persist(e1); +t.commit(); +session.close(); +``` + +**Using HibernateTemplate with Spring:** +```java +Employee e1 = new Employee(111, "arun", 40000); +hibernateTemplate.save(e1); +``` + +#### Methods of `HibernateTemplate` class: + +| No. | Method | Description | +|-----|-----------------------------------|---------------------------------------------------------| +| 1) | `void persist(Object entity)` | Persists the given object. | +| 2) | `Serializable save(Object entity)`| Persists the given object and returns its ID. | +| 3) | `void saveOrUpdate(Object entity)`| Persists or updates the given object based on ID. | +| 4) | `void update(Object entity)` | Updates the given object. | +| 5) | `void delete(Object entity)` | Deletes the given object based on ID. | +| 6) | `Object get(Class entityClass, Serializable id)` | Retrieves a persistent object based on ID. | +| 7) | `Object load(Class entityClass, Serializable id)`| Lazy-loads a persistent object based on ID. | +| 8) | `List loadAll(Class entityClass)` | Retrieves all persistent objects of a given type. | + +### Steps for Hibernate and Spring Integration: + +1. **Create Database Table**: (Optional) Create a table in the database. + +2. **Create `applicationContext.xml`**: Configure data source, session factory, and other Hibernate-related beans. + +3. **Create `Employee.java`**: Define the persistent class. + +4. **Create `employee.hbm.xml`**: Mapping file for `Employee` class. + +5. **Create `EmployeeDao.java`**: DAO class using `HibernateTemplate` to interact with the database. + +6. **Create `InsertTest.java`**: Test class to demonstrate saving an employee object. + +### Example of Hibernate and Spring Integration: + +#### Directory Structure: + +``` +java +|--- com + |--- codeharbourhub + |--- Employee.java + |--- EmployeeDao.java + |--- InsertTest.java +resources +|--- applicationContext.xml +|--- employee.hbm.xml +``` + +#### 1) Create Table in the Database: + +```sql +CREATE TABLE EMPLOYEE ( + ID NUMBER(10) NOT NULL, + NAME VARCHAR2(255), + SALARY FLOAT, + PRIMARY KEY (ID) +); +``` + +#### 2) Create Employee.java file: + +```java title="Employee.java" +package com.codeharbourhub; + +public class Employee { + private int id; + private String name; + private float salary; + + // Getters and Setters +} +``` + +#### 3) `employee.hbm.xml`: + +```xml title="employee.hbm.xml" + + + + + + + + + + + + + +``` + +#### 4) `EmployeeDao.java`: + +```java title="EmployeeDao.java" +package com.codeharbourhub; + +import org.springframework.orm.hibernate3.HibernateTemplate; +import java.util.List; + +public class EmployeeDao { + HibernateTemplate template; + + public void setTemplate(HibernateTemplate template) { + this.template = template; + } + + // Method to save employee + public void saveEmployee(Employee e) { + template.save(e); + } + + // Method to update employee + public void updateEmployee(Employee e) { + template.update(e); + } + + // Method to delete employee + public void deleteEmployee(Employee e) { + template.delete(e); + } + + // Method to return one employee of given id + public Employee getById(int id) { + Employee e = (Employee) template.get(Employee.class, id); + return e; + } + + // Method to return all employees + public List getEmployees() { + List list = template.loadAll(Employee.class); + return list; + } +} +``` + +#### 5) `applicationContext.xml`: + +```xml title="applicationContext.xml" + + + + + + + + + + + + + + + + employee.hbm.xml + + + + + + + org.hibernate.dialect.Oracle9Dialect + update + true + + + + + + + + + + + + + +``` + +#### 6) `InsertTest.java`: + +```java title="InsertTest.java" +package com.codeharbourhub; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.xml.XmlBeanFactory; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +public class InsertTest { + public static void main(String[] args) { + Resource r = new ClassPathResource("applicationContext.xml"); + BeanFactory factory = new XmlBeanFactory(r); + + EmployeeDao dao = (EmployeeDao) factory.getBean("d"); + + Employee e = new Employee(); + e.setId(114); + e.setName("varun"); + e.setSalary(50000); + + dao.saveEmployee(e); + } +} +``` + +Now, upon executing `InsertTest.java`, the record will be successfully inserted into the Oracle database. +In this tutorial, we explored the integration of Hibernate with the Spring framework, leveraging Spring's powerful features to simplify the development process. Here's a summary of the key points covered: + +1. **Integration Overview**: + - Spring offers seamless integration with ORM (Object-Relational Mapping) frameworks like Hibernate, JPA, JDO, Oracle Toplink, and iBATIS. + - The integration provides advantages such as reduced boilerplate code, easier testing through IoC (Inversion of Control), improved exception handling, and integrated transaction management. + +2. **Hibernate and Spring Integration**: + - Hibernate applications typically require a `hibernate.cfg.xml` file to configure database information. However, when integrating with Spring, this configuration can be provided in the `applicationContext.xml` file. + - Spring simplifies Hibernate usage by providing classes like `HibernateTemplate`, reducing the need for manual configuration and session management. + +3. **Benefits of Spring with Hibernate**: + - With Spring, developers can utilize the `HibernateTemplate` class, significantly reducing the amount of code required compared to using Hibernate alone. + - The `HibernateTemplate` class provides methods for common operations like persisting, updating, and deleting objects, as well as fetching objects by ID or loading all objects of a particular type. + +4. **Steps for Integration**: + - The integration process involves several steps, including creating database tables, defining Hibernate mapping files (`employee.hbm.xml`), implementing the persistent class (`Employee.java`), creating a DAO (Data Access Object) class (`EmployeeDao.java`), and configuring the Spring application context (`applicationContext.xml`). + - Finally, a test class (`InsertTest.java`) is used to demonstrate the integration by saving an instance of the `Employee` class using the `EmployeeDao`. + +5. **Configuration**: + - The `applicationContext.xml` file contains configuration details such as DataSource setup, session factory configuration, Hibernate properties, and bean definitions for the `HibernateTemplate` and DAO classes. + +6. **Execution**: + - Upon executing the `InsertTest` class, the Spring context is initialized, and the `EmployeeDao` bean is obtained from the context. An instance of `Employee` is created and saved using the DAO's `saveEmployee` method, demonstrating successful integration and data persistence. + +By following these steps, developers can seamlessly integrate Hibernate with Spring, leveraging the powerful features of both frameworks to build robust and maintainable Java applications. \ No newline at end of file diff --git a/docs/java/Spring-and-Spring-Boot/spring-environment-setup.md b/docs/java/Spring-and-Spring-Boot/spring-environment-setup.md new file mode 100644 index 000000000..a38ae27bd --- /dev/null +++ b/docs/java/Spring-and-Spring-Boot/spring-environment-setup.md @@ -0,0 +1,172 @@ +--- +id: spring-environment-setup +title: Spring Environment Setup +sidebar_label: spring environment setup +sidebar_position: 2 +tags: [java, spring,core-java, programming, java core, java spring, java web] +description: in thi tutorial you will learn about how to install and use spring framework in you local computer environment. and make your first java spring project in ecllips +--- + +# Spring Environment Setup + +## Step 1 - Setup Java Development Kit (JDK) + +You can download the latest version of SDK from Oracle's Java site − [Java SE Downloads](https://www.oracle.com/java/technologies/javase-downloads.html). You will find instructions for installing JDK in the downloaded files, follow the given instructions to install and configure the setup. Finally, set PATH and JAVA_HOME environment variables to refer to the directory that contains `java` and `javac`, typically `java_install_dir/bin` and `java_install_dir` respectively. + +If you are running Windows and have installed the JDK in `C:\jdk1.6.0_15`, you would have to put the following line in your `C:\autoexec.bat` file. + +```shell +set PATH=C:\jdk1.6.0_15\bin;%PATH% +set JAVA_HOME=C:\jdk1.6.0_15 +``` + +Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button. + +On Unix (Solaris, Linux, etc.), if the SDK is installed in `/usr/local/jdk1.6.0_15` and you use the C shell, you will have to put the following into your `.cshrc` file. + +```shell +setenv PATH /usr/local/jdk1.6.0_15/bin:$PATH +setenv JAVA_HOME /usr/local/jdk1.6.0_15 +``` + +Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE. + +## Step 2 - Install Apache Common Logging API + +You can download the latest version of the Apache Commons Logging API from [Apache Commons Logging](https://commons.apache.org/logging/). Once you download the installation, unpack the binary distribution into a convenient location. For example, in `C:\commons-logging-1.1.1` on Windows, or `/usr/local/commons-logging-1.1.1` on Linux/Unix. This directory will have the following jar files and other supporting documents, etc. + +Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application. + +## Step 3 - Setup Eclipse IDE + +All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine. + +To install Eclipse IDE, download the latest Eclipse binaries from [Eclipse Downloads](https://www.eclipse.org/downloads/). Once you download the installation, unpack the binary distribution into a convenient location. For example, in `C:\eclipse` on Windows, or `/usr/local/eclipse` on Linux/Unix and finally set the PATH variable appropriately. + +Eclipse can be started by executing the following commands on Windows machines, or you can simply double-click on `eclipse.exe`. + +```shell +%C:\eclipse\eclipse.exe +``` + +Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machines − + +```shell +$/usr/local/eclipse/eclipse +``` + +After a successful startup, if everything is fine then it should display the following result − + +## Step 4 - Setup Spring Framework Libraries + +Now if everything is fine, then you can proceed to set up your Spring framework. Following are the simple steps to download and install the framework on your machine. + +1. Make a choice whether you want to install Spring on Windows or Unix, and then proceed to the next step to download the `.zip` file for Windows and `.tz` file for Unix. + +2. Download the latest version of Spring framework binaries from [Spring Releases](https://repo.spring.io/release/org/springframework/spring). + +At the time of developing this tutorial, `spring-framework-4.1.6.RELEASE-dist.zip` was downloaded on a Windows machine. After the downloaded file was unzipped, it gives the following directory structure inside `E:\spring`. + + + +You will find all the Spring libraries in the directory `E:\spring\libs`. Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application. If you are using Eclipse, then it is not required to set CLASSPATH because all the settings will be done through Eclipse. + +Once you are done with this last step, you are ready to proceed to your first Spring example. + +## Steps to Create Spring Application in Eclipse IDE + +Let's see the 5 steps to create the first Spring application using Eclipse IDE. + +### 1. Create the Java Project + +Go to File menu → New → Project → Java Project. Write the project name e.g., `firstspring` and click Finish. Now the Java project is created. + +### 2. Add Spring Jar Files + +There are mainly three jar files required to run this application. + +- `org.springframework.core-3.0.1.RELEASE-A` +- `com.springsource.org.apache.commons.logging-1.1.1` +- `org.springframework.beans-3.0.1.RELEASE-A` + +To load the jar files in Eclipse IDE, right-click on your project → Build Path → Add external archives → select all the required jar files → Finish. + +### 3. Create Java Class + +In this case, we are simply creating the `Student` class with a `name` property. The name of the student will be provided by the XML file. It is just a simple example, not the actual use of Spring. We will see the actual use in the Dependency Injection chapter. To create the Java class, right-click on `src` → New → Class → Write the class name e.g., `Student` → Finish. Write the following code: + +```java +package com.javatpoint; + +public class Student { + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public void displayInfo() { + System.out.println("Hello: " + name); + } +} +``` + +This is a simple bean class, containing only one property `name` with its getter and setter methods. This class contains one extra method named `displayInfo()` that prints the student name with a hello message. + +### 4. Create the XML File + +To create the XML file click on `src` → New → File → Give the file name such as `applicationContext.xml` → Finish. Open the `applicationContext.xml` file, and write the following code: + +```xml + + + + + + + + +``` + +The `bean` element is used to define the bean for the given class. The `property` sub-element of `bean` specifies the property of the `Student` class named `name`. The value specified in the `property` element will be set in the `Student` class object by the IOC container. + +### 5. Create the Test Class + +Create the Java class e.g., `Test`. Here we are getting the object of the `Student` class from the IOC container using the `getBean()` method of `BeanFactory`. Let's see the code of the test class. + +```java +package com.javatpoint; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.xml.XmlBeanFactory; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +public class Test { + public static void main(String[] args) { + Resource resource = new ClassPathResource("applicationContext.xml"); + BeanFactory factory = new XmlBeanFactory(resource); + + Student student = (Student) factory.getBean("studentbean"); + student.displayInfo(); + } +} +``` + +--- + +## Conclusion + +Setting up the Java Development Kit (JDK), Apache Commons Logging API, Eclipse IDE, and Spring Framework libraries are essential steps in preparing your development environment for building Java applications with the Spring Framework. By following these steps, you ensure that your environment is properly configured, enabling you to focus on writing and running your Spring applications efficiently. + +Once your setup is complete, creating your first Spring application becomes straightforward with the help of Eclipse IDE. This guide walked you through the steps to create a simple Spring application, demonstrating the power and flexibility of the Spring Framework. + +With your environment ready and your first application up and running, you're well on your way to exploring the many features and capabilities of Spring. Happy coding! diff --git a/docs/java/Spring-and-Spring-Boot/spring-mvc.md b/docs/java/Spring-and-Spring-Boot/spring-mvc.md new file mode 100644 index 000000000..1135b9f7d --- /dev/null +++ b/docs/java/Spring-and-Spring-Boot/spring-mvc.md @@ -0,0 +1,227 @@ +--- +id: spring-mvc +title: introduction to spring mvc +sidebar_label: Introduction to Spring mvc +sidebar_position: 6 +tags: [java, spring,core-java, programming, java core, java spring, java web,java-mvc,model,view,controller,mvc in] +description: in thi tutorial you will learn about what is MVC and how to sue it in java and it works with java with example +--- +### Spring MVC Tutorial + +Spring MVC is a Java framework used for building web applications. It implements the Model-View-Controller (MVC) design pattern and provides features like Inversion of Control and Dependency Injection. + +#### Spring Web Model-View-Controller + +![Spring Web Model-View-Controller](https://static.javatpoint.com/sppages/images/spring-web-model-view-controller.png) + +- **Model:** Contains the data of the application. It can be a single object or a collection of objects. +- **Controller:** Contains the business logic of the application. Marked with the `@Controller` annotation. +- **View:** Represents the provided information in a particular format. JSP+JSTL is commonly used for creating view pages. + +#### Front Controller + +In Spring Web MVC, the `DispatcherServlet` class acts as the front controller, managing the flow of the Spring MVC application. + +![Flow of Spring Web MVC](https://static.javatpoint.com/sppages/images/flow-of-spring-web-mvc.png) + +- All incoming requests are intercepted by the `DispatcherServlet`. +- The `DispatcherServlet` forwards the request to the appropriate controller. +- The controller returns a `ModelAndView` object. +- The `DispatcherServlet` invokes the specified view component. + +#### Advantages of Spring MVC Framework + +- **Separate roles:** Each role is fulfilled by a specialized object, promoting better code organization. +- **Lightweight:** Utilizes a lightweight servlet container for application development and deployment. +- **Powerful Configuration:** Provides robust configuration for both framework and application classes. +- **Rapid Development:** Facilitates fast and parallel development. +- **Reusable Business Code:** Allows the reuse of existing business objects. +- **Easy to Test:** Supports the creation of JavaBeans classes for easy testing. + +#### Spring Web MVC Framework Example + +##### Required Jar files or Maven Dependency + +If using Maven, add the following dependencies to the `pom.xml` file: + +```xml title="pom.xml" + + + org.springframework + spring-webmvc + 5.1.1.RELEASE + + + + + javax.servlet + servlet-api + 3.0-alpha-1 + +``` + +##### Create the Controller Class + +```java title="controller.java" +package com.javatpoint; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class HelloController { + @RequestMapping("/") + public String display() { + return "index"; + } +} +``` + +##### Provide the entry of controller in the `web.xml` file + +```xml title="web.xml" + + spring + org.springframework.web.servlet.DispatcherServlet + 1 + + + spring + / + +``` + +##### Define the bean in the XML file (`spring-servlet.xml`) + +```xml + + + + + + + + + + + + + +``` + +##### Display the message in the JSP page (`index.jsp`) + +```jsp + + +

Welcome to Spring MVC Tutorial

+ + +``` + +In this tutorial, we've seen how to set up a basic Spring MVC application. With this setup, incoming requests are handled by the `DispatcherServlet`, which maps them to the appropriate controller. The controller then returns a view, which is rendered to the user. + + +##### Create Multiple Controllers + +Let's extend our example to include multiple controllers, each handling different requests. + +1. **Add Dependencies to `pom.xml`** + + Ensure that the Spring Web MVC dependency is included in the `pom.xml` file. + +2. **Create the Request Page (`index.jsp`)** + + Create a simple JSP page containing links to different controllers. + + ```jsp + + + Spring MVC || + Spring Boot + + + ``` + +3. **Create Controller Classes** + + We'll create two controller classes, each handling a different request. + + + + ```java title="HelloController.java" + package com.javatpoint; + + import org.springframework.stereotype.Controller; + import org.springframework.web.bind.annotation.RequestMapping; + + @Controller + public class HelloController1 { + @RequestMapping("/hello1") + public String display() { + return "viewpage1"; + } + } + ``` + + + ```java title="hellocontroller2.java" + package com.javatpoint; + + import org.springframework.stereotype.Controller; + import org.springframework.web.bind.annotation.RequestMapping; + + @Controller + public class HelloController2 { + @RequestMapping("/hello2") + public String display() { + return "viewpage2"; + } + } + ``` + +4. **Provide the Entry of Controllers in `web.xml`** + + Ensure that the `DispatcherServlet` is configured to map requests correctly. + +5. **Define the Bean in the XML File (`spring-servlet.xml`)** + + Define the view resolver to map logical view names to physical JSP files. + +6. **Create the View Pages** + + Create JSP pages corresponding to each controller. + + **viewpage1.jsp** + + ```jsp + + +

Welcome to Spring MVC Tutorial

+ + + ``` + + **viewpage2.jsp** + + ```jsp + + +

Welcome to Spring Boot Tutorial

+ + + ``` + +By following these steps, you can create a Spring MVC application with multiple controllers, each handling specific requests and returning corresponding views. + +This concludes the extended example of a Spring MVC framework. You can now deploy the project and start the server to see the application in action. \ No newline at end of file