0% found this document useful (0 votes)
8 views

Unit5 Java

The Spring Framework is an open-source framework for building enterprise-level Java applications, utilizing Dependency Injection and Inversion of Control for better code management. It includes modules for various development areas and simplifies application creation with Spring Boot. The document outlines how to initialize a Spring application, handle form submissions, and validate input using annotations and controllers.

Uploaded by

begamgulshan30
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit5 Java

The Spring Framework is an open-source framework for building enterprise-level Java applications, utilizing Dependency Injection and Inversion of Control for better code management. It includes modules for various development areas and simplifies application creation with Spring Boot. The document outlines how to initialize a Spring application, handle form submissions, and validate input using annotations and controllers.

Uploaded by

begamgulshan30
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Spring

• The Spring Framework is a popular, open-source framework for building


enterprise-level Java applications that simplifies development by providing
infrastructure support for common tasks, allowing developers to focus on
application logic.
Features
• Spring uses Dependancy Injection, a key design pattern, to manage
dependencies between objects, promoting loose coupling and making code
more maintainable and testable.
• The Spring Framework is composed of several modules, each addressing a
specific area of development, such as web applications (Spring MVC), data
access (Spring Data).
• Aspect-Oriented Programming allows you to modularize cross-cutting
concerns like logging and security, improving code organization.
• Inversion of Control a core principle of Spring, shifts control of objects
from the application to the framework, making it easier to manage and
test.
• Spring Boot is a powerful, open-source Java framework that simplifies
the development of Spring-based applications, allowing you to create
stand-alone, production-ready applications with minimal configuration.
Initialize and configure Spring
application
Navigate to https://start.spring.io.
Project: Choose either Gradle or Maven as your build tool.
Language: Select the language you'll be using (e.g., Java).
Spring Boot: Choose the most recent non-SNAPSHOT release of Spring
Boot.
Project Metadata: Group: Enter your organization's domain name in
reverse order (e.g., com.example).
Artifact: Enter a name for your project.
Dependencies: Select the necessary dependencies for your project (e.g.,
Spring Web, Spring Data JPA).
Click Generate: Once you have configured your project, click the
"Generate" button.
Writing a Spring Application
DemoApplication.java (Main Application Class) - This class is
annotated with @SpringBootApplication, which enables Spring Boot's
auto-configuration, component scanning, and configuration properties.
@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {


SpringApplication.run(DemoApplication.class, args);
}
}
HelloController.java (Controller Class) - REST controller that listens for
GET requests on the /hello endpoint and returns the string "Hello,
World!".

@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
Maven pom.xml Dependencies: POM stands for "Project Object Model".
It is an XML representation of a Maven project held in a file named pom.
xml. The pom.xml should already have the necessary Spring Boot starter
dependencies.
<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>
Processing Form Submission
1. Create a form in the HTML page: This form will submit data
to the Spring controller.
2. Create a controller method to handle the form submission.
3. Bind form data to a model object using Spring's
@ModelAttribute or @RequestParam.
4. Result page.
Step 1: HTML Form
In the HTML view, We create a form that submits data. Spring provides its
own tag library (spring-form) to bind form fields to model attributes easily.
<html>
<body>
<h2>Form Submission Example</h2>
<form:form action="/submit" modelAttribute="user" method="post">
<label for="username">Username:</label>
<form:input path="username" id="username" /><br><br>
</form:form>
</body>
</html>
Step 2: Controller Method
The controller will handle the form submission. In Spring MVC, we’ll create a
controller method that listens for form submissions via @RequestMapping or
@PostMapping.
@Controller
public class UserController {
@GetMapping("/form")
public String showForm(Model model) {
model.addAttribute("user", new User()); // Empty User object to bind form
return "form"; // form.html view
}
@PostMapping("/submit")
public String submitForm(@ModelAttribute User user, Model model) {
System.out.println("Submitted user: " + user);
model.addAttribute("user", user);
return "result"; // Show result after form submission
}
}
Step 3: Model Class (User)
The model class represents the data we're submitting. In this case, we have
a simple User class with username.
public class User {
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@ModelAttribute: Binds form data to the User object. When the form is
submitted, Spring will automatically map the form field (username) to
the properties of the User object.
@PostMapping("/submit"): Handles the POST request when the form is
submitted.
Model: We use the Model to pass data to the view. In this case, after the
form is submitted, we send the user object back to the view to display the
result.
Result Page (result.html) - After the form is submitted, We can display the
results:
<html>
<head>
<title>Submission Result</title>
</head>
<body>
<h2>Form Submission Result</h2>
<p>Username: ${user.username}</p>
</body>
</html>
Validating Form Input
1. Add Validation Annotations in the Model Class: These
annotations ensure that the form input meets certain criteria.
2. Enable Validation in the Controller: Use @Valid or
@Validated in the controller method to trigger validation.
3. Display Validation Errors: If validation fails, the errors are
shown back to the user.
4. Result Page
Step 1: Add Validation Annotations in the Model Class
We can use annotations from the javax.validation.constraints package to
validate the fields in the model class. @NotNull: Ensures the field is not null.
@Size(min, max): Ensures the field's length is between a certain range.
public class User {
@NotNull(message = "Username is required")
@Size(min = 2, max = 30, message = "Username must be between 2 and 30 characters")
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
Step 2: Enable Validation in the Controller
In the controller, We will use the @Valid annotation to tell Spring to
validate the model object before proceeding with the request handling.
@Controller
public class UserController {
@GetMapping("/form")
public String showForm(Model model) {
model.addAttribute("user", new User());
return "form"; // form.html view
}
@PostMapping("/submit")
public String submitForm(@Valid @ModelAttribute User user,
BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
return "form"; // If validation fails, return to the form page
}
// If validation is successful, process the user data
model.addAttribute("user", user);
return "result"; // Show result after form submission
}
}
Step 3: Display Validation Errors in the View
In your view (form.html), we can display validation error messages using
Spring’s form tags.
<html>
<head> <title>Form Submission</title> </head>
<body>
<h2>Form Submission Example</h2>
<form:form action="/submit" modelAttribute="user" method="post">
<label for="username">Username:</label>
<form:input path="username" id="username" />
<form:errors path="username" cssClass="error" /><br><br>
<input type="submit" value="Submit"/>
</form:form>
</body>
</html>
Step 4: Result Page
After the form is submitted successfully, We can display the submitted
data:
<html>
<head> <title>Submission Result</title> </head>
<body>
<h2>Form Submission Result</h2>
<p>Username: ${user.username}</p>
</body>
</html>

You might also like