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

Advanced Java Programming Lab

lab

Uploaded by

Usri Devi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

Advanced Java Programming Lab

lab

Uploaded by

Usri Devi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 100

ENGINEERING COLLEGE

(AUTONOMOUS)

Komarapalayam – 637 303

MASTER OF COMPUTER APPLICATIONS

SECOND SEMESTER

23PMC207 – ADVANCED JAVA PROGRAMMING


LABORATORY

Name :

Register No. :

DEPARTMENT OF MCA

JUNE - 2024
E N G I N E E R I N G COLLEGE
(AUTONOMOUS)
Komarapalayam – 637

DEPARTMENT OF MCA

BONAFIDE CERTIFICATE

Certified that this is bonafide record of practical work

Done by :

Register No:

for 23PMC207 – ADVANCED JAVA PROGRAMMING LABORATORY

of the Second semester of Master of Computer Applications


during June 2024

Staff in-charge Head of the Department

Submitted for the University Practical Examination held on

Internal Examiner External Examiner


23PMC207 – ADVANCED JAVA PROGRAMMING LABORATORY

S. No Date Experiments Page no Sign

1
22/03/2024 Event Registration and Form Validation Using
Javascript and IndexedDB

2 Build Java Script application using Classes and


05/04/2024 Modules with Indexed DB (Browser Storage
Persistance)

3 18/04/2024 Build Web Application Using Gradle

4 26/04/2024 Spring Web Socket Api

5 File Upload and validation using Spring MVC


03/05/2024
Application

6 RESTful Spring Boot application using Spring


10/05/2024
REST, Spring Security

7 Spring JPA and Hibernate and Perform Crud &


16/05/2024
JPQL queries using Restful API

8 24/05/2024 Spring Restful Application with Spring Data


JPA(H2 Database)

9 31/05/2024 Build React Application with components and


components

10 Build a Full-Stack Application with React and


14/06/2024
Spring
EX NO:1 Event Registration and Form Validation Using Javascript and
IndexedDB

Aim:
To Create an event registration application using javascript. It should implement
different widgets for registration form and registered records view using tabs. It should
perform the form validation.
IndexedDB:

Indexeddb is an alternative for web SQL data base and more effective than older technologies.
Features
• it stores key-pair values

• it is not a relational database

• IndexedDB API is mostly asynchronous

• it is not a structured query language

• it has supported to access the data from same domain


Algorithm:

Step1: Indexeddb is a buit-in storage which is available in google chrome


Step2: to view Indexeddb database click three icone in chrome  go to More tools click
Developers Tools
Step3: click the << arrow mark:
Step4: Click the application option

Step5:Click the indexeddB database:


Source Code:
Indexedbdemo.html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/idb.min.js"></script>
<form name="RegForm" onsubmit="return validate()" method="post">

<table cellspacing=5 cellpadding=5 border=5>


<tr colspan=2><td >REGISTRATION FORM</td></tr>
<tr><td>Name:</td><td> <input type="text"
size="65" name="Name" /></p></td></tr>
<tr><td>

<p>E-mail Address:</td><td> <input type="text"


size="65" name="EMail" /></p></td></tr>
<tr>
<td><p>Telephone: </td><td><input type="text"
size="65" name="phone" /></p></td></tr>
<br />
<tr><td>
Address:</td><td> <input type="text"
size="65" name="Address" /></td></tr>
<tr>
<td>
<p>
SELECT YOUR COURSE</td><td>
<select type="text" value="" name="Subject">
<option>MCA</option>
<option>MBA</option>
<option>BCA</option>
<option>B.COM</option>

</select>
</td>
</tr>
<tr><td>
<button onclick="addStudent()">Add a student</button></td><td>
<button onclick="clearStudents()">Clear student</button></td></tr>
</table>

<p>student list:</p>

<ul id="listElem"></ul>
</form>
<script>
let res;
function validate() {
var name =
document.forms["RegForm"]["Name"];
var email =
document.forms["RegForm"]["EMail"];
var phone =
document.forms["RegForm"]["Telephone"];
var what =
document.forms["RegForm"]["Subject"];
var password =
document.forms["RegForm"]["Password"];
var address =
document.forms["RegForm"]["Address"];

if (name.value == "") {
window.alert("Please enter your name.");
name.focus();
return false;
}

if (address.value == "") {
window.alert("Please enter your address.");
address.focus();
return false;
}

if (email.value == "") {
window.alert(
"Please enter a valid e-mail address.");
email.focus();
return false;
}

if (phone.value == "") {
window.alert(
"Please enter your telephone number.");
phone.focus();
return false;
}

if (what.selectedIndex < 1) {
alert("Please enter your course.");
what.focus();
return false;
}

return true;
}
let db;

init();

async function init() {


db = await idb.openDb('studentDb', 1, db => {
db.createObjectStore('students', {keyPath: 'sname'});
});

list();
}

async function list() {


let tx = db.transaction('students');
let studentStore = tx.objectStore('students');

let students = await studentStore.getAll();

if (students.length) {
listElem.innerHTML = students.map(student => `<li>
name: ${student.sname}, mail: ${student.email},phone: ${student.phone},address: $
{student.address}
course: ${student.course}</li>`).join('');
} else {
listElem.innerHTML = '<li>No students yet. Please add students.</li>'
}

async function clearStudents() {


let tx = db.transaction('students', 'readwrite');
await tx.objectStore('students').clear();
await list();
}

async function addStudent() {

var sn = document.forms["RegForm"]["Name"];
var em = document.forms["RegForm"]["EMail"];
sname=sn.value;
email=em.value;
var phone= document.forms["RegForm"]["phone"].value;
var address = document.forms["RegForm"]["Address"].value;
var course = document.forms["RegForm"]["Subject"].value;
let tx = db.transaction('students', 'readwrite');
try {
await tx.objectStore('students').add({sname, email,phone,address,course});
await list();
} catch(err)
{
if (err.name == 'ConstraintError') {
alert("Such studentexists already");
await addStudent();
} else {
throw err;
}
}

}
window.addEventListener('unhandledrejection', event => {
alert("Error: " + event.reason.message);
});

</script>

Output:
Validation Performed on registration

Successfully inserted in indexed db


Inserting the second record

Values in Indexeddb database:


Result:
Thus the Program executed successfully.
Build Java Script application using Classes and Modules with Indexed DB
EX NO:2
(Browser Storage Persistance)

AIM:

Create a javascript application in an Object Oriented way using Classes and Modules. It
should also use browser storage for persistence.
ALGORITHM:

Step1: Create the class namedEmployee


Step2:Create Constructor with 2 arguments as id and name
Step3:Create detail() Method to display employee id and employee name
Step4:Create Object for Employee Class as e1 and e2
Step5:Write IndexedDB code and create the database named sriviims
Step6: Create Constant type array in the name of employeeData
Step7:Add the Value of Constant array with Database in Browser
Step8: Display the Output
Sourcecode:
<!DOCTYPE html>
<html>
<body>

<script>
//Declaring class

class Employee
{

//Initializing an object
constructor(id,name)
{
this.id=id;
this.name=name;
}

//Declaring method

detail()
{
document.writeln("&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Employee id :"+ this.id+"
"+", Employee name:"+ this.name+" <br>");

}
}

//passing object to a variable

var e1=new Employee(101,"Dr.Srimathi");

var e2=new Employee(102,"Nivedha.J");

window.indexedDB = window.indexedDB || window.mozIndexedDB ||


window.webkitIndexedDB || window.msIndexedDB;

//prefixes of window.IDB objects


window.IDBTransaction = window.IDBTransaction ||
window.webkitIDBTransaction || window.msIDBTransaction;

window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange ||


window.msIDBKeyRange

if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.")
}
var db;
var request = window.indexedDB.open("sriviims", 1);
request.onerror = function(event) {
console.log("error: ");
};

request.onsuccess = function(event) {
db = request.result;
console.log("success: "+ db);
};

request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("employee", {keyPath: "id"});
const employeeData = [
{ id: e1.id, name: e1.name },
{ id: e2.id, name: e2.name}
];
for (var i in employeeData) {
objectStore.add(employeeData[i]);
alert("added");
}
}
document.writeln("&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;");
document.writeln(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br>");
document.writeln("&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp;");
document.writeln(" <b> Employee Details <br>");
document.writeln("&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;");
document.writeln(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br>");
e1.detail(); //calling method
e2.detail();
document.writeln("<br><b>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
Successfully added in indexed db...... ");
</script>

</body>
</html>

Output:
To check whether the value is added in indexeddb in browser goto
Dev tools click applications click indexeddb option and verify srivvims db has created and
record inserted.
Result:

Thus the program executed successfully.


EX NO:3 Build Web Application Using Gradle

AIM:

To Build a web application using Gradle. The server side of the application should
implement RESTful APIs using Servlet and do necessary logging. The client side of the
application should be a single page application which consumes the RESTful APIs through
AJAX.
Gradle is a build automation tool known for its flexibility to build software. A build
automation tool is used to automate the creation of applications. The building process includes
compiling, linking, and packaging the code.
ALGORITHM:

Steps1: Open Eclipse


Step2: Install gradle

Step3: Create new gradle project

In Eclipse, go to File → New → Other… menu path to select new project.


In New wizard, select Gradle Project and click on Next.
In next wizard, preview the project configuration and click on Finish.

Step 4: Project Structure


project structure

Step5: Add the following code in build.gradle


Build.gradle:

/*
* This build file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java Library project to get you started.
* For more details take a look at the Java Libraries chapter in the Gradle
* user guide available at https://docs.gradle.org/4.3/userguide/java_library_plugin.html
*/

// Apply the java-library plugin to add support for Java Library


apply plugin: 'java-library'
apply plugin: 'java'
apply plugin: 'application'

// In this section you declare where to find the dependencies of your project
repositories {
// Use jcenter for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
}

dependencies {
// This dependency is exported to consumers, that is to say found on their compile classpath.
api 'org.apache.commons:commons-math3:3.6.1'
compile 'com.google.guava:guava:20.0' // Google Guava dependency
testCompile 'junit:junit:4.12' // JUnit dependency for testing
// This dependency is used internally, and not exposed to consumers on their own compile
classpath.
implementation 'com.google.guava:guava:23.0'

// Use JUnit test framework


testImplementation 'junit:junit:4.12'
}
mainClassName = 'com.boraji.tutorial.MainApp' // Main class with main method

Step6: Create MainAppTest.java file under src/test/java folder and write the following JUnit testcase in it.

package com.boraji.tutorial;

import org.junit.Test;
import static org.junit.Assert.*;
public class MainAppTest {
@Test
public void testSayHello() {
MainApp app = new MainApp();
assertNotNull("Success", app.sayHello());
}

Step7: Create MainAppTest.java file under src/test/java folder and write the following JUnit testcase in it.

Create MainAppTest.java file under src/test/java folder and write the following JUnit testcase in it.

package com.boraji.tutorial;

import org.junit.Test;
import static org.junit.Assert.*;
public class MainAppTest {
@Test
public void testSayHello() {
MainApp app = new MainApp();
assertNotNull("Success", app.sayHello());
}

}
Step8: To show the Gradles Tasks view:
In the menu choose Window > Show View > Other..., select Gradle > Gradle
Tasks and click Open.
Step9: Build the Project: In Gradle Tasks view/tab, right click on the build task
and select Run Gradle Tasks to build the java project.
Step10: Gradle execution Output:

Result:

Thus the Program Executed Successfully.


EX NO:4 SPRING WEB SOCKET API

AIM:
To Create A Chat Application Using Spring Web Socket API.
ALGORITHM:
STEP 1:Install and open the eclipse to create a java based maven project ,go to
"FILE=>NEW =>DYNAMIC WEB PROJECT

STEP 2: Enter the project name Websocketserver and browse the project location and click
next

STEP 3 : Right click on SRC =>NEW=>PACKAGE=>server.ws=>FINISH


STEP 4: Right click on server.ws package=>NEW=>CLASS name as
WsServer=>FINISH

STEP 5 :Right clickon WebContent=>NEW=>HTML Name aswsclient=>NEXT=>FINISH


STEP 6: Run the project
PROGRAM CODING:

WsServer.java
package server.ws;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/websocketendpoint")
public class WsServer {
@OnOpen
public void onOpen(){
System.out.println("Open Connection ...");
}
@OnClose
public void onClose(){
System.out.println("Close Connection ...");
}
@OnMessage
public String onMessage(String message){
System.out.println("Message from the client: " + message);
String echoMsg = "Echo from the server : " + message;
return echoMsg;
}
@OnError
public void onError(Throwable e){
e.printStackTrace();
}}
Web.Xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://
xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>WebSocketServerExample</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list></web-app>
Wsclient.Html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tomcat WebSocket</title>
</head>
<body>
<form>
<input id="message" type="text">
<input onclick="wsSendMessage();" value="Echo" type="button">
<input onclick="wsCloseConnection();" value="Disconnect" type="button">
</form>
<br>
<textarea id="echoText" rows="5" cols="30"></textarea>
<script type="text/javascript">
varwebSocket = new
WebSocket("ws://localhost:8080/WebSocketServerExample/websocketendpoint");
varechoText = document.getElementById("echoText");
echoText.value = "";
var message = document.getElementById("message");
webSocket.onopen = function(message){ wsOpen(message);};
webSocket.onmessage = function(message){ wsGetMessage(message);};
webSocket.onclose = function(message){ wsClose(message);};
webSocket.onerror = function(message){ wsError(message);};
functionwsOpen(message)
{
echoText.value += "Connected ... \n";
}

functionwsSendMessage()
{
webSocket.send(message.value);
echoText.value += "Message sended to the server : " + message.value + "\n";
message.value = "";
}
functionwsCloseConnection()
{
webSocket.close();
}
functionwsGetMessage(message)
{
echoText.value += "Message received from to the server :message.data + "\n";
}
functionwsClose(message)
{
echoText.value += "Disconnect ... \n";
}

functionwserror(message){
echoText.value += "Error ... \n";
}
</script>
</body>
</html>

OUTPUT:
RESULT :

Thus the program executed successfully.


EX NO:5 File Upload and validation using Spring MVC Application

AIM:

To Create a Spring MVC application. The application should handle form


validation, file upload, session tracking.
ALGORITHM:

Step1; To handle file uploads, Spring provides a MultipartResolver bean which is responsible
for resolving multipart request. This resolver is working with two file upload libraries:
Step2: Declare the MultipartResolverbean in Spring’s context file
For CommonsMultipartResolver:
<bean
 id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 <!-- max file size in bytes -->
<property name="maxUploadSize" value="2000000" />
<!-- other properties... -->
</bean>
And for CosMultipartResolver:

Step3: Add to classpath jar files of the file upload library employed:

o For Apache Commons File Upload: commons-fileupload-VERSION.jar and commons-io-


VERSION.jar (Commons File Upload depends on Commons IO).

o For COS: cos.jar

<bean id="multipartResolver"
class="org.springframework.web.multipart.cos.CosMultipartResolver">
<!-- max file size in bytes -->
<property name="maxUploadSize" value="2000000" />
<!-- other properties... -->
</bean>
Step4: Create the projectstructure

Step5: Create file upload form using jsp file Create a new JSP file called UploadForm.jsp under
project’s WebContent directory,

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring MVC File Upload Demo</title>
</head>
<body>
<center>
<h1>Spring MVC File Upload Demo</h1>
<form method="post" action="uploadFile.do" enctype="multipart/form-data">
<table border="0">
<tr>
<td>Description:</td>
<td><input type="text" name="description" size="50"/></td>
</tr>
<tr>
<td>Pick file #1:</td>
<td><input type="file" name="fileUpload" size="50" /></td>
</tr>
<tr>
<td>Pick file #2:</td>
<td><input type="file" name="fileUpload" size="50" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Upload" /></td>
</tr>
</table>
</form>
</center>
</body>
</html>
Form outlook:

Step6: Configuring Spring MVC and MultipartResolver


Create a Spring’s context configuration file under project’s WebContent\WEB-
INFdirectory, called spring-mvc.xml:
Paste the following code in spring-mvc.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="net.codejava.spring" />

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- max upload size in bytes -->
<property name="maxUploadSize" value="20971520" /> <!-- 20MB -->

<!-- max size of file in memory (in bytes) -->


<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->

</bean>

<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.Exception">Error</prop>
</props>
</property>
</bean>
</beans>
Step7: Enable Spring to handle requests coming into this application by creating web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>FileUploadSpringMVC</display-name>

<servlet>
<servlet-name>SpringController</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>SpringController</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>UploadForm.jsp</welcome-file>
</welcome-file-list>
</web-app>
Step8: Spring Controller Creation

Create Package: net.codejava.spring

Name: FileUploadController

FileUploadController.class

package net.codejava.spring;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
@RequestMapping("/uploadFile.do")
public class FileUploadController {

private String saveDirectory = "E:/Test/Upload/";

@RequestMapping(method = RequestMethod.POST)
public String handleFileUpload(HttpServletRequest request,
@RequestParam CommonsMultipartFile[] fileUpload) throws Exception {

System.out.println("description: " + request.getParameter("description"));

if (fileUpload != null && fileUpload.length > 0) {


for (CommonsMultipartFile aFile : fileUpload){

System.out.println("Saving file: " + aFile.getOriginalFilename());

if (!aFile.getOriginalFilename().equals("")) {
aFile.transferTo(new File(saveDirectory + aFile.getOriginalFilename()));
}
}
}

// returns to the view "Result"


return "Result";
}
}

Note: Annotation Used

@Controller: marks this class as a Spring controller.

@RequestMapping:

Step9:Create result page and error page


Result.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload Result</title>
</head>
<body>
<center>
<h2>The file(s) was uploaded successfully!</h2>
</center>
</body>
</html>

Note:
This page simply displays a message when the upload was successful.
Error.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Error</title>
</head>
<body>
<center>
<h2>Sorry, there was an error occurred:</h3>
<h3>${exception.message}</h2>
</center>
</body>
</html>
Note:
This error page displays error message of the thrown exception
Step10: Final structure of file:
Step11: run the Project
http://localhost:8080/FileUploadSpringMVC/
The upload form is displayed, type something into the Description field and pick up two
arbitrary files, then hit Upload:
Output:

The following result page after the files were uploaded successfully:

if we pick up a file which is larger than the configured max upload size, the error page will be
displayed instead:

Result:

Thus the program executed successfully.


RESTful Spring Boot application using Spring REST, Spring
EX NO:6
Security
AIM:
To Implement a RESTful Spring Boot application using Spring REST, Spring Security
and Spring Cache.
Algorithm:
a) Authentication through Built in Password Provided by Spring Security
Step1: Create the spring boot project name: srisecureapp, group: com.viimsexample, package
as com.viimsexample.secure

Step 2:Click Next button

Step 3: select spring web, spring security

Step 4: Create Home Controller


Create method (mention as @requestmapping before method)

Step 5: Write the following code in HomeController.java:

HomeController.java:
package com.viimsexample.secure;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {
@RequestMapping("/")
public String home()
{
return "home.jsp";
}

}
Step6: Create webapp folder under main folderè src/main ( to create jsp)

 Create home.jsp and write the following codings:


 Home.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>
<h1><font color=red> welcome Aliens</font></h1>

</body>
</html>
Step7: To access jsp in spring boot include jasper dependency in pom.xml as follows:

To work with jsp in spring boot go to maven dependency and add jasper in pom.xml

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.46</version>
</dependency>

Step8: Want to secure webapp to access home.jsp, Create login.jsp


Spring security automatic creation by spring boot itself create user name and password
 By default usersname is user
Password go and check it in console paste it
Step9: run the project and output is

Step10 : JSR303,JSR349,JSR380  used for bean API validation and Hibernate validate
Step11: go to google and search jasr 349 maven dependency and Copy down maven
dependency of 2.0.1

b) We want to create our own password and username

Create ApplicationSecurityConfig.java
ApplicationSecurityConfig.java
a. Then extend the class to WebSecurityConfigurerAdapter
b. To denote this class belongs to configuration use è@configuration
c. Use @EnableWebSecurity
d. Add overrides method right clickèclick source è click Overrides

e. Click userdetailService()
f.. we need UserDetailService as a objectèuse @Bean before this method

f. This method has to return user name and password.


g. Create list which must be the in-built type of Userdetails

@Configuration
@EnableWebSecurity
public class ApplicationSecurityconfig extends WebSecurityConfigurerAdapter {
@Bean
@Override
protected UserDetailsService userDetailsService() {
List<UserDetails> users=new ArrayList();
users.add()è asking object for user name(default object is user)
password may be plain text or encrypted.now use defaultpassword encoder
Give username and password.

users.add(User.withDefaultPasswordEncoder().username("srimathi").password("viims123").build());

èIt shows withdefaultpasswordencoder() depreciated.we will use some other method.

We can also use some roles within this method.


users.add(User.withDefaultPasswordEncoder().username("srimathi").password("viims123").roles("user").build());

we will add as many users we will add with this method.


Return InmemoryUserDetailManage rè because we will not use any database
ApplicationSecurityConfig.java:
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class ApplicationSecurityconfig extends WebSecurityConfigurerAdapter {
@Bean
@Override
protected UserDetailsService userDetailsService() {
List<UserDetails> users=new ArrayList();

users.add(User.withDefaultPasswordEncoder().username("srimathi").password("viims123").roles("user").build());

return new InMemoryUserDetailsManager(users);


}

èRelaunch the application


c) Username and password verified through database….

Comment all statements. By(ctrl+/)

Fetch username and password from database.


èUse AuthenticationProvider method
èdeclare this method as @Bean
èDAOèData Access Object to access Database. (DAOAuthenticationProvider)
@Bean
public AuthenticationProvider authprovider()
{
DaoAuthenticationProvider provider=new
DaoAuthenticationProvider();
return provider;

èinclude dependency in maven repository


Dependenciesè spring-data-jpa,mysql connectivity
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId></dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>

èconfigure mysql

create database srimathi;


show databases;
use srimathi;
create table user(id int,username varchar(20) ,password varchar(20));
insert into user values(101,"srimathi","sriviims"),(102,"kavipriya","kaviviims");
select * from user;
username: root
password: srimathi
Then go to eclipse:
 in order to connect database do configuration in application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/srimathi
spring.datasource.username=root
spring.datasource.password=srimathi
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

create the model class which will connect database.


User.java:
package com.viimsexample.secure;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class User {
@Id
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

}
èthis will connect the database
Then go to applicationsecurityconfig class
Every provider guide the database
èEvery configuration interact with service layer
DaoAuthenticationProvider provider=new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
create object for predefined class
@Autowired
private UserDetailsService userDetailsSerivce;
èUse Password Encoder
provider.setPasswordEncoder(NoOpPasswordEncoder.getInstance());
Then define userDetailsSerivce class
Create classs calledè MyUserDetailService
And Implements interface userdetailsservice

It will give loadUserByUsername method which will interact with user


Create one more interface ècalled èUserRepository which will extends jparespository
Mention the type as User and id data typeis Integer.
è public interface UserRepository extends JpaRepository<User,Integer>
èit will provide all methods(findall,findone)
ègo back to applicationsecurity
Create UserRepository with annotation (need not instantiate separately)
@Autowired
private UserRepository repo;

 the return type of loadUserByUsername as UserDetails.


 It wants to return UserDetails (but it is interface)

So we have to create the class which will implementUserDetails Interface

Create class UserPrincipal: which implement UserDetails interface.


It will have

èmake is Enabled() as true, isCredentialsNonExpired() as true.

public boolean isAccountNonLocked() {


// TODO Auto-generated method stub
return true;
}

public boolean isCredentialsNonExpired() {


// TODO Auto-generated method stub
return true;
}

public boolean isEnabled() {


// TODO Auto-generated method stub
return true;
}

We need getPassword(),getUsername()return as Object è User object

public class UserPrincipal implements UserDetails {


private User user; è User object created
Create Constructorfor User class

With this user object we will return object in ger getpassword(),getcusername().

public String getPassword() {


// TODO Auto-generated method stub
return user.getPassword();
}

public String getUsername() {


// TODO Auto-generated method stub
return user.getUsername();
}
getAuthorities() è return collection of authorities

public Collection<? extends GrantedAuthority> getAuthorities() {

return Collections.singleton(new SimpleGrantedAuthority("USER"));


}
Now go to MyuserDetailService.java
Return the value as follows:
public class MyUserDetailService implements UserDetailsService {

@Autowired
private UserRepository repo;

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

User user=repo.findByUsername(username);
if(user==null)
{
throw new UsernameNotFoundException("User 404");
}

return new UserPrincipal(user);


}

}
before MyUserDetailService include @service annotation
è @Service
public class MyUserDetailService implements UserDetailsService {
OUTPUT:

Invalid Username user

Valid User name from Database:

Final Output:

Result:

Thus the program executed successfully.


EX NO:7
Spring JPA and Hibernate and Perform Crud & JPQL queries
using Restful API
AIM:

To Design a complex system using JPA and Hibernate. The system should have multiple
entities and relationships between the entities. The database schema should be generated through
Hibernate. Provide RESTful endpoints for CRUD operations for the defined entities. Also, support
pagination and searching using JPA’s JPQL and Criteria API.

ALGORITHM:

REST Http Method:

Algorithm:
A) To return single Data:

Step1: Create restful web services Click maven project

Step2: To implement rest we use jersey so in filter search jersery If not available,
Go window menu click prefereneces

Step3:Go to Maven and check the following two options

Step4: Another way to add jersey


Step5:Create Group id com.sriproj
Artifact id demorest click ok

Jersey maven project everything will be retrieved from internet as follows:

Step6: To set target runtime for our project:


Go to project right click select properties select target runtime as apache 8.0 (then all errors
will go)
Step7:When we run the project the following window will be displayed.

Step8: Click java resource you got output as follows


Step9: Write Basisc of JERSEY:
When we type the click the link:
 @Path("myresource")  Linking (through web.xml sent to servletcontainer)
 @GET  specifies the get request(default all request are get)

@Produces(MediaType.TEXT_PLAIN)

public String getIt() {


return "Got it!";
 }
Step10: Create model project(create the class POJO) Alien.java and we need to display in
xml format so we must specify root element in pojo class ( @XmlRootElement

Alien.java:
package com.sriex.demorest;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Alien {

private String name;


private int points;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}

Step11: Create AlienResource.java and when we send any data we must specify the the format by
@produces
 @Produces(MediaType.APPLICATION_XML) in AlienResource.java

AlienResource.java
package com.sriex.demorest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("aliens")
public class AlienResource {
@GET
@Produces(MediaType.APPLICATION_XML)
public Alien getAlien()
{
System.out.println("getAlien called");
Alien a1=new Alien();
a1.setName("Dr.Srimathi.J");

a1.setPoints(20);
return a1;

}
Step12: Run the project as http://localhost:8082/demorest/webapi/aliens
Step13: Run the project
Output in console:
Output in Browser:

b) To return Multiple Data:

Step13: Return list of alien resource include the statement List<Alien> aliens=Arrays.asList(a1,a2);
Step14: Change AlienResource
AlienResource.java:
package com.sriex.demorest;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("aliens")
public class AlienResource {
@GET
@Produces(MediaType.APPLICATION_XML)
public List<Alien> getAlien()
{
System.out.println("getAlien called");
Alien a1=new Alien();
a1.setName("Dr.Srimathi.J");

a1.setPoints(20);
Alien a2=new Alien();
a2.setName("Dr.John");

a2.setPoints(20);
List<Alien> aliens=Arrays.asList(a1,a2);
return aliens;

}
Step15: Run the project and output will be

c) Create MockRepository

Step16: Send data and Create resource in server use @POST


AlienResource1.java

Result:
Thus the program is executed successfully.
EX NO:8 Spring Restful Application with Spring Data JPA(H2 Database)

AIM:
Create a Spring RESTful Application with Spring Data JPA. Support pagination and
searching using Specifications
ALGORITHM:

step1: Create spring boot project by clicking file newother  click Spring Boot project as follows:

Step2: give group id and artifactid as follows:


Step3 SPRING DATA jpa,spring web,H2 database (in memory database)

Step4: Create com.Telusko.Model package

Step5: Create a POJO CLASS Alien.java under the package com.Telusko.Model


Alien.java:
package com.Telusko.demo.model;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Alien {
@Id
private int aid;
private String aname;
private String tech;

@Override
public String toString() {
return "Alien [aid=" + aid + ", aname=" + aname + ", tech=" + tech +
"]";
}
public String getTech() {
return tech;
}
public void setTech(String tech) {
this.tech = tech;
}
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public String getAname() {
return aname;
}

public void setAname(String aname) {


this.aname = aname;
}

}
Step6: Create Webapp folder under src/main/ as follows

Step7:Create home.jsp under webapp folder

<%@ 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>
<form action="addAlien">
<input type=text name="aid"><br>
<input type=text name="aname"><br>
<input type=text name="atech"><br>
<input type="submit"><br>
</form>
<form action="getAlien">
<input type=text name="aid"><br>
<input type="submit"><br>
</form>
</body>
</html>

Step8: Include the jasper dependency in pom.xml

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.46</version>
</dependency>
Step9:Creation of Controller class  first create the package as
com.Telusko.demo.controller within that create AlienController .java

AlienController.java:
package com.Telusko.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.Telusko.demo.dao.AlienRepo;
import com.Telusko.demo.model.Alien;
@Controller

public class AlienController {


@Autowired
AlienRepo repo;
@RequestMapping("/")
public String home()
{
return ("home.jsp");

@RequestMapping("/addAlien")
public String addAlien(Alien alien)
{
repo.save(alien);
return "home.jsp";
}
@RequestMapping("/getAlien")
public ModelAndView getAlien(@RequestParam int aid)
{
ModelAndView mv=new ModelAndView("showAlien.jsp");
//Alien alien=repo.findById(aid).orElse(null);
Alien alien=repo.findById(aid).orElse(new Alien());
System.out.println(repo.findBytech("java"));
System.out.println(repo.findByAidGreaterThan(1));
mv.addObject(alien);
return mv;
}

}
Step10: launch the project  Right click the project and select run as and click
SprinbootApp and type in browser as
After launching console will display as follows:

Type in browser as http://localhost:8080/ and get output as follows:


Step11: H2 is a inbuilt database so as to enable it we want to configure
application.properties

Write the following code in application.properties:


#enabling the H2 console
spring.h2.console.enabled=true
spring.datasource.platform=/h2
spring.datasource.url=jdbc:h2:mem:sri

Step12: Save and relaunch it

Way to access h2 database: in url type http:/localhost:8080/h2-console


Click test connection

Step13: After test successful click on connect button


Step14: we want to create TABLE for that configure JPA go to model class
Alien.java and metion the annotation @Entity before Alien Class before Variable
declaration mention @Id

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Alien {
@Id
private int aid;
private String aname;
private String tech;
Step15: spring boot will create table for us , relaunch the project then refresh the
h2 console

then click connect


Step16: Now check it out Alien table created like this table is autoconfigured.
Write a query in h2 console query window to check table created and values
available.

Step17: inserting the table values when launching the project itself write data.sql
under the project as follows.
Write the following code in data.sql:

insert into alien values(1,'srimathi','java');


insert into alien values(2,'Abirami','Python');
insert into alien values(3,'Mahalaxmi','Android');
insert into alien values(4,'Hemasri','java');

Step18: Launch the prject and go to h2 console in browser as


http://localhost:8080/h2-console and connect and type the query in h2 console we
will get result as follows:
Step19: We want to write the data into the table through code for that reason create
repository class under a package . so create new package as
com.Telusko.demo.dao and create a repository class as follows:

Step20: create crud operation in Alienrepo and extends with another inerface
import org.springframework.data.repository.CrudRepository;

import com.Telusko.demo.model.Alien;

import java.util.*;

public interface AlienRepo extends CrudRepository<Alien,Integer>{

List<Alien> findBytech(String tech);


List<Alien> findByAidGreaterThan(int aid);
}
Step21: mention table name Alien, Id as ===> integer

Step22: create AlienRepo object in Controller


Step23: create autowired before instance because Alien object need to search
Repository object

Step24: write the save code in Alien repo.save(alien)


Step25: relaunch and run the project and type in the browser as follows:
http://localhost:8080/addAlien?aid=4&aname=Gayathri&tech=java
Step 26: Check with h2 console by typing in URL http://localhost:8080/h2-
console/

Step 27: create getAlien form tag inside home.jsp


Step 28: create controller to accept getAlien request from user go to
AlienController class
==>aid inside the getAlien() method
==> user @RequestParam annotation inside the method to fetch value from user
==>create separate jsp to view requested aid's data as showAlien.jsp

Step29: send the detail to showAlien.jsp so use modelAndViewin


getAlien()method
Step 30: create instance for ModelAndView and pass jsp as constructor (another
way)

Step31: fetch the data using aid


Step32: findbyid() is integer so change the parameter as integer
Step33: showAlien.jsp page include ${alien } to display value on screen

relaunch it and we will check it out its working


Output:

=============================================
H2query method Write customized query
System.out.println(repo.findBytech("java"));

Result:

This Program executed successfully.


EX NO:9 Build React Application with components and components

AIM:
Create a React application with different components and interactions between the
components.
ALGORITHM:

Step1: Create the class namedEmployee


Step2:Create Constructor with 2 arguments as id and name
Step3:Create detail() Method to display employee id and employee name
Step4:Create Object for Employee Class as e1 and e2
Step5:Write IndexedDB code and create the database named sriviims
Step6: Create Constant type array in the name of employeeData
Step7:Add the Value of Constant array with Database in Browser
Step8: Display the Output
Sourcecode:
<!DOCTYPE html>
<html>
<body>

<script>
//Declaring class

class Employee
{

//Initializing an object
constructor(id,name)
{
this.id=id;
this.name=name;
}

//Declaring method

detail()
{
document.writeln("&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Employee id :"+ this.id+"
"+", Employee name:"+ this.name+" <br>");
}
}

//passing object to a variable

var e1=new Employee(101,"Dr.Srimathi");

var e2=new Employee(102,"Nivedha.J");

window.indexedDB = window.indexedDB || window.mozIndexedDB ||


window.webkitIndexedDB || window.msIndexedDB;

//prefixes of window.IDB objects


window.IDBTransaction = window.IDBTransaction ||
window.webkitIDBTransaction || window.msIDBTransaction;

window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange ||


window.msIDBKeyRange

if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.")
}
var db;
var request = window.indexedDB.open("sriviims", 1);
request.onerror = function(event) {
console.log("error: ");
};

request.onsuccess = function(event) {
db = request.result;
console.log("success: "+ db);
};

request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("employee", {keyPath: "id"});
const employeeData = [
{ id: e1.id, name: e1.name },
{ id: e2.id, name: e2.name}
];
for (var i in employeeData) {
objectStore.add(employeeData[i]);
alert("added");
}
}
document.writeln("&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;");
document.writeln(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br>");
document.writeln("&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp;");
document.writeln(" <b> Employee Details <br>");
document.writeln("&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;");
document.writeln(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br>");
e1.detail(); //calling method
e2.detail();
document.writeln("<br><b>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
Successfully added in indexed db...... ");
</script>

</body>
</html>

OUTPUT:
To check whether the value is added in indexeddb in browser goto
Dev tools click applications click indexeddb option and verify srivvims db has created and
record inserted.
Result:

This Program executed successfully.


EX NO:10 Build a Full-Stack Application with React and Spring

AIM:
To develop a full-stack application with different components React and Spring. Make
use of Spring REST, Spring Security, Spring Data JPA, Hibernate, Spring Boot, Gradle
and ReactJS state and component mechanism.
ALGORITHM:

Step 1: Set up a Spring Boot Project

Ensure you have Spring Boot installed, or use a build tool like Gradle to manage dependencies.

plugins {

id 'org.springframework.boot' version '2.5.0'

id 'io.spring.dependency-management' version '1.0.11.RELEASE'

id 'java'

group = 'com.example'

version = '0.0.1-SNAPSHOT'

sourceCompatibility = '11'

repositories {

mavenCentral()

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

implementation 'org.springframework.boot:spring-boot-starter-security'

implementation 'org.springframework.boot:spring-boot-starter-web'

runtimeOnly 'com.h2database:h2' // In-memory database for demo purposes

testImplementation 'org.springframework.boot:spring-boot-starter-test'

application.properties (configure database and security):

spring.datasource.url=jdbc:h2:mem:testdb

spring.datasource.driverClassName=org.h2.Driver

spring.datasource.username=sa

spring.datasource.password=password

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.h2.console.enabled=true

# Spring Security

spring.security.user.name=admin

spring.security.user.password=adminpassword

spring.security.user.roles=ROLE_USER

Step 2: Define Entity and Repository


1. Item.java (Entity class using JPA annotations):
package com.example.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Item {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;


private double price;
// getters and setters

public Long getId() {


return id;
}

public void setId(Long id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


this.price = price;
}
}
2. ItemRepository.java (Spring Data JPA repository):

package com.example.demo.repository;

import com.example.demo.model.Item;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ItemRepository extends JpaRepository<Item, Long> {
}

Step 3: Create REST Controller

1. ItemController.java (REST controller using Spring MVC):

package com.example.demo.controller;

import com.example.demo.model.Item;

import com.example.demo.repository.ItemRepository;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController

@RequestMapping("/api/items")

public class ItemController {

@Autowired

private ItemRepository itemRepository;

@GetMapping

public List<Item> getAllItems() {

return itemRepository.findAll();

@GetMapping("/{id}")

public ResponseEntity<Item> getItemById(@PathVariable Long id) {

Item item = itemRepository.findById(id)

.orElseThrow(() -> new RuntimeException("Item not found with id: " + id));

return ResponseEntity.ok(item);

@PostMapping

public ResponseEntity<Item> createItem(@RequestBody Item item) {


Item savedItem = itemRepository.save(item);

return ResponseEntity.status(HttpStatus.CREATED).body(savedItem);

@PutMapping("/{id}")

public ResponseEntity<Item> updateItem(@PathVariable Long id, @RequestBody Item


itemDetails) {

Item item = itemRepository.findById(id)

.orElseThrow(() -> new RuntimeException("Item not found with id: " + id));

item.setName(itemDetails.getName());

item.setPrice(itemDetails.getPrice());

Item updatedItem = itemRepository.save(item);

return ResponseEntity.ok(updatedItem);

@DeleteMapping("/{id}")

public ResponseEntity<Void> deleteItem(@PathVariable Long id) {

Item item = itemRepository.findById(id)

.orElseThrow(() -> new RuntimeException("Item not found with id: " + id));

itemRepository.delete(item);

return ResponseEntity.noContent().build();

}
Step 4: Spring Security Configuration (Optional)

Configure Spring Security for authentication and authorization as needed. Example


configurations can be added in a separate class annotated with @Configuration.

Frontend (ReactJS)

Step 5: Set up React Project

Ensure you have Node.js and npm (or yarn) installed for managing frontend dependencies.

1. Create React App:

npx create-react-app frontend

cd frontend

Step 6: Implement React Components

1. Item.js (Component for listing items):

import React, { useEffect, useState } from 'react';

import axios from 'axios';

const Item = () => {

const [items, setItems] = useState([]);

const [name, setName] = useState('');

const [price, setPrice] = useState(0);

useEffect(() => {

fetchItems();

}, []);

const fetchItems = () => {


axios.get('/api/items')

.then(response => setItems(response.data))

.catch(error => console.error('Error fetching items: ', error));

};

const handleCreateItem = () => {

const newItem = { name, price };

axios.post('/api/items', newItem)

.then(response => {

fetchItems();

setName('');

setPrice(0);

})

.catch(error => console.error('Error creating item: ', error));

};

const handleDeleteItem = (id) => {

axios.delete(`/api/items/${id}`)

.then(response => {

fetchItems();

})

.catch(error => console.error('Error deleting item: ', error));

};
return (

<div>

<h1>Items</h1>

<div>

<label>Name:</label>

<input type="text" value={name} onChange={e => setName(e.target.value)} />

</div>

<div>

<label>Price:</label>

<input type="number" value={price} onChange={e => setPrice(e.target.value)} />

</div>

<button onClick={handleCreateItem}>Add Item</button>

<ul>

{items.map(item => (

<li key={item.id}>

{item.name} - ${item.price}

<button onClick={() => handleDeleteItem(item.id)}>Delete</button>

</li>

))}

</ul>

</div>
);

};

export default Item;

2. App.js (Main component for routing):

import React from 'react';

import './App.css';

import Item from './Item';

function App() {

return (

<div className="App">

<Item />

</div>

);

export default App;


OUTPUT:

RESULT:

Thus the program executed successfully.

You might also like