Advanced Java Programming Lab
Advanced Java Programming Lab
(AUTONOMOUS)
SECOND SEMESTER
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
Done by :
Register No:
1
22/03/2024 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
</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();
list();
}
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>'
}
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
AIM:
Create a javascript application in an Object Oriented way using Classes and Modules. It
should also use browser storage for persistence.
ALGORITHM:
<script>
//Declaring class
class Employee
{
//Initializing an object
constructor(id,name)
{
this.id=id;
this.name=name;
}
//Declaring method
detail()
{
document.writeln(" Employee id :"+ this.id+"
"+", Employee name:"+ this.name+" <br>");
}
}
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(" ");
document.writeln(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br>");
document.writeln("
");
document.writeln(" <b> Employee Details <br>");
document.writeln(" ");
document.writeln(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br>");
e1.detail(); //calling method
e2.detail();
document.writeln("<br><b>
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:
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:
/*
* 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
*/
// 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'
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:
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
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 :
AIM:
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:
<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,
<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 -->
</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
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 {
@RequestMapping(method = RequestMethod.POST)
public String handleFileUpload(HttpServletRequest request,
@RequestParam CommonsMultipartFile[] fileUpload) throws Exception {
if (!aFile.getOriginalFilename().equals("")) {
aFile.transferTo(new File(saveDirectory + aFile.getOriginalFilename()));
}
}
}
@RequestMapping:
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:
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)
</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>
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
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
@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());
@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());
èconfigure mysql
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
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
@Autowired
private UserRepository repo;
User user=repo.findByUsername(username);
if(user==null)
{
throw new UsernameNotFoundException("User 404");
}
}
before MyUserDetailService include @service annotation
è @Service
public class MyUserDetailService implements UserDetailsService {
OUTPUT:
Final Output:
Result:
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:
Algorithm:
A) To return single Data:
Step2: To implement rest we use jersey so in filter search jersery If not available,
Go window menu click prefereneces
@Produces(MediaType.TEXT_PLAIN)
Alien.java:
package com.sriex.demorest;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Alien {
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:
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
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 newother click Spring Boot project as follows:
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;
}
}
Step6: Create Webapp folder under src/main/ as follows
<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
@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:
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
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:
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.*;
=============================================
H2query method Write customized query
System.out.println(repo.findBytech("java"));
Result:
AIM:
Create a React application with different components and interactions between the
components.
ALGORITHM:
<script>
//Declaring class
class Employee
{
//Initializing an object
constructor(id,name)
{
this.id=id;
this.name=name;
}
//Declaring method
detail()
{
document.writeln(" Employee id :"+ this.id+"
"+", Employee name:"+ this.name+" <br>");
}
}
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(" ");
document.writeln(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br>");
document.writeln("
");
document.writeln(" <b> Employee Details <br>");
document.writeln(" ");
document.writeln(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br>");
e1.detail(); //calling method
e2.detail();
document.writeln("<br><b>
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:
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:
Ensure you have Spring Boot installed, or use a build tool like Gradle to manage dependencies.
plugins {
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'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
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
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;
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> {
}
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")
@Autowired
@GetMapping
return itemRepository.findAll();
@GetMapping("/{id}")
.orElseThrow(() -> new RuntimeException("Item not found with id: " + id));
return ResponseEntity.ok(item);
@PostMapping
return ResponseEntity.status(HttpStatus.CREATED).body(savedItem);
@PutMapping("/{id}")
.orElseThrow(() -> new RuntimeException("Item not found with id: " + id));
item.setName(itemDetails.getName());
item.setPrice(itemDetails.getPrice());
return ResponseEntity.ok(updatedItem);
@DeleteMapping("/{id}")
.orElseThrow(() -> new RuntimeException("Item not found with id: " + id));
itemRepository.delete(item);
return ResponseEntity.noContent().build();
}
Step 4: Spring Security Configuration (Optional)
Frontend (ReactJS)
Ensure you have Node.js and npm (or yarn) installed for managing frontend dependencies.
cd frontend
useEffect(() => {
fetchItems();
}, []);
};
axios.post('/api/items', newItem)
.then(response => {
fetchItems();
setName('');
setPrice(0);
})
};
axios.delete(`/api/items/${id}`)
.then(response => {
fetchItems();
})
};
return (
<div>
<h1>Items</h1>
<div>
<label>Name:</label>
</div>
<div>
<label>Price:</label>
</div>
<ul>
{items.map(item => (
<li key={item.id}>
{item.name} - ${item.price}
</li>
))}
</ul>
</div>
);
};
import './App.css';
function App() {
return (
<div className="App">
<Item />
</div>
);
RESULT: