[go: up one dir, main page]

0% found this document useful (0 votes)
9 views43 pages

Web Tech New

The document outlines a series of web development experiments, including creating HTML pages, using JavaScript for dynamic web functionalities, and implementing server-side programming with Servlets and JSP. Each experiment provides code examples and expected outputs for tasks such as form validation, array methods, and database interactions. The document serves as a comprehensive guide for learning web development concepts and practices.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views43 pages

Web Tech New

The document outlines a series of web development experiments, including creating HTML pages, using JavaScript for dynamic web functionalities, and implementing server-side programming with Servlets and JSP. Each experiment provides code examples and expected outputs for tasks such as form validation, array methods, and database interactions. The document serves as a comprehensive guide for learning web development concepts and practices.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

INDEX

S.N Date of Date of Sign


Name of the Program Implementation Submission

1 Create a simple webpage using HTML.

2 Create a HTML page which has properly aligned paragraph


with Image along with it.
3 Write a program to display list of items in different styles.

4 Use frames to include Images and Videos.

5 Add a Cascading Style Sheet to design a Webpage.

6 Design a dynamic web page with validation using


JavaScript
7 Write a program using JavaScript to demonstrate
the concept of built-in array methods.
8 Write a program using JavaScript to demonstrate
the concept of nested functions.
9 Write programs using JavaScript for Web Page to
display browsers information.
10 Write a program using JavaScript to merge property
of two objects.
11 Write a program using JavaScript to include a JS file
into another JS file.
12 Develop a Servlet to validate user name and
password stored in database. Display
authorized user is she/he is authorized else display
unauthorized user.
13 Write JSP & Servlet program to store student
details sent from registration form in to
database table.
14 Write appropriate JSP pages to insert, update and
delete data in student table in a single
application with proper linking of JSP pages and
session management.
15 Write a java program/servlet application to connect
to a database and extract data from the table
containing employee’s information and display
them.
16 Write program to demonstrate the concept of spring
and spring boot.
17 Create REST Service for an Education Site.
18 Use the Spring Boot Starter Web to Create a Web
Application.
EXPERIMENT – 1
1. Create a simple webpage using HTML.
Code :
<html>
<head>
< tle>Web Development Basics</ tle>
</head>
<body>
<h1>Introduc on to Web Development</h1>
<h3>Frontend and Backend</h3>
<p>Web development refers to crea ng websites and web applica ons.</p>
<br>
<p>It includes designing, coding, and maintaining websites.</p>
<h4>HTML, CSS, and JavaScript are important for frontend development.</h4>
<b>HTML</b> <br>
<i>CSS</i> <br>
<u>JavaScript</u>
</body>
</html>

OUTPUT :-
EXPERIMENT – 2
2. Create a HTML page, which has property aligned paragraphs with image along with
it.
<html>
<head>
< tle>Simple HTML Page</ tle>
</head>
<body>
<h1>Paragraph with Image</h1>
<img src="C:\Users\Downloads\Flower" alt="Flower Image" width="150" height="150">
<p align="jus fy">
Flowers are one of nature's most beau ful crea ons, symbolizing purity and new beginnings.<br>
Their vibrant colors and pleasant fragrances not only upli the environment but also bring<br>
joy and posi vity to our lives.
</p>
</body>
</html>

OUTPUT :-
EXPERIMENT – 3
3. Write a program to display list of items in different styles.
Code:
<html>
<head>< tle></ tle>
</head><body>
<h4>Ordered List</h4>
<ol>
<li>Pen</li>
<li>Pencil</li>
</ol>
<ol type="A">
<li>Coffee</li>
<li>Tea</li>
</ol>
<h4>Unordered List</h4>
<ul>
<li>Pen</li>
<li>Pencil</li>
</ul>
<ul style="list-style-type: square">
<li>Coffee</li>
<li>Tea</li>
</ul>
<ul type="circle">
<li>Pen</li>
</ul>
<h3>Descrip on List</h3>
<dl>
<dt>HTML</dt>
<dd>- HyperText Markup Language</dd>
<dt>CSS</dt>
<dd>- Cascading Style Sheets</dd>
</dl>
</body>
</html>
OUTPUT:-
EXPERIMENT – 4
4. Use frames to include Images and Videos.
Code:
<html>
<head>
< tle>Web Development</ tle>
</head>
<body>
<h3>Introduc on to Web Development - Video</h3>
<p>Web development involves building and maintaining websites.</p>
<iframe width="560" height="250" src="h ps://www.youtube.com/embed/1Rs2ND1ryYc"
tle="Introduc on to Web Development" frameborder="0" allow="fullscreen"></iframe>
<p>This video provides a beginner-friendly introduc on to web development basics including
HTML, CSS, and JavaScript.</p>
<iframe
src="h ps://upload.wikimedia.org/wikipedia/commons/6/61/HTML5_logo_and_wordmark.svg"
width="150" height="150" tle="HTML5 Logo" frameborder="0"></iframe>

<p>This image represents the HTML5 logo, a popular standard for structuring web content.</p>
</body>
</html>

OUTPUT:-
EXPERIMENT – 5
5. Add a Cascading Style sheet for designing the web page.

Index.html file
<html>
<head>
< tle>Types of CSS</ tle>
<link rel="stylesheet" href="styles.css">
<style>
body {
font-family: Arial, sans-serif;
background-color: black;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<h2 style="color: white;">Types of CSS</h2>
<p style="font-size: 18px;">
CSS (Cascading Style Sheets) can be applied in three ways: Inline, Internal, and External.<br></p>
<h4>Inline CSS is wri en directly inside a HTML element's style a ribute.</h4>
<h5>Internal CSS is wri en inside a style tag within the head sec on of the HTML page.</h5>
<h5>External CSS is wri en in a separate .css file and linked to the HTML page using link.</h5>
</body>
</html>

Styles.css file
body {
color: white;
margin: 20px;
}

p{
margin: 20px;
color: yellow;
font-size: 18px;
text-align: jus fy;
}
h4 {
color: white;
text-align: jus fy;
margin: 20px;
}

h5 {
color: #00ffcc;
text-align: jus fy;
margin: 20px;
}

OUTPUT :
EXPERIMENT - 6
6. Design a dynamic web page with valida on using JavaScript.

Code:

<!DOCTYPE html>
<html>
<head>
< tle>Form</ tle>
<script>
func on data() {
var a = document.getElementById("n1").value.trim(); var b =
document.getElementById("n2").value.trim(); var c = document.getElementById("n3").value.trim();
var d = document.getElementById("n4").value.trim();

if (a === "" || b === "" || c === "" || d === "") {


alert("No field can be empty");
return false;
}
if (b.length !== 10) {
alert("Length should be exactly 10 characters"); return false;
}
if (isNaN(b)) {
alert("Only numbers are allowed in Last Name field"); return false;
}
if (c !== d) {
alert("Passwords do not match"); return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return data()" ac on="abc.html">
<label for="fname">First name:</label><br>
<input type="text" id="n1" name="fname"><br>
<label for="lname">Last name (10-digit number):</label><br>
<input type="text" id="n2" name="lname"><br><br>
<label for="pass">Password:</label><br>
<input type="password" id="n3" name="pass"><br><br>
<label for="con">Confirm password:</label><br>
<input type="password" id="n4" name="con"><br><br>
<input type="submit" value="Submit your data">
</form>
<body>
</html>

OUTPUT :-
EXPERIMENT - 7
6. Write a program using JavaScript to demonstrate the concept of built-in array
methods.
Code:
<html>
<head>
< tle>Array Methods Demo</ tle>
</head>
<body>

<h2>JavaScript Array Methods Output</h2>


<pre id="output"></pre>

<script>
const arr = [10, 20, 30, 40, 50];
let output = "";

arr.push(60);
output += "A er push(60): " + arr + "\n";

arr.pop();
output += "A er pop(): " + arr + "\n";

arr.unshi (5);
output += "A er unshi (5): " + arr + "\n";

arr.shi ();
output += "A er shi (): " + arr + "\n";

const sliced = arr.slice(1, 4);


output += "slice(1, 4): " + sliced + "\n";

arr.splice(2, 1, 35);
output += "A er splice(2, 1, 35): " + arr + "\n";

const mapped = arr.map(x => x * 2);


output += "map(x => x * 2): " + mapped + "\n";

const filtered = arr.filter(x => x > 25);


output += "filter(x > 25): " + filtered + "\n";

const sum = arr.reduce((acc, x) => acc + x, 0);


output += "reduce(sum): " + sum + "\n";

output += "indexOf(30): " + arr.indexOf(30) + "\n";


output += "includes(40): " + arr.includes(40) + "\n";
output += "join('-'): " + arr.join('-') + "\n";
output += "sort(): " + arr.slice().sort((a, b) => a - b) + "\n";

document.getElementById("output").innerText = output;
</script>

</body>
</html>

OUTPUT:
EXPERIMENT – 8
8. Write a program using JavaScript to demonstrate the concept of nested
func ons.
Code:
<!DOCTYPE html>
<html>
<head>
< tle>Nested Func ons in JavaScript</ tle>
</head>
<body>
<h2>Nested Func on</h2>
<div id="output"></div>

<script>
func on outerFunc on(name) {
let gree ng = "Hello";

func on innerFunc on() {


return `${gree ng}, ${name}! Welcome to nested func ons in JavaScript.`;
}

return innerFunc on();


}

let message = outerFunc on("abcd");


document.getElementById("output").innerText = message;
</script>
</body>
</html>

OUTPUT:
EXPERIMENT – 9
9. Write programs using JavaScript for Web Page to display browsers informa on.

Code:
<!DOCTYPE html>
<html><head>
< tle>Browser Informa on</ tle>
</head>
<body>
<h2>Browser Informa on</h2>
<div id="browser-info" style="font-family: Arial; line-height: 1.6;"></div>
<script>
const info = `
<strong>Browser Code Name:</strong> ${navigator.appCodeName} <br>
<strong>Browser Name:</strong> ${navigator.appName} <br>
<strong>Browser Version:</strong> ${navigator.appVersion} <br>
<strong>Pla orm:</strong> ${navigator.pla orm} <br>
<strong>User Agent:</strong> ${navigator.userAgent} <br>
<strong>Language:</strong> ${navigator.language} <br>
<strong>Online:</strong> ${navigator.onLine ? "Yes" : "No"} <br>`;
document.getElementById("browser-info").innerHTML = info;
</script>
</body>
</html>

OUTPUT:
EXPERIMENT – 10
10.Write a program using JavaScript to merge property of two objects.
Code:
<!DOCTYPE html>
<html>
<head>
< tle>Merge Two Objects</ tle>
</head>
<body>
<h2>Merged Object Output</h2>
<pre id="output" style="background: #f4f4f4; padding: 10px;"></pre>
<script>
const object1 = {
name: "John",
age: 22
};
const object2 = {
course: "MCA",
college: "Galgo as College"
};
const mergedObject1 = { ...object1, ...object2 };
const mergedObject2 = Object.assign({}, object1, object2);
const result = `
Method 1: Spread Operator
${JSON.stringify(mergedObject1, null, 2)}
Method 2: Object.assign()
${JSON.stringify(mergedObject2, null, 2)}
`;
document.getElementById("output").innerText = result;
</script>
</body>
</html>
OUTPUT:-
EXPERIMENT – 11
11.Write a program using JavaScript to include a JS file into another JS file.

// mathU ls.js
export func on add(a, b) { return a + b;
}
export func on subtract(a, b) { return a - b; }

// main.js
import { add, subtract } from './mathU ls.js';
console.log("Addi on: ", add(10, 5)); console.log("Subtrac on: ", subtract(10, 5));
document.body.innerHTML += `<p>Addi on: ${add(10, 5)}</p>`;
document.body.innerHTML += `<p>Subtrac on: ${subtract(10, 5)}</p>`;

//index.html
<html>
<head>
< tle>Include JS File into Another</ tle>
</head>
<body>
<h2>Result will be shown below:</h2>
<script type="module" src="main.js"></script>
</body>
</html>
OUTPUT:-
EXPERIMENT – 12
12. Develop a Servlet to validate user name and password stored in the database. Display
authorized user is she/he is authorized else display unauthorized user.
SQL File

CREATE DATABASE loginDB;


USE loginDB;
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL
);
INSERT INTO users (username, password) VALUES
('admin', 'admin123'),
('user1', 'password1');

LoginServlet.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.h p.*;
public class LoginServlet extends H pServlet {
protected void doPost(H pServletRequest request, H pServletResponse response)
throws ServletExcep on, IOExcep on {
String username = request.getParameter("username");
String password = request.getParameter("password");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connec on con = DriverManager.getConnec on( "jdbc:mysql://localhost:3306/loginDB",
"root", " ");
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM users WHERE username=? AND password=?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
out.println("<h2>Authorized User</h2>");
} else {
out.println("<h2>Unauthorized User</h2>");
}
con.close();
} catch (Excep on e) {
out.println("Error: " + e.getMessage());
}
}
}

web.xml
<!-- LoginServlet Configura on -->
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pa ern>/login</url-pa ern>
</servlet-mapping>
</web-app>

login.html
<html>
<body>
<form ac on="login" method="post">
Username: <input type="text" name="username"/><br><br>
Password: <input type="password" name="password"/><br><br>
<input type="submit" value="Login"/>
</form>
</body>
</html>

OUTPUT:-
For Authorized User:

For Unauthorized User:


EXPERIMENT – 13
13. Write JSP & Servlet program to store student details sent from registra on form into
database table.
Student Database
CREATE DATABASE studentdb;
USE studentdb;
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
course VARCHAR(100)
);

Registra on.jsp
<html>
<head>
< tle>Student Registra on</ tle>
</head>
<body>
<h2>Student Registra on Form</h2>
<form ac on="register" method="post">
Name: <input type="text" name="name"><br><br>
Email: <input type="text" name="email"><br><br>
Course: <input type="text" name="course"><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>

RegisterServlet.java

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.h p.*;

public class RegisterServlet extends H pServlet {


protected void doPost(H pServletRequest request, H pServletResponse response)
throws ServletExcep on, IOExcep on {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String name = request.getParameter("name");


String email = request.getParameter("email");
String course = request.getParameter("course");

try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connec on con = DriverManager.getConnec on(
"jdbc:mysql://localhost:3306/studentdb", "root", " ");

PreparedStatement ps = con.prepareStatement(
"insert into students(name, email, course) values(?, ?, ?)");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, course);

int i = ps.executeUpdate();
if (i > 0)
out.println("<h3>Registra on Successful!</h3>");
else
out.println("<h3>Registra on Failed!</h3>");

con.close();
} catch (Excep on e) {
e.printStackTrace(out);
}
out.close();
}
}

Web.xml
<web-app xmlns="h p://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pa ern>/register</url-pa ern>
</servlet-mapping>
</web-app>

OUTPUT
EXPERIMENT – 14
14. Write appropriate JSP pages to insert, update and delete data in student table in a
single applica on with proper linking of JSP pages and session management.
Student table
CREATE DATABASE studentdb;
USE studentdb;
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
course VARCHAR(100)
);

insert.jsp
<%
if (session.getA ribute("user") == null) {
response.sendRedirect("login.jsp");
return;
}
%>
<h2>Insert Student</h2>
<form method="post">
Name: <input type="text" name="name"/><br><br>
Email: <input type="text" name="email"/><br><br>
Course: <input type="text" name="course"/><br><br>
<input type="submit" value="Insert"/>
</form>
<%@ include file="db.jsp" %>
<%
String name = request.getParameter("name");
String email = request.getParameter("email");
String course = request.getParameter("course");
if (name != null && email != null && course != null) {
PreparedStatement ps = conn.prepareStatement("INSERT INTO students(name, email,
course) VALUES (?, ?, ?)");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, course);
int i = ps.executeUpdate();
if (i > 0) {
out.println("<p>Student Inserted Successfully!</p>");
}
conn.close();
}
%>
<a href="view.jsp">Back to Dashboard</a>

update.jsp

<%
if (session.getA ribute("user") == null) {
response.sendRedirect("login.jsp");
return;
}
%>
<h2>Update Student</h2>
<form method="post">
ID to Update: <input type="text" name="id"/><br><br>
New Name: <input type="text" name="name"/><br><br>
New Email: <input type="text" name="email"/><br><br>
New Course: <input type="text" name="course"/><br><br>
<input type="submit" value="Update"/>
</form>
<%@ include file="db.jsp" %>
<%
String id = request.getParameter("id");
String name = request.getParameter("name");
String email = request.getParameter("email");
String course = request.getParameter("course");
if (id != null && name != null && email != null && course != null) {
PreparedStatement ps = conn.prepareStatement("UPDATE students SET name=?, email=?,
course=? WHERE id=?");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, course);
ps.setInt(4, Integer.parseInt(id));
int i = ps.executeUpdate();
if (i > 0) {
out.println("<p>Student Updated Successfully!</p>");
} else {
out.println("<p>ID not found!</p>");
}
conn.close();
}
%>
<a href="view.jsp">Back to Dashboard</a>

delete.jsp
<%
if (session.getA ribute("user") == null) {
response.sendRedirect("login.jsp");
return;
}
%>
<h2>Delete Student</h2>
<form method="post">
ID to Delete: <input type="text" name="id"/><br><br>
<input type="submit" value="Delete"/>
</form>
<%@ include file="db.jsp" %>
<%
String id = request.getParameter("id");
if (id != null) {
PreparedStatement ps = conn.prepareStatement("DELETE FROM students WHERE id=?");
ps.setInt(1, Integer.parseInt(id));
int i = ps.executeUpdate();
if (i > 0) {
out.println("<p>Student Deleted Successfully!</p>");
} else {
out.println("<p>ID not found!</p>");
}
conn.close();
}
%>
<a href="view.jsp">Back to Dashboard</a>

view.jsp
<%
if (session.getA ribute("user") == null) {
response.sendRedirect("login.jsp");
return;
}
%>
<h2>Welcome, <%= session.getA ribute("user") %>!</h2>
<a href="insert.jsp">Insert Student</a> |
<a href="update.jsp">Update Student</a> |
<a href="delete.jsp">Delete Student</a> |
<a href="logout.jsp">Logout</a>
<br><br>
<%@ include file="db.jsp" %>
<h3>All Students</h3>
<table border="1">
<tr><th>ID</th><th>Name</th><th>Email</th><th>Course</th></tr>
<%
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
while (rs.next()) {
%>
<tr>
<td><%= rs.getInt("id") %></td>
<td><%= rs.getString("name") %></td>
<td><%= rs.getString("email") %></td>
<td><%= rs.getString("course") %></td>
</tr>
<%
}
conn.close();
%>
</table>

db.jsp

<%@ page import="java.sql.*" %>


<%
Connec on conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnec on("jdbc:mysql://localhost:3306/studentdb", "root", " ");
}
catch (Excep on e) {
out.println(e);
}
%>

OUTPUT:-
EXPERIMENT – 15
15. Write a Java program/servlet applica on to connect to a database and extract data
from the table containing employee’s informa on and display them.
EmployeeServlet.java File

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.h p.*;

public class EmployeeServlet extends H pServlet {


protected void doGet(H pServletRequest request, H pServletResponse response)
throws ServletExcep on, IOExcep on {
String jdbcURL = "jdbc:mysql://localhost:3306/company";
String dbUser = "root";
String dbPassword = " ";
response.setContentType("text/html");
PrintWriter out = response.getWriter();

try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connec on conn = DriverManager.getConnec on(jdbcURL,dbUser,dbPassword);
String sql = "SELECT * FROM employees";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
out.println("<html><body><h2>Employee Details</h2>");
out.println("<tableborder='1'><tr><th>ID</th><th>Name</th><th>
Department</th></tr>");
while (rs.next()) {
out.println("<tr><td>" + rs.getInt("id") + "</td><td>" + rs.getString("name") + "</td><td>"
+ rs.getString("department") + "</td></tr>");
}
out.println("</table></body></html>");
rs.close();
stmt.close();
conn.close();
} catch (Excep on e) {
out.println("Error: " + e.getMessage());
}
}
}

WEB.XML File
<web-app xmlns="h p://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<servlet>
<servlet-name>EmployeeServlet</servlet-name>
<servlet-class>EmployeeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>EmployeeServlet</servlet-name>
<url-pa ern>/employees</url-pa ern>
</servlet-mapping>
</web-app>

MYSQL File
CREATE DATABASE company;
USE company;
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
department VARCHAR(50)
);
INSERT INTO employees (id, name, department) VALUES
(1, 'John', 'IT'),
(2, 'Smith', 'HR');
OUTPUT :
EXPERIMENT – 16
16. Write program to demonstrate the concept of spring and spring boot.
Code:
class Gree ng {
private String message;
public Gree ng(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
// Spring Component
@Component
class Gree ngService {
public Gree ng getGree ng() {
return new Gree ng("Hello, Spring!");
}
}

// Spring Boot Applica on @SpringBootApplica on public class DemoApplica on {


public sta c void main(String[] args) {
// Run the Spring Boot applica on
SpringApplica on.run(DemoApplica on.class, args);

// Get the applica on context


Applica onContext context = SpringApplica on.run(DemoApplica on.class, args);

// Get the Gree ngService bean from the context


Gree ngService gree ngService = context.getBean(Gree ngService.class);

// Get the gree ng message


Gree ng gree ng = gree ngService.getGree ng();
// Print the gree ng message
System.out.println(gree ng.getMessage());
}
}

OUTPUT :
EXPERIMENT – 17
17. Create REST Service for an Educa on Site.
Code:

package com.educa on.site;


import org.springframework.boot.SpringApplica on;
import org.springframework.boot.autoconfigure.SpringBootApplica on; import
org.springframework.web.bind.annota on.*;
import java.u l.*;
import java.u l.concurrent.atomic.AtomicLong;
@SpringBootApplica on
@RestController
@RequestMapping("/api/courses")
public class Educa onSiteApplica on {
public sta c void main(String[] args) {
SpringApplica on.run(Educa onSiteApplica on.class, args);
}
Map<Long, Course> courseRepo = new HashMap<>();
private AtomicLong idCounter = new AtomicLong();
// ===== CRUD Endpoints =====
@GetMapping
public Collec on<Course> getAllCourses() {
return courseRepo.values();
}
@GetMapping("/{id}")
public Course getCourseById(@PathVariable Long id) {
return courseRepo.get(id);
}

@PostMapping
public Course addCourse(@RequestBody Course course)
{
long id = idCounter.incrementAndGet();
course.setId(id);
courseRepo.put(id, course);
return course;
}
@PutMapping("/{id}")
public Course updateCourse(@PathVariable Long id, @RequestBody Course course)
{
course.setId(id);
courseRepo.put(id, course);
return course; }
@DeleteMapping("/{id}")
public void deleteCourse(@PathVariable Long id) {
courseRepo.remove(id);
}

// ===== Course POJO =====


sta c class Course {
private Long id;
private String tle;
private String descrip on;
public Long getId() {
return id; }
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return tle;
}
public void setTitle(String tle)
{
this. tle = tle;
}
public String getDescrip on() {
return descrip on;
}
public void setDescrip on(String descrip on)
{
this.descrip on = descrip on;
}
}
}
EXPERIMENT – 18
18. Use the Spring Boot Starter Web to Create a Web Applica on.
DemoApplica on.java
package com.example.demo;

import org.springframework.boot.SpringApplica on;


import org.springframework.boot.autoconfigure.SpringBootApplica on;

@SpringBootApplica on
public class DemoApplica on {

public sta c void main(String[] args) {


SpringApplica on.run(DemoApplica on.class, args);
}
}

HelloController.java

package com.example.demo.controller;
import org.springframework.web.bind.annota on.GetMapping;
import org.springframework.web.bind.annota on.RestController;
@RestController
public class HelloController {
@GetMapping("/")
public String hello() {
return "Hello, Welcome to Spring Boot Web Applica on!";
}
}
pom.xml
<project xmlns="h p://maven.apache.org/POM/4.0.0"
xmlns:xsi=h p://www.w3.org/2001/XMLSchema-instance
xsi:schemaLoca on="h p://maven.apache.org/POM/4.0.0
h p://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<ar factId>demo</ar factId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<descrip on>Demo project for Spring Boot Starter Web</descrip on>
<parent>
<groupId>org.springframework.boot</groupId>
<ar factId>spring-boot-starter-parent</ar factId>
<version>3.2.5</version>
<rela vePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<ar factId>spring-boot-starter-web</ar factId>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<ar factId>spring-boot-starter-test</ar factId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<ar factId>spring-boot-maven-plugin</ar factId>
</plugin>
</plugins>
</build>
</project>

OUTPUT:

You might also like