0% found this document useful (0 votes)
7 views210 pages

Advance Java Notes

The document provides a comprehensive tutorial on Servlet technology for creating web applications using Java. It covers the advantages of Servlets over CGI, setup instructions for Apache Tomcat and Eclipse, and includes code examples for various functionalities such as addition, factorial calculations, and session management. Additionally, it explains the differences between sessions and cookies, along with practical implementations of each.

Uploaded by

mayuripatil6695
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)
7 views210 pages

Advance Java Notes

The document provides a comprehensive tutorial on Servlet technology for creating web applications using Java. It covers the advantages of Servlets over CGI, setup instructions for Apache Tomcat and Eclipse, and includes code examples for various functionalities such as addition, factorial calculations, and session management. Additionally, it explains the differences between sessions and cookies, along with practical implementations of each.

Uploaded by

mayuripatil6695
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

Servlet Tutorial

Servlet technology is used to create a web application (resides at server side and
generates a dynamic web page).

Servlet technology is robust and scalable because of java language. Before Servlet,
CGI (Common Gateway Interface) scripting language was common as a server-side
programming language. However, there were many disadvantages to this technology.
We have discussed these disadvantages below.

There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.

What is a Servlet?
Servlet can be described in many ways, depending on the context.

o Servlet is a technology which is used to create a web application.


o Servlet is an API that provides many interfaces and classes including documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic web
page.
What is a web application?
A web application is an application accessible from the web. A web application is
composed of web components like Servlet, JSP, Filter, etc. and other elements such as
HTML, CSS, and JavaScript. The web components typically execute in Web Server and
respond to the HTTP request.

Advantages of Servlet

There are many advantages of Servlet over CGI. The web container creates threads for
handling the multiple requests to the Servlet. Threads have many benefits over the
Processes such as they share a common memory area, lightweight, cost of
communication between the threads are low. The advantages of Servlet are as follows:

1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection, etc.
4. Secure: because it uses java language.

***********************************SetUp****************************************

Required Software:

➢ Apache Tomcat 10.1.25 version


➢ Eclipse for Enterprise Edition (Check that Maven and Dynamic project available)

Create New Project: File>New>Dynamic Project>Name it>Next


Tick on the box>Finish

On the Project Explorer Your Project name with all the sub files should be present
Set Java JRE as default
Right Click on Project>Build Path>Configure Build path
Libraries>JRE System library>Edit

Select the Workspace default JRE>Finish


Set The Server
Window>Show View>Servers

Click on the link to create new server


On Server Type expand Tomcat cat under that>select Tomcat v10.1 server>next

Browse and Select the Apache Tomcat up zipped folder.


(Optional step if you have not downloaded the apache tomcat )

Download and Install> Accept the license> Finish


Select on Add all

Finish
The Server pop up window should open and display this.

Now the project structure should be like this.


First Program

Right click on webapp>New>Html file>add name>finish

Write a simple Html code.


After writing the code right click>run as>run on server

Select tomcat >finish

On the web localhost the program will run.


Note :

Create a package in

Src – main- java – as – [Link]

1.

[Link] in webapp folder


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- <form action="route" in [Link]></form> -->
<form action="add" method="POST">
<label>Enter 1 Number :</label>
<input type="text" name="n1"><br><br>
<label>Enter 2 Number :</label>
<input type="text" name="n2"><br><br>
<input type="submit" value="Add">

</form>
</body>
</html>

[Link]
package [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class Add extends HttpServlet{

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out=[Link]();

[Link]("Addition is :");
int n1=[Link]([Link]("n1"));
int n2=[Link]([Link]("n2"));
int sum=n1+n2;

[Link]("Addition is :"+sum);

[Link] – do registeration

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="[Link]
xmlns="[Link]
xsi:schemaLocation="[Link]
[Link] id="WebApp_ID" version="5.0">
<display-name>DemoApp</display-name>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>addition</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>addition</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
2. Factorial

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="fact" method="POST">
<label>Enter Number:</label>
<input type="text" name="n1"><br><br>
<input type="submit" value=Calculate Factorial>

</form>
</body>
</html>

[Link]

package [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class Factorial extends HttpServlet{

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out=[Link]();
int fact=1,i;
[Link]("<h1>Hello Welcome </h1>");
int n1=[Link]([Link]("n1"));
for(i=1;i<=n1;i++)
{
fact=fact*i;
}

[Link]("Factorial is :"+fact);
}

[Link]
<servlet>
<servlet-name>factorial</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>factorial</servlet-name>
<url-pattern>/fact</url-pattern>

RequestDispatcher(calling servlet to servlet)

.html – servlet file – second servlet file

It is a method to call one servlet from other servlet

• RequestDispatcher( call servlet to another servlet)


.html ->servlet file ->second servlet file
• Sendredirect: to fetch the current route and redirect to current route.
• Senddirect(Session Management)-
[Link] Session (store data on server side)
[Link] (store data on client side)
[Link] form (when we write html in java and the type is hidden)
[Link] Annotation (no need for registering on xml )

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="reqdis1" method="GET">
<label>Enter 1 Number :</label>
<input type="text" name="n1"><br><br>
<label>Enter 2 Number :</label>
<input type="text" name="n2"><br><br>
<input type="submit" value="Add">
</form>
</body>
</html>

[Link]
package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class RequestDispatchet1 extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
{
int a = [Link]( [Link]("n1"));
int b = [Link]( [Link]("n2"));

int Sum = a+b;

[Link]("sum" , Sum);

//route forn second servlet from [Link] file


RequestDispatcher rd = [Link]("reqdis2");
[Link](req, res);
}

[Link]
package [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class RequestDispatcher2 extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws


IOException, ServletException
{
int k = (int) [Link]("sum");
int sq = k*k;
PrintWriter out = [Link]();
[Link]("square = "+ sq);

RequestDispatcher rd=
[Link]("[Link]");
[Link](req, res);
//include - to add /give route to specific servlet

[Link]
<servlet>
<servlet-name>requestdispatcher2</servlet-name>
<servlet-class>[Link].RequestDispatcher2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>requestdispatcher2</servlet-name>
<url-pattern>/reqdis2</url-pattern>
</servlet-mapping>

Sendredirect : to fetch the current route and redirect to current route

.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="sendredirect1" method="GET">
<label>Enter 1 Number :</label>
<input type="text" name="n1"><br><br>
<label>Enter 2 Number :</label>
<input type="text" name="n2"><br><br>
<input type="submit" value="Add">
</form>
</body>
</html>

Senddirect1
package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class Sendredirect1 extends HttpServlet{

public void doGet(HttpServletRequest req, HttpServletResponse res) throws


IOException, ServletException
{
int a = [Link]( [Link]("n1"));
int b = [Link]( [Link]("n2"));

int Sum = a+b;


//xmlfileroute?query parameter -- kindly check the url of an program
[Link]("sendredirect2?sum="+Sum);

[Link]
package [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class Sendredirect2 extends HttpServlet{

public void doGet(HttpServletRequest req, HttpServletResponse res) throws


IOException, ServletException
{
int sum=[Link]([Link]("sum"));
int sq = sum*sum;

[Link]("text/html");
PrintWriter out = [Link]();

[Link]("square = "+ sq);

}
[Link]
<servlet>
<servlet-name>sendredirect2</servlet-name>
<servlet-class>[Link].Sendredirect2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sendredirect2</servlet-name>
<url-pattern>/sendredirect2</url-pattern>
</servlet-mapping>

Difference Between Session and Cookies


Cookies Session

Cookies are client-side files on a


Sessions are server-side files that contain user
local computer that hold user
data.
information.

Cookies end on the lifetime set When the user quits the browser or logs out of
by the user. the programmed, the session is over.

It can only store a certain


It can hold an indefinite quantity of data.
amount of info.

We can keep as much data as we like within a


The browser’s cookies have a session, however there is a maximum memory
maximum capacity of 4 KB. restriction of 128 MB that a script may
consume at one time.

Because cookies are kept on the


To begin the session, we must use the session
local computer, we don’t need to
start() method.
run a function to start them.

Session are more secured compare than


Cookies are not secured.
cookies.
Cookies Session

Cookies stored data in text file. Session save data in encrypted form.

Cookies stored on a limited data. Session stored a unlimited data.

In PHP, to get the data from


In PHP , to get the data from Session,
Cookies , $_COOKIES the global
$_SESSION the global variable is used
variable is used

In PHP, to destroy or remove the data stored


We can set an expiration date to
within a session, we can use the
delete the cookie’s data. It will
session_destroy() function, and to unset a
automatically delete the data at
specific variable, we can use the unset()
that specific time.
function.

Senddirect (Session Management) – 1. HttpSession [Link] [Link]

1. HttpSession

.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="httpsession1" method="GET">
<label>Enter 1 Number :</label>
<input type="text" name="n1"><br><br>
<label>Enter 2 Number :</label>
<input type="text" name="n2"><br><br>
<input type="submit" value="Add">
</form>
</body>
</html>

[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class HttpSession1 extends HttpServlet{

public void doGet(HttpServletRequest req, HttpServletResponse res) throws


IOException, ServletException
{
int a = [Link]( [Link]("n1"));
int b = [Link]( [Link]("n2"));

int Sum = a+b;

HttpSession session=[Link]();
[Link]("sum",Sum);
//redirection variable,storing
variable
[Link]("httpsession2");
}
}

[Link]
package [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class HttpSession2 extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
{
HttpSession session=[Link]();
int sum=(int)([Link]("sum"));
int sq = sum*sum;

[Link]("text/html");
PrintWriter out = [Link]();

[Link]("square = "+ sq);

}
[Link]
<servlet>
<servlet-name>httpsession</servlet-name>
<servlet-class>[Link].HttpSession1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>httpsession</servlet-name>
<url-pattern>/httpsession1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>httpsession2</servlet-name>
<servlet-class>[Link].HttpSession2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>httpsession2</servlet-name>
<url-pattern>/httpsession2</url-pattern>
</servlet-mapping>

2. Cookie

.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="cookie1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

</body>
</html>

[Link]
package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class Cookie1 extends HttpServlet{

public void doPost(HttpServletRequest request, HttpServletResponse


response){
try{

[Link]("text/html");
PrintWriter out = [Link]();

String n=[Link]("userName");
[Link]("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie object


[Link](ck);//adding cookie in the response

[Link]("cookie2");

[Link]();

}catch(Exception e){[Link](e);}
}

[Link]
package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class Cookie2 extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse


response){
try{

[Link]("text/html");
PrintWriter out = [Link]();

Cookie ck[]=[Link]();
for(Cookie c:ck)
{
if([Link]().equals("uname"))
{
[Link]("Hello "+[Link]());
}
}

[Link]();

}catch(Exception e){[Link](e);}
}

}
[Link]
<servlet>
<servlet-name>cookie1</servlet-name>
<servlet-class>[Link].Cookie1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cookie1</servlet-name>
<url-pattern>/cookie1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>cookie2</servlet-name>
<servlet-class>[Link].Cookie2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cookie2</servlet-name>
<url-pattern>/cookie2</url-pattern>
</servlet-mapping>

3. Hidden Form

.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="hiddenform1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

</body>
</html>

[Link]
package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class HiddenForm1 extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse


response){
try{
[Link]("text/html");
PrintWriter out = [Link]();

String n=[Link]("userName");
[Link]("Welcome "+n);

//creating submit button


[Link]("<form action='hiddenform2'>");
[Link]("<input type='hidden' name='username'
value='"+n+"'>");
[Link]("<input type='submit' value='go'>");
[Link]("</form>");

[Link]();

}catch(Exception e){[Link](e);}
}
}

[Link]
package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class HiddenForm2 extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse


response){
try{

[Link]("text/html");
PrintWriter out = [Link]();

String n=[Link]("username");
[Link]("Hello "+n+"in second form");

[Link]();

}catch(Exception e){[Link](e);}
}
}

.xml
<servlet>
<servlet-name>hiddenform1</servlet-name>
<servlet-class>[Link].HiddenForm1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hiddenform1</servlet-name>
<url-pattern>/hiddenform1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>hiddenform2</servlet-name>
<servlet-class>[Link].HiddenForm2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hiddenform2</servlet-name>
<url-pattern>/hiddenform2</url-pattern>
</servlet-mapping>

Servlet config and servlet context are written in xml file where you can send value with parameter

Servletconfig – written for specific servlet (private)

Servletcontext – written for overall servlet (shareable)

Both are applied in same file

.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="contextparam">
<input type="submit" value="check">
</form>
</body>
</html>

.java
package [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class ContextParam extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException{

[Link]("text/html");
PrintWriter out = [Link]();

//1 global
ServletContext ctx=getServletContext();
String name=[Link]("name");
[Link](name);

//2. private
ServletConfig ct=getServletConfig();
String n=[Link]("n");
[Link](n);

}
}

.xml
<servlet>
<servlet-name>contextparam</servlet-name>
<servlet-class>[Link]</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>Spark</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>contextparam</servlet-name>
<url-pattern>/contextparam</url-pattern>
</servlet-mapping>
<context-param>
<param-name>name</param-name>
<param-value>KArtiki</param-value>
</context-param>

Servlet Annotation :

Adv : no need to write the xml file

.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body><form action="servletannotation">
<input type="submit" value="check">
</form>

</body>
</html>

.java file
package [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/servletannotation")
public class Servletannotation extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws IOException{

[Link]("text/html");
PrintWriter out = [Link]();
[Link]("Welcome to Servlet Annotations");

}
}

What is JavaServer Page (JSP)?


JSP technology is used to create web applications just like Servlet technology. It can
be thought of as an extension to Servlet because it provides more functionality than
servlet such as expression language, JSTL, etc.

JSP helps developers insert Java code in HTML pages by making use of special JSP
tags, most of which start with <% and end with %>.

A JavaServer Pages component is a type of Java servlet that is designed to fulfill the
role of a user interface for a Java web application. Web developers write JSPs as text
files that combine HTML or XHTML code, XML elements, and embedded JSP actions
and commands.
Using JSP, you can collect input from users through Webpage forms, present records
from a database or another source, and create Web pages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing
control between pages, and sharing information between requests, pages, etc.

What is a JSP File?


JavaServer Page (JSP) file is a template for a Web page that uses Java code
to generate an HTML document dynamically. JSPs are run in a server-
side component known as a JSP container, which translates them into equivalent Java
servlets.

Well, a JSP file is simply an HTML page with some Java code sprinkled in and it
basically gives you dynamic content that you can include on your page.

The below diagram shows a simple JSP structure - It has some HTML code, some
Java code, you can make some more HTML code, and so on.

The end result is that you'll have an HTML page with content that's generated by
some Java code.

Where is the JSP Processed?


• JSP file is actually processed on the server. For example, JSP files can be
processed on a web server or application servers like tomcat server or
Glassfish or JBoss, etc.
• Finally, when JSP file processing is completed, the result of the Java code is
actually included in the HTML returned to the browser.
Look at the above diagram, we have a web browser, we make a request for a JSP
page, it goes across, the JSP pages processed by a server and then the results of that
Java code will generate HTML and that those results will actually return back to the
web browser. Finally, the web browser will display the HTML page.

Advantages of JSP
JSP pages have all the advantages of servlets:

• They have better performance and scalability than CGI scripts because they
are persistent in memory and multithreaded.
• No special client setup is required.
• They have built-in support for HTTP sessions, which makes application
programming possible.
• They have full access to Java technology–network awareness, threads, and
database connectivity—without the limitations of client-side applets.

But, in addition, JSP pages have advantages of their own:

• They are automatically recompiled when necessary.


• Because they exist in the ordinary Web server document space, addressing JSP
pages is simpler than addressing servlets.
• Because JSP pages are HTML-like, they have greater compatibility with Web
development tools.
JavaServer page (JSP) is a template for a Web page that uses Java code to generate an
HTML document dynamically. JSPs are run in a server-side component known as a JSP
container, which translates them into equivalent Java servlets. For this reason, servlets and
JSP pages are intimately related.

How JSP Works

A JSP page exists in three forms:

• JSP source code - This is the form the developer actually writes. It exists in a text file
with an extension of .jsp, and consists of a mix of HTML template code, Java
language statements, and JSP directives and actions that describe how to generate a
Web page to service a particular request.
• Java source code - The JSP container translates the JSP source code into the source
code for an equivalent Java servlet as needed. This source code is typically saved in a
work area and is often helpful for debugging.
• Compiled Java class - Like any other Java class, the generated servlet code is
compiled into bytecodes in a .class file, ready to be loaded and executed.

How the container process JSP page?


The JSP container manages each of these forms of the JSP page automatically, based on the
timestamps of each file. In response to an HTTP request, the container checks to see if
the .jsp source file has been modified since the .java source was last compiled. If so, the
container retranslates the JSP source into Java source and recompiles it.
The above diagram illustrates the process used by the JSP container. When a request for a
JSP page is made, the container first determines the name of the class corresponding to
the .jsp file. If the class doesn’t exist or if it’s older than the .jsp file (meaning the JSP
source has changed since it was last compiled), then the container creates Java source code
for an equivalent servlet and compiles it. If an instance of the servlet isn’t already running,
the container loads the servlet class and creates an instance. Finally, the container dispatches
a thread to handle the current HTTP request in the loaded instance.

The scripting elements provide the ability to insert Java code inside the JSP.

In JSP, there are actually different types of scripting elements.

1. JSP expressions
2. JSP scriptlets
3. JSP declarations
Now, we'll actually have a deep dive on each one of these topics in the separate article but I
wanted to give you just an overview real quick.

Below diagram shows the summary of using these scripting elements:

Let's discuss each scripting element with their syntax and examples.

1. JSP expressions

We use JSP expressions to compute some type of expression and the result of that is
included in the HTML page that's returned to the browser.

Expression tag evaluates the expression placed in it, converts the result into String and send
the result back to the client through response implicit object.
The Syntax of JSP Expression Tag

<%= expression %>

JSP Expression Tag Examples


Here is sample snippet which basically converts this string to all caps or to all upper case.

<html>
<body>
Converting a string to uppercase:
<%=new String("Hello World").toUpperCase()%>
</body>
</html>

2. JSP scriptlets

A scriptlet is a set of Java programming statements embedded in an HTML page. The


statements are distinguished from their surrounding HTML by being placed between <% and
%> markers, as the following shows:

<% statement; [statement; …] %>

Example of JSP scriptlet tag

In this example, we are displaying a HelloWorld message.


```jsp
<html>
<body>
<% [Link]("HelloWorld"); %>
</body>
</html>

3. JSP declarations

JSP declarations basically allow you to declare a method in the JSP page, and then you can
call them from the same JSP page.

So it's very useful like any normal code that you create. If you need to execute some code
over and over again, you simply encapsulate it in a method declaration.
The Syntax of JSP Declaration Tag

<%! Declaration %>

JSP Declaration Tag Example


In this example of JSP declaration tag, we are defining the method which returns the cube of
a given number and calling this method from the JSP expression tag. But we can also use JSP
scriptlet tag to call the declared method.

<html>
<body>
<%!
int cube(int n){
return n * n * n;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
1. [Link]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
<form action="[Link]" method="post">
<input type="text" name="number" />
<input type="submit" name="submit" />
</form>
</body>
</html>

[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<!-- Decalartion tag-->


<%!

String printNum(char num) {


switch(num){
case '1':
return "one";
case '2':
return "two";
case '3':
return "three";
case '4':
return "four";
case '5':
return "five";
case '6':
return "six";
case '7':
return "seven";
case '8':
return "eight";
case '9':
return "nine";
case '0':
return "zero";
default:
return "";
}
}
%>
<%
//request is implicit object
String num =
[Link]("number");

int len = [Link]();


for(int i=0; i<len; i++){
[Link]("<strong style='font-
size:50px'>" + printNum([Link](i)) +
"</strong>");
}
%>

</body>
</html>
Post method :

Get method:

Jsp : Get method can be handle simulataneously

2. [Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- <form action="route" in [Link]></form> -->
<form action="[Link]" method="POST">
<label>Enter 1 Number :</label>
<input type="text" name="n1"><br><br>
<label>Enter 2 Number :</label>
<input type="text" name="n2"><br><br>
<input type="submit" value="Add">

</form>
</body>
</html>
[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
int
n1=[Link]([Link]("n1"));
int
n2=[Link]([Link]("n2"));
int sum=n1+n2;
[Link]("Addition is :"+sum);
%>

</body>
</html>

[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1>Current Date and Time</h1>


<p>
<%
[Link] date = new
[Link]();
[Link]([Link]());
%>
</p>
</body>
</html>

4. [Link]

<html>
<head>
<title>User Input Form</title>
</head>
<body>
<h1>User Input Form</h1>
<form method="post" action="[Link]">
Enter your name: <input type="text"
name="username" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Greeting</h1>
<p>
Hello,
<%
String username =
[Link]("username");
if (username != null &&
![Link]().isEmpty()) {
[Link](username);
} else {
[Link]("Guest");
}
%>!
</p>
</body>
</html>
5. [Link]

<html>
<head>
<title>Login Form</title>
</head>
<body>
<h1>Login Form</h1>
<form method="post" action="[Link]">
Username: <input type="text"
name="username" /><br/>
Password: <input type="password"
name="password" /><br/>
<input type="submit" value="Login" />
</form>
</body>
</html>

[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome Page</h1>
<%
String username =
[Link]("username");
String password =
[Link]("password");
if ("admin".equals(username) &&
"admin@123".equals(password)) {
[Link]("Welcome, " + username +
"!");
} else {
[Link]("Invalid username or
password.");
}
%>
</body>
</html>

6. [Link]

<%-- [Link] --%>


<html>
<head>
<title>Request Headers</title>
</head>
<body>
<h1>Request Headers</h1>
<table border="1">
<tr>
<th>Header Name</th>
<th>Header Value</th>
</tr>
<%
[Link]<String>
headerNames = [Link]();
while ([Link]()) {
String headerName =
[Link]();
String headerValue =
[Link](headerName);
%>
<tr>
<td><%= headerName %></td>
<td><%= headerValue %></td>
</tr>
<%
}
%>
</table>
</body>
</html>

[Link]

<%-- [Link] --%>


<html>
<head>
<title>Client Information</title>
</head>
<body>
<h1>Client Information</h1>
<p>IP Address: <%= [Link]()
%></p>
<p>Client Host: <%= [Link]()
%></p>
<p>Client Browser: <%= [Link]("User-
Agent") %></p>
</body>
</html>

[Link]

<%-- [Link] --%>


<html>
<head>
<title>Page Counter</title>
</head>
<body>
<h1>Page Counter</h1>
<%
Integer counter = (Integer)
[Link]("counter");
if (counter == null) {
counter = 1;
} else {
counter++;
}
[Link]("counter", counter);
%>
<p>This page has been accessed <%= counter %>
times in this session.</p>
</body>
</html>

[Link]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form id="myform" action="[Link]"
method="POST">
<table>

<tr>
<td>Enter number one</td>
<td><input type="text"
name="n1"></td>
</tr>

<tr>
<td>Enter number two</td>
<td><input type="text"
name="n2"></td>
</tr>
<tr>
<td><input type="submit"
value="add" name="btn"></td>
<td><input type="submit"
value="sub" name="btn"></td>
<td><input type="submit"
value="mul" name="btn"></td>
<td><input type="submit"
value="div" name="btn"></td>
</tr>
</table>
</form>
</body>
</html>

[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
int n1 =
[Link]([Link]("n1"));
int n2 =
[Link]([Link]("n2"));
String btn = [Link]("btn");
float result=0;

if([Link]("add")) {
result = n1+n2;
} else if([Link]("sub")) {
result = n1-n2;
}else if([Link]("mul")) {
result = n1*n2;
}else if([Link]("div")) {
result = (float)n1/n2;
}

//RequestDispatcher rd =
[Link]("[Link]").inc
lude(request,response);
//[Link](request, response);
[Link]("result = "+ result);
//[Link]("[Link]").i
nclude(request,response);

%>
</body>
</html>

JSP Directives – The jsp directives are message that tells the web container
how to translate a jsp page into the corresponding servlet.
1. Page directive
2. Include directive
3. Taglib directive
Syntax- <%@ directive attribute=”value”%>
Attributes:
1. IsError page
2. Language
3. contentType
4. Session
5. EL(Expression language)
It simplifies the accessibility of data stored in the java bean component,
and other object like session, operators and reserve words in EL.
It only works on JSP 2.0
Syntax:${expression}
Examples:
pageScope,requestScope,sessionScope,applicationScope,param,
paramValue, header, headerValue, cookie

Page Directive
There are several attributes, which are used along with Page Directives
and these are
❖ import
❖ session
❖ isErrorPage
❖ errorPage
❖ ContentType
❖ isThreadSafe
❖ extends
❖ info
❖ language
❖ autoflush
❖ Buffer

JSP Implicit Objects


Implicit Description
Object
request The HttpServletRequest object associated with the request.

response The HttpServletRequest object associated with the response that is sent back to the browser.

out The JspWriter object associated with the output stream of the response.

session The HttpSession object associated with the session for the given user of request.

application The ServletContext object for the web application.


config The ServletConfig object associated with the servlet for current JSP page.

pageContext The PageContext object that encapsulates the enviroment of a single request for this current JSP page

page The page variable is equivalent to this variable of Java programming language.

exception The exception object represents the Throwable object that was thrown by some other JSP page.

10. isError – implicit object

Always jsp files both because html cannot generate error

[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8"%>

<%@page errorPage="[Link]" %>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%!
int a=10, b=20;

%>

<%
String str = null;

%>

<h1>Division = <%= a/b %></h1>


<h1>String length = <%= [Link]() %></h1>

</body>
</html>

[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- implicit object -->
<%@page isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1>error page</h1>
<h1 style="color: red">something went
wrong........</h1>
<h1><%= exception %></h1>
<h1><%= [Link]() %></h1>

</body>
</html>

[Link] directive

[Link]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 style="background: gray">I am Header</h1>
</body>
</html>

[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1 style="background: gray">I am footer</h1>

</body>
</html>

[Link]

<%@page import="[Link]"%>
<%@ page language="java" contentType="text/html;
charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%@ include file="[Link]" %>

<h1> this is content from main file</h1>

<%
Random random = new Random();
int rd = [Link]();
%>

<%= "random number = " + rd %>

<%@ include file="[Link]" %>


</body>
</html>

[Link]

[Link]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="[Link]" method="post">
<input type="text" name="name">
<input type="submit" name="submit" >
</form>

</body>
</html>

[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
String name = [Link]("name");

[Link]("name", name);
[Link]("[Link]");

%>

</body>
</html>

[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- (string) is used to convert object session
into string printable session -->
<%
String name = (String)
[Link]("name");
%>

<h1>your name = <%= name %></h1>

<h2><a href="[Link]">Go Back</a></h2>


</body>
</html>

[Link] in jsp

[Link]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<form action="[Link]" method="post">


Enter name: <input type="text" name="name"><br>
Enter Email: <input type="text" name="email"><br>
Enter city: <input type="text" name="city"><br>
Enter number: <input type="text" name="number"><br>
<button type="submit"
value="submit">submit</button>

</form>

</body>
</html>
[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
String name = [Link]("name");
String email = [Link]("email");
String city = [Link]("city");
String number = [Link]("number");

%>

<h1>Name : <%=name %></h1>


<h1>email : <%=email %></h1>
<h1>city : <%=city %></h1>
<h1>number : <%=number %></h1>
</body>
</html>
Advance JSP

[Link] on file>create maven project>next


[Link]>select Internal
Filter>select webapp>next

[Link] Group Id then Artifact Id i.e project name>finish


[Link] console
Enter Y

[Link] JRE as default


Right click>build path>select jre>edit library>finish

Project Structure
If Error “
JSTL (JavaServer Pages Standard Tag Library)
It is a collection of useful JSP tags which encapsulates the core functionality
common to many JSP application.
It completely runs on tags.
Classification of JSTL tags
• Core tags
• Formatting tags
• SQL tags
• XML tags
• JSTL functions
[Link] Tags-
<%@ taglib prefix=”c” url=”[Link]
JSTL Core Tags List

Tags Description
c:out It display the result of an expression, similar to the way <%=...%> tag work.

c:import It Retrives relative or an absolute URL and display the contents to either a String in 'var',a R
'varReader' or the page.

c:set It sets the result of an expression under evaluation in a 'scope' variable.

c:remove It is used for removing the specified scoped variable from a particular scope.

c:catch It is used for Catches any Throwable exceptions that occurs in the body.

c:if It is conditional tag used for testing the condition and display the body content only if the e
evaluates is true.

c:choose, It is the simple conditional tag that includes its body content if the evaluated condition is true.
c:when,
c:otherwise

c:forEach It is the basic iteration tag. It repeats the nested body content for fixed number
over collection.

c:forTokens It iterates over tokens which is separated by the supplied delimeters.

c:param It adds a parameter in a containing 'import' tag's URL.

c:redirect It redirects the browser to a new URL and supports the context-relative URLs.

c:url It creates a URL with optional query parameters.


Create folder in webapp :jstl

[Link] Language (EL)

[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
[Link]("name", "omkar");

Cookie ck = new
Cookie("email","omkar@[Link]");
[Link](ck);

%>
<!-- check that session created is showing or not-
->
<a href='[Link]'>go to next</a>

<form action="[Link]">
<h3>Name</h3>
<input name="name">
<input name="name">
<h3>food list</h3>
<select name='food'>
<option value="mango">mango</option>
<option value="orange">orange</option>
<option value="grapes">grapes</option>
<option value="apple">apple</option>
</select>

<h3>items</h3>
<!-- item name for checkbox is same since it
will stored in array -->
<input type="checkbox" name="item"
value="laptop">laptop
<input type="checkbox" name="item"
value="pc">pc
<input type="checkbox" name="item"
value="mouse">mouse

<input type="submit">

</form>

<!-- like servlet context type -- like global


variable
if to use servletcontext use application.
if to use servletconfig use config. -->
<%
[Link]("author","omkar
sathe");
[Link]("url",
"[Link]
%>

</body>
</html>

[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<!-- if isELIgnored="true" it will not show the
value it will give your normal text-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
using session
<h1>name: ${[Link]}</h1>

using cookies
<h1>Email: ${[Link]}</h1>

<!-- in the form of query string since


single value is stored -->
using param
<h1>${[Link] }</h1>
<h1>${[Link] }</h1>

<!-- in the form array since value is


multiple stored -->
using paramvalues
${[Link][0] }
${[Link][1] }
${[Link][2] }

using application scope


<!-- using expression lang -->
<h1>Author: ${[Link] }
</h1>
<h1>URL: <a href='${[Link]
}'> ${[Link] } </a></h1>

<!-- since href='redirectionlink' then


value -->

</body>
</html>

15. CoreJstltags
<%@ page language="java" contentType="text/html;
charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>

<%@ taglib prefix="c"


uri="[Link] %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<style type="text/css">
h3{
color: red;
}
body{
padding: 0px 50px;
}
</style>
</head>
<body>
<h1 style='text-align:center; color:blue'>Core
Tags : 14</h1>
<p style='text-align:center;'>The JSTL core tag
provides variable support, URL management, flow
control etc.</p>
<h3>c:if no else is there in jstl</h3>
It is conditional tag used for testing the
condition and display the body content only if the
expression evaluates is true.
<h3>c:set</h3>
It sets the result of an expression under
evaluation in a 'scope' variable.
<c:set var="a" value="-5"></c:set>
<c:if test= "${a>0}">
<!-- test,var,value is inbuilt -->

<h1> ${a} is positive number </h1>


</c:if>

<c:if test= "${a<0}">


<h1> ${a} is negative number </h1>
</c:if>

<h3>c:out</h3>
It display the result of an expression, similar
to the way "expression" tag work.
<h2>
<c:out value="${'<h5>This is a <c:out>
escape XML test</h5>' }"></c:out> <br>
sum of 10 + 20 : <c:out
value="${10+20}"></c:out>
</h2>

<h3>c:catch</h3>
It is used for Catches any Throwable exceptions
that occurs in the body.
<c:catch var="exception">
<% int x = 10 / 0; %>
</c:catch>
<c:if test="${exception != null}">
<h1>error occured : ${exception}</h1>
</c:if>

<h3>c:url and c:param</h3>


url => It creates a URL with optional query
parameters. <br>
param => It adds a parameter in a containing
'import' tag's URL.
<c:url value="/[Link]" var="coreUrl">
<c:param name="name"
value="Omkar"></c:param>
</c:url>
<h1>complete url : ${coreUrl}</h1>
<h4><a href="${coreUrl}">click here
</a></h4>

<h3>c:forEach</h3>
most commonly used tag because it iterates over
a collection of object.
<h1>
<c:forEach var="i" begin="1" end="10" >
<c:out value="${i*2}"></c:out>
</c:forEach>
</h1>

Using array<br><br>
<%
int array[]={10,20,30};
[Link]("array", array);
%>

address of array :<c:out


value="${array}"></c:out> <br>
<h1>
<c:forEach var="i" items="${array}">
<c:out value="${i}"></c:out>
</c:forEach>
</h1>

<%
int array1[]={10,20,30};
// [Link]("array",
array);
%>
<h1>
<c:forEach var="i" items="<%= array1
%>">
<c:out value="${i}"></c:out>
</c:forEach>
</h1>
<h3>c:import</h3>
It Retrives relative or an absolute URL and
display the contents to either a String in 'var',a
Reader in 'varReader' or the page.
<c:import var="data"
url="[Link]
<%-- <c:out value="${data}"/> --%>
${data}

<h3>c:remove</h3>
removes the variable from either a first scope
or a specified scope.
<c:set var="income" scope="session"
value="${4000*4}"/>
<h1>Before Remove Value is: <c:out
value="${income}"/></h1>
<c:remove var="income"/>
<h1>After Remove Value is: <c:out
value="${income}"/></h1>

<h3>c:choose c:when c:otherwise</h3>


The c:when and c:otherwise works like if-else
ladder statement. But it must be placed inside
c:choose tag.
<c:set var="income" scope="session"
value="${4000*4}"/>
<c:choose>
<c:when test="${income <= 1000}">
<h1>Income is not good.</h1>
</c:when>
<c:when test="${income > 10000}">
<h1>Income is very good.</h1>
</c:when>
<c:otherwise>
<h1>Income is undetermined... </h1>
</c:otherwise>
</c:choose>

<h3>c:forTokens</h3>
It iterates over tokens which is separated by
the supplied delimeters.
<c:forTokens items="Rahul-Nakul-Rajesh"
delims="-" var="name">
<h1><c:out value="${name}"/></h1>
</c:forTokens>

</body>
</html>

16. formatting-tags

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>

<%@ taglib prefix="c"


uri="[Link] %>
<%@ taglib
uri="[Link] prefix="fmt"
%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
h3{
color: red;
}
body{
padding: 0px 50px;
}
</style>
</head>
<body>
<h1 style='text-align:center;
color:blue'>Formatting Tags : 9</h1>
<p style='text-align:center;'> The formatting
tags provide support for message formatting, number
and date formatting etc.</p>

<h3>fmt:parseNumber</h3>
It is used to Parses the string representation
of a currency, percentage or number.
<c:set var='amount'
value='456.980'></c:set>
<h1>${amount}</h1>
<fmt:parseNumber var='amt'
value="${amount}" type="number"></fmt:parseNumber>
<h2>amount after parse : ${amt}</h2>
<fmt:parseNumber var='amt'
value="${amount}" type="number"
integerOnly="true"></fmt:parseNumber>
<h2>amount after parse integer only :
${amt}</h2>

<h3>fmt:timeZone</h3>
It specifies a parsing action nested in its
body or the time zone for any time formatting.
<c:set var = "now" value = "<%= new
[Link]()%>" ></c:set>
<br>
${now}
<br>
<fmt:formatDate value="${now}"
type='both'></fmt:formatDate>

</body>
</html>

17. [Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>

<%@ taglib prefix="c"


uri="[Link] %>

<%@ taglib prefix="fn"


uri="[Link] %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
h3{
color: red;
}
body{
padding: 0px 50px;
}
</style>
</head>
<body>

<h1 style='text-align:center;
color:blue'>Function Tags : 15</h1>
<p style='text-align:center;'>The JSTL function
provides a number of standard functions, most of
these functions are common string manipulation
functions.</p>

<h3>fn:contains('str' 'subStr')</h3>
It is used to test if an input string
containing the specified substring in a program.
<c:set var="testStr" value="this is JSTL
function"></c:set>
<h1>${testStr}</h1>
<c:if test="${fn:contains(testStr, 'JSTL')
}">
<h2>JSTL present in string</h2>
</c:if>
<c:if test="${!fn:contains(testStr, 'jstl')
}">
<h2>jstl does not present in
string</h2>
</c:if>

<h3>fn:containsIgnoreCase('str' 'subStr')</h3>
It is used to test if an input string contains
the specified substring as a case insensitive way.
<c:if
test="${fn:containsIgnoreCase(testStr, 'JSTL') }">
<h2>JSTL present in string</h2>
</c:if>
<c:if
test="${fn:containsIgnoreCase(testStr, 'jstl') }">
<h2>jstl present in string</h2>
</c:if>

<h3>fn:startsWith('str', 'startStr')</h3>
It is used for checking whether the given
string is started with a particular string value.
<c:if test="${!fn:startsWith(testStr,
'Hello') }">
<h2>string does not starts with
Hello</h2>
</c:if>
<c:if test="${fn:startsWith(testStr,
'this') }">
<h2>string starts with this</h2>
</c:if>

<h3>fn:endsWith('str', 'endStr')</h3>
It is used to test if an input string ends with
the specified suffix.
<c:if test="${!fn:endsWith(testStr, 'java')
}">
<h2>string does not ends with java</h2>
</c:if>
<c:if test="${fn:endsWith(testStr,
'function') }">
<h2>string ends with function</h2>
</c:if>

<h3>fn:length(str)</h3>
It returns the number of characters inside a
string, or the number of items in a collection.
<h2>Length of string :
${fn:length(testStr)}</h2>

<h3>fn:replace(String input, String search_for,


String replace_with)</h3>
It searches the search_for string in the input
and replaces all the occurrences with replace_with
string.
<h2>after replace this with This:
${fn:replace(testStr, 'this', 'This') }</h2>

<h3>fn:trim('str')</h3>
It removes the blank spaces from both the ends
of a string.
<h2>${fn:trim(testStr)}</h2>

<h3>fn:split('str', 'split with')</h3>


It splits the string into an array of
substrings.
<c:set var='arr'
value='${fn:split(testStr," ")}'
scope="session"></c:set>
<h2>${arr}</h2>

<% String[] strArr = (String[])


[Link]("arr");
for(String ar : strArr){
[Link]("<h1>"+ ar +"</h1>");
}
%>

<h3>fn:join('str', 'join with')</h3>


<!-- can convert array into string -->
<c:set var='arr' value='${fn:join(arr,"
")}'></c:set>
<h2>${arr}</h2>

<h3>fn:indexOf('str', 'search')</h3>
It returns an index within a string of first
occurrence of a specified substring.
<c:set var='strInd' value="abc xyz
abc"></c:set>
<h1>${strInd}</h1>
<h2>start index of abc:
${fn:indexOf(strInd, 'abc')}</h2>
<h2>start index of y: ${fn:indexOf(strInd,
'y')}</h2>

<h3>fn:escapeXml('str')</h3>
It escapes the characters that would be
interpreted as XML markup.
<c:set var='str1'
value='<h1>OMKAR</h1>'></c:set>
<c:set var='str2' value='<h2>omkar
sathe</h2>'></c:set>
${str1}
${str2}
actual out for escape - html tags will be
seen as it is
${fn:escapeXml(str1)}
${fn:escapeXml(str2)}

<h3>fn:toLowerCase('str')</h3>
It converts all the characters of a string to
lower case.
${fn:toLowerCase(str1)}

<h3>fn:toUpperCase('str')</h3>
It converts all the characters of a string to
upper case.
${fn:toUpperCase(str2)}

<h3>fn:substring('str', startIndex,
endIndex)</h3>
It returns the subset of a string according to
the given start and end position. start include,
end exclude
<c:set var='substr' value='i am example of
sub string'></c:set>
<h1>${substr}</h1>
<h2>${fn:substring(substr, 2, 7)}</h2>

<h3>fn:substringAfter('str',
'strAfterThis')</h3>
It returns the subset of string after a
specific substring.
<h2>${fn:substringAfter(substr, 'of')}</h2>

<h3>fn:substringBefore('str',
'strAfterThis')</h3>
It returns the subset of string before a
specific substring.
<h2>${fn:substringBefore(substr,
'of')}</h2>

</body>
</html>

18. filter

Create [Link],[Link],[Link] in web app folder

In private folder in webapp create- firsthtml and [Link]

Create folder java- auth- [Link]

java- private

[Link]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
private route
</body>
</html>

[Link]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
name:<input type="text" name="name"><br/>
pass: <input type="password"
name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>

[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<% String name =(String)
[Link]("name"); %>
welcome <%= name %>

<!-- or -->

<%-- ${name} --%>

</body>
</html>

In private folder
[Link]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
first route
</body>
</html>

[Link]

<%@ page language="java" contentType="text/html;


charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
second route
</body>
</html>

In java folder – in auth folder

package auth;

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/login")
public class Login extends HttpServlet{
static final long serialVersionUID = 1L;

@Override
protected void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException,
IOException {
String name = "omkar";
String password = "123";
String uName = [Link]("name");
String uPass =
[Link]("password");

if([Link](uName) &&
[Link](uPass)) {
HttpSession session =
[Link]();
[Link]("name", name);
[Link]([Link]()
+"/[Link]");
}else {
[Link]([Link]()
+"/[Link]");
}
}

Create filter folder – [Link]

package filters;
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebFilter(urlPatterns =
{"/[Link]","/[Link]", "/private/*"} )
public class AuthFilter implements Filter{

@Override
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest req =
(HttpServletRequest) request;
HttpServletResponse res =
(HttpServletResponse) response; // data casting
into http servlets
HttpSession session = [Link]();

String isName =(String)


[Link]("name");
if(isName != null ){
[Link](isName);
[Link](request, response);
}else {
[Link]([Link]() +
"/[Link]");
}
}

Hibernate
• Developed by Gavin King 2001
• Java framework that simplifies the development of java application to
interact with database.
• It is open source, lightweight, ORM(Object Relational Mapping) tool
• It implements the specifications of JPA(Java Persistence API) for data
persistence.
• Any type of application can be build with hibernate framework.
• Classes are table and object are rows.
• It is best ORM for java
• ORM = object relational mapping
• We don’t need to write sql query
• Class is table (column names)
• Objects are rows
Note : Hibernate :New app – maven – internal – quick start

Hibernate+ Frontend :New app – maven – internal – webapp

[Link]—standard file- if you write this name in java folder – session factory no need to
five the configuration file name

Session Factory – class in that configuration is a interface so we cannot create the object so we use
the configure method from it and from that buildsessionfactory method

New app→maven-internal-quick start-next-finish

Set Java JRE as default built path


Create a xml file on java folder name= [Link]

Add [Link] code


On Java Create bean folder->create classes.
If there are error on [Link] file do the following changes->
[Link]→Preferences→Maven→Tick on the below tick box →Appy &
Apply and close

[Link] the above doesn’t work try this try this as well
Windows→Preferences→XML(Wild Web Developer)→Tick on the below tick
box →Appy & Apply and close
Dependency add In [Link]

<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>

<groupId>demo</groupId>
<artifactId>HibernateBasic</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>HibernateBasic</name>
<url>[Link]

<properties>
<[Link]>UTF-8</[Link]>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

<!-- [Link] -->


<dependency>
<groupId>[Link]</groupId>
<artifactId>hibernate-core</artifactId>
<version>[Link]</version>
</dependency>

<!-- [Link] -->


<dependency>
<groupId>[Link]</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>
</dependencies>
</project>
[Link]

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"[Link]

<hibernate-configuration>
<session-factory>
<property
name="connection.driver_name">[Link]</property>
<property
name="[Link]">jdbc:mysql://localhost:3306/hibernate</property>
<property name="[Link]">root</property>
<property name="[Link]"></property>
<!-- <property
name="dialect">[Link]</property> -->
<property name="[Link]">update</property>
<property name="show_sql">true</property>
<!-- <property name="format_sql">true</property> -->

<mapping class="[Link]"></mapping>
</session-factory>
</hibernate-configuration>

In Bean package

[Link]

package [Link];

import [Link];
import [Link];

//ctrl+space to import annotation for entity


@Entity
public class Student {
@Id
private int id;
private String name;
private String email;
private String address;
public Student() {
// TODO Auto-generated constructor stub

public Student(int id, String name, String email, String


address) {
super();
[Link] = id;
[Link] = name;
[Link] = email;
[Link] = address;
}

public int getId() {


return id;
}

public void setId(int id) {


[Link] = id;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public String getEmail() {


return email;
}
public void setEmail(String email) {
[Link] = email;
}

public String getAddress() {


return address;
}

public void setAddress(String address) {


[Link] = address;
}

@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ",
email=" + email + ", address=" + address + "]";
}

In Hibernatebasic package

[Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

import [Link];

/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
[Link]( "Hello World!" );
// Configuration cfg = new Configuration().configure();
SessionFactory factory = new
Configuration().configure().buildSessionFactory();
[Link](factory);

Session session=[Link]();
Transaction transaction=[Link]();

Student sb=new Student();


[Link](1);
[Link]("Ram");
[Link]("abc@[Link]");
[Link]("Pune");

Student sp=new
Student(2,"Raj","raj@[Link]","mumbai");

//to save data and update data create data -->


persist
[Link](sb);
[Link](sp);

//operation to be saved till persist() only once


called
[Link]();

//only once
[Link]();
[Link]();
}
}

Now create a separate file for Connection so that it can be shared

In HibernateBasic package

[Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class Connection {

SessionFactory factory = new


Configuration().configure().buildSessionFactory();

Session session=[Link]();
Transaction transaction=[Link]();

public Session getSession()


{
return session;
}

public void commitTransaction()


{
[Link]();
}

public void closeSession()


{
[Link]();
[Link]();
}
}

In Method package

[Link]

package [Link];

import [Link];

import [Link];
import [Link];

public class SaveStudent {

public static void main(String[] args) {


// TODO Auto-generated method stub

Connection con=new Connection();

try
{
Session session=[Link]();
Student sp=new
Student(4,"vijay","vijay@[Link]","nagpur");
//persist -- create a persitance state to save
object
[Link](sp);

//commit -- actual running of a sql query


[Link]();
[Link]("Successfully Record
Saved!");
}
catch(Exception e)
{
[Link](e);
}
finally
{
[Link]();
}

[Link]

package [Link];

import [Link];

import [Link];
import [Link];

public class GetStudent {

public static void main(String[] args) {


// TODO Auto-generated method stub

Connection con=new Connection();

try
{
Session session=[Link]();

//commit -- actual running of a sql query


//commit is not required for get method only
require for create,update,delete
Student stud=[Link]([Link],1);
[Link](stud);
}
catch(Exception e)
{
[Link](e);
}
finally
{
[Link]();
}

[Link]

package [Link];

import [Link];

import [Link];
import [Link];

public class UpadateStudent {

public static void main(String[] args) {


// TODO Auto-generated method stub
Connection con=new Connection();

try
{
Session session=[Link]();

//commit -- actual running of a sql query


//commit is not required for get method only
require for create,update,delete
Student stud=[Link]([Link],1);
[Link]("Banglore");
[Link]("ram@[Link]");
[Link](stud);
[Link]();
[Link]("student Updated
Successfully!!");
}
catch(Exception e)
{
[Link](e);
}
finally
{
[Link]();
}
}

[Link]

package [Link];

import [Link];

import [Link];
import [Link];

public class DeleteStudent {

public static void main(String[] args) {


// TODO Auto-generated method stub
Connection con=new Connection();

try
{
Session session=[Link]();
//commit -- actual running of a sql query
//commit is not required for get method only
require for create,update,delete
Student stud=[Link]([Link],1);
[Link](stud);
[Link]();
//persist is for saving commit is to complete
[Link]("Deleted Successfully!!");
}
catch(Exception e)
{
[Link](e);
}
finally
{
[Link]();
}

Hibernate Annotations is the powerful way to provide the metadata for the
Object and Relational Table mapping. All the metadata is clubbed into the
POJO (Plain Old Java Object) java file along with the code, this helps the user
to understand the table structure and POJO simultaneously during the
development.

If you going to make your application portable to other EJB 3 compliant ORM
applications, you must use annotations to represent the mapping
information, but still if you want greater flexibility, then you should go with
XML-based mappings.
Employee Example

In bean folder

[Link]

package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

//entity -- by default classname is taken as tablename and


created
//@Table -- if bydefault classname should not be your table
name if ypu want to give your own table name use @Table
@Entity
@Table(name="EmployeeTable")

public class Employee {

@Id
@GeneratedValue(strategy=[Link])

//@GeneratedValue(strategy=[Link])
private int id;
@Column(name="name",nullable=false,length = 20)
private String empName;
private double salary;
@Temporal([Link])
private LocalDateTime joiningdate;
private String email;
private boolean status;
//transient will not that data permanently in database
it is just like flag setting
@Transient
private String token;

public Employee() {
// TODO Auto-generated constructor stub

public Employee(String empName, double salary,


LocalDateTime joiningdate, String email, boolean status,
String token) {
super();
[Link] = empName;
[Link] = salary;
[Link] = joiningdate;
[Link] = email;
[Link] = status;
[Link] = token;
}

public int getId() {


return id;
}

public void setId(int id) {


[Link] = id;
}

public String getEmpName() {


return empName;
}

public void setEmpName(String empName) {


[Link] = empName;
}

public double getSalary() {


return salary;
}

public void setSalary(double salary) {


[Link] = salary;
}

public LocalDateTime getJoiningdate() {


return joiningdate;
}

public void setJoiningdate(LocalDateTime joiningdate) {


[Link] = joiningdate;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


[Link] = email;
}

public boolean isStatus() {


return status;
}

public void setStatus(boolean status) {


[Link] = status;
}

public String getToken() {


return token;
}

public void setToken(String token) {


[Link] = token;
}

@Override
public String toString() {
return "Employee [id=" + id + ", empName=" + empName
+ ", salary=" + salary + ", joiningdate=" + joiningdate
+ ", email=" + email + ", status=" + status
+ ", token=" + token + "]";
}

In method package

[Link]
package [Link];

import [Link];

import [Link];

import [Link];
import [Link];

public class SaveEmployee {

public static void main(String[] args) {


Connection con=new Connection();

try
{
Session session=[Link]();
Employee sp=new
Employee("Ram",20000D,[Link](),"ram@[Link]",true,"Ram@
12");
//2000D -- D is for Double L is for Long
//persist -- create a persitance state to save
object
[Link](sp);

//commit -- actual running of a sql query


[Link]();
[Link]("Successfully Record Saved!");
}
catch(Exception e)
{
[Link](e);
}
finally
{
[Link]();
}

In [Link] register the employee class

<mapping class="[Link]"></mapping>

Mapping in Hibernate
One to one mapping
Unidirectional

Only one table has foreign key

Bidirectional

Both table has foreign key

[Link] Mapping

Unidirectional

[Link]—bean folder

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

//to create the table


@Entity
@Table(name="employee_details")
public class EmployeeDetails {

// to create the unique id we use @Id


@Id
//to create automatic values and to be compatible with db type
@GeneratedValue(strategy=[Link])
private int id;
//compulsary name field should have value
@Column(nullable=false)
private String name;
//create the object of address class
// one to one mapping annotation

@OneToOne
private EmployeeAddress address;
public EmployeeDetails() {
// TODO Auto-generated constructor stub

}
public int getId() {
return id;
}
public void setId(int id) {
[Link] = id;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public EmployeeAddress getAddress() {
return address;
}
public void setAddress(EmployeeAddress address) {
[Link] = address;
}
@Override
public String toString() {
return "EmployeeDetails [id=" + id + ", name=" + name +
", address=" + address + "]";
}
public EmployeeDetails(String name, EmployeeAddress
address) {
super();
[Link] = name;
[Link] = address;
}

[Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@Entity
@Table(name="Employee_Address")
public class EmployeeAddress {

// to create the unique id we use @Id


@Id
//to create automatic values and to be compatible with
db type
@GeneratedValue(strategy=[Link])
private int id;
//compulsary name field should have value
@Column(nullable=false)
private String address;

public EmployeeAddress() {
// TODO Auto-generated constructor stub
}

public int getId() {


return id;
}

public void setId(int id) {


[Link] = id;
}

public String getAddress() {


return address;
}

public void setAddress(String address) {


[Link] = address;
}

@Override
public String toString() {
return "EmployeeAddress [id=" + id + ", address=" +
address + "]";
}

public EmployeeAddress( String address) {


super();
[Link] = address;
}

}
[Link] – [Link] package

package [Link];

import [Link];

import [Link];
import [Link];
import [Link];

public class OneToOne {

public static void main(String[] args) {


// TODO Auto-generated method stub

Connection conn=new Connection();


try
{Session session=[Link]();

//to save details and object

EmployeeAddress address=new
EmployeeAddress("pune") ;
EmployeeDetails details=new
EmployeeDetails("Kartiki",address);
//if not taken detail will be null
[Link](details);
[Link](address);
[Link](details);

[Link]();

//get the data


EmployeeDetails
details1=[Link]([Link], 1);
[Link]([Link]());
//print whole address table
[Link]([Link]());
//print address name from address table

[Link]([Link]().getAddress());
}
catch(Exception e)
{
[Link](e);
}

finally
{
[Link]();
}
}

.xml file

<mapping class="[Link]"></mapping>
<mapping class="[Link]"></mapping>

Note : Delete and drop table first from xamp of empdetail and empaddress

BiDirectional

[Link]

//same name from details table object


@OneToOne(mappedBy="address")
private EmployeeDetails details;

public EmployeeDetails getDetails() {


return details;
}

public void setDetails(EmployeeDetails details) {


[Link] = details;
}
[Link]

// fetch employeedetails from employeeaddress

EmployeeAddress
address1=[Link]([Link],1);
[Link]([Link]());

[Link]([Link]().getName());

Note :

Consider you have to delete the detail table record then by default address table will have unknown
deleted reference so to delete it

In [Link]

@OneToOne(cascade=[Link])

[Link]

//delete one record from employeedetail to check if


address refered to it is deleting or not
EmployeeDetails
details=[Link]([Link], 1);
[Link](details);
[Link]();

.cgf

<property name="[Link]">update</property>

[Link] to Many

[Link]

package [Link];
import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
@Entity
public class StudentDetails {

@Id
private int id;
private String name;

//eager --> fetch all the data from other table at once
@OneToMany(mappedBy="studentdetails",fetch=FetchType.E
AGER)
private List<StudentAddress> address=new ArrayList<>();

public StudentDetails() {
// TODO Auto-generated constructor stub
}

public int getId() {


return id;
}

public void setId(int id) {


[Link] = id;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public List<StudentAddress> getAddress() {


return address;
}

public void setAddress(List<StudentAddress> address) {


[Link] = address;
}

@Override
public String toString() {
return "StudentDetails [id=" + id + ", name=" + name + ",
address=" + address + "]";
}

public StudentDetails(int id, String name,


List<StudentAddress> address) {
super();
[Link] = id;
[Link] = name;
[Link] = address;
}

[Link]

package [Link];

import [Link];
import [Link];
import [Link];
@Entity
public class StudentAddress {

@Id
private int id;
private String addressType; // permanent or temporary
private String address;

@ManyToOne
private StudentDetails studentdetails;

public StudentAddress() {
// TODO Auto-generated constructor stub
}

public int getId() {


return id;
}

public void setId(int id) {


[Link] = id;
}

public String getAddressType() {


return addressType;
}

public void setAddressType(String addressType) {


[Link] = addressType;
}

public String getAddress() {


return address;
}

public void setAddress(String address) {


[Link] = address;
}

public StudentDetails getStudentdetails() {


return studentdetails;
}

public void setStudentdetails(StudentDetails studentdetails) {


[Link] = studentdetails;
}
@Override
public String toString() {
return "StudentAddress [id=" + id + ", addressType=" +
addressType + ", address=" + address
+ ", studentdetails=" + studentdetails + "]";
}

public StudentAddress(int id, String addressType, String


address) {
super();
[Link] = id;
[Link] = addressType;
[Link] = address;
}

[Link]

package [Link];

import [Link];
import [Link];
import [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class OneToMany {

public static void main(String[] args) {


// TODO Auto-generated method stub
Connection conn=new Connection();
try
{
Session session=[Link]();
// to save details and address of student
StudentAddress ad1=new
StudentAddress(1,"permanent","kolhapur");
StudentAddress ad2=new
StudentAddress(2,"temporary","pune");

List<StudentAddress> list=new ArrayList<>();


[Link](ad1);
[Link](ad2);

StudentDetails st=new
StudentDetails(1,"Kartiki",list);

// ==================bidirectional data
===========================
[Link](st);
[Link](st);

[Link](ad1);
[Link](ad2);
[Link](st);

[Link]("Successfully added student!!");

[Link]();

// //get the data

StudentDetails
st2=[Link]([Link], 1);
[Link]([Link]());
for(StudentAddress address:[Link]())
{
[Link]([Link]()+"
"+[Link]());
}

}
catch(Exception e)
{
[Link](e);
}

finally
{
[Link]();
}

.xml file

<mapping class="[Link]"></mapping>
<mapping class="[Link]"></mapping>

[Link]

[Link]

package [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

@Entity
public class WorkerDetails {

@Id
private int id;
private String name;
@ManyToMany(fetch=[Link])
private List<WorkerAddress> address=new ArrayList<>();

public WorkerDetails() {
// TODO Auto-generated constructor stub
}

public int getId() {


return id;
}

public void setId(int id) {


[Link] = id;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public List<WorkerAddress> getAddress() {


return address;
}

public void setAddress(List<WorkerAddress> address) {


[Link] = address;
}

public WorkerDetails(int id, String name) {


super();
[Link] = id;
[Link] = name;
}
@Override
public String toString() {
return "WorkerDetails [id=" + id + ", name=" + name + ",
address=" + address + "]";
}

[Link]

package [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];

@Entity
public class WorkerAddress {
@Id
private int id;
private String address;

@ManyToMany(mappedBy="address")
private List<WorkerDetails> details=new ArrayList<>();

public WorkerAddress() {
// TODO Auto-generated constructor stub
}

public int getId() {


return id;
}

public void setId(int id) {


[Link] = id;
}

public String getAddress() {


return address;
}

public void setAddress(String address) {


[Link] = address;
}

public List<WorkerDetails> getDetails() {


return details;
}

public void setDetails(List<WorkerDetails> details) {


[Link] = details;
}

@Override
public String toString() {
return "WorkerAddress [id=" + id + ", address=" +
address + ", details=" + details + "]";
}

public WorkerAddress(int id, String address) {


super();
[Link] = id;
[Link] = address;

[Link]

package [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class ManyToMany {

public static void main(String[] args) {


// TODO Auto-generated method stub

Connection conn=new Connection();


try {

Session session=[Link]();

WorkerDetails wt1=new WorkerDetails(1,"Ram");


WorkerDetails wt2=new WorkerDetails(2,"Raj");

WorkerAddress wa1=new
WorkerAddress(1,"Pune");
WorkerAddress wa2=new
WorkerAddress(2,"Mumbai");

List<WorkerDetails> wdList=new ArrayList<>();


[Link](wt1);
[Link](wt2);

List<WorkerAddress> waList=new ArrayList<>();


[Link](wa1);
[Link](wa2);

[Link](waList);
[Link](waList);

[Link](wdList);
[Link](wdList);

[Link](wt1);
[Link](wt2);
[Link](wa1);
[Link](wa2);

[Link]();

}
catch(Exception e)
{
[Link](e);
}
finally
{
[Link]();

}
}

.xml

<mapping class="[Link]"></mapping>
<mapping class="[Link]"></mapping>

********************************************************************************

HQL : Hibernate Query Language (HQL) is an object-oriented query


language, similar to SQL, but instead of operating on tables and columns,
HQL works with persistent objects and their properties. HQL queries are
translated by Hibernate into conventional SQL queries, which in turns
perform action on database.

Although you can use SQL statements directly with Hibernate using Native
SQL, but I would recommend to use HQL whenever possible to avoid
database portability hassles, and to take advantage of Hibernate's SQL
generation and caching strategies.

Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but
properties like table and column names are case sensitive in HQL.

Hibernate is a Java framework that makes it easier to create database-


interactive Java applications. In HQL, instead of a table name, it uses a class
name. As a result, it is a query language that is database-independent.
There are many HQL clauses available to interact with relational databases,
and several of them are listed below:
1. FROM Clause
2. SELECT Clause
3. WHERE Clause
4. ORDER BY Clause
5. UPDATE Clause
6. DELETE Clause
7. INSERT Clause

DAO(Data Access Object Pattern): Data Access Object Pattern or DAO pattern
is a way of organizing code to handle the communication between your
program and a database. It helps keep your code clean and separates the logic
for interacting with data from the rest of your application.

CheatSheet : [Link]

.xml

<mapping class="[Link]"></mapping>

[Link]→bean

package [Link];

import [Link];
import [Link];

@Entity
public class StudentHQL {
@Id
private int id;
private String name;
private String address;

public StudentHQL() {
// TODO Auto-generated constructor stub
}

public int getId() {


return id;
}

public void setId(int id) {


[Link] = id;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public String getAddress() {


return address;
}

public void setAddress(String address) {


[Link] = address;
}

@Override
public String toString() {
return "StudentHQL [id=" + id + ", name=" + name + ",
address=" + address + "]";
}

public StudentHQL(int id, String name, String address) {


super();
[Link] = id;
[Link] = name;
[Link] = address;
}

[Link]

package [Link];

import [Link];

import [Link];
import [Link];
import [Link];

public class SaveStudent {

public static void main(String[] args) {


// TODO Auto-generated method stub
Connection con=new Connection();

try
{
Session session=[Link]();
StudentHQL sp=new
StudentHQL(1,"vijay","nagpur");
StudentHQL sp2=new StudentHQL(2,"jay","pune");
//persist -- create a persitance state to save object
[Link](sp);
[Link](sp2);

//commit -- actual running of a sql query


[Link]();
[Link]("Successfully Record Saved!");
}
catch(Exception e)
{
[Link](e);
}
finally
{
[Link]();
}

[Link]

package [Link];

import [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];

public class GetStudent {

public static void main(String[] args) {


// TODO Auto-generated method stub

Connection con=new Connection();

try
{
Session session=[Link]();

// get all
Query<StudentHQL>
query=[Link]("from
StudentHQL",[Link]);
List<StudentHQL> students=[Link]();

for(StudentHQL student:students)
{
[Link](student);
}
//get by Id
//manually query not used
StudentHQL
student1=[Link]([Link], 1);
[Link](student1);

//using query
//student fetch whose id and address is same
Query<StudentHQL>
query2=[Link]("from StudentHQL where id=1 and
address='nagpur'"
+ " ",[Link]);

StudentHQL student2=[Link]();
[Link]("by id and address
:"+student2);

//dyanmic
Query<StudentHQL>
query3=[Link]("from StudentHQL where id=:id and
address=:address"
+ " ",[Link]);
[Link]("id", 2);
[Link]("address", "pune");
StudentHQL student3=[Link]();
[Link]("dynamic values by id and
address :"+student3);

//order by : by default ascending


Query<StudentHQL>
query4=[Link]("from StudentHQL order by id desc
",[Link]);
List<StudentHQL> students4=[Link]();

for(StudentHQL student:students4)
{
[Link](student);
}

//get only address


//String is return type
Query<String>
query5=[Link]("Select address from StudentHQL
where id=1",[Link]);
String student5=[Link]();
[Link]("by id and address
:"+student5);

//get address & name


//Object is return type

Query<Object[]>
query6=[Link]("Select address,name from
StudentHQL where id=2",Object[].class);
Object[] student6=[Link]();
[Link]("by address and name
:"+student6[0]+ ","+student6[1]);

}
catch(Exception e)
{
[Link](e);
}
finally
{
[Link]();
}

[Link]

package [Link];

import [Link];
import [Link];

import [Link];
public class UpdateStudent {

public static void main(String[] args) {


// TODO Auto-generated method stub

Connection conn=new Connection();


try {
Session session=[Link]();

MutationQuery
query=[Link]("update StudentHQL set
name='ram update' ,address='pune update' where id=1");

int i=[Link]();
if(i==1)
{
[Link]("Updated Successfully ");
}
else
{
[Link]("Fail to Updated ");
}
[Link]();
}
catch(Exception e)
{
[Link](e);
}
finally
{
[Link]();
}

[Link]

package [Link];
import [Link];
import [Link];

import [Link];

public class DeleteStudent {

public static void main(String[] args) {


// TODO Auto-generated method stub

Connection conn=new Connection();


try {
Session session=[Link]();

MutationQuery
query=[Link]("delete from StudentHQL
where id=1");

int i=[Link]();
if(i==1)
{
[Link]("Deleted Successfully ");
}
else
{
[Link]("Fail to Delete ");
}
[Link]();
}
catch(Exception e)
{
[Link](e);
}
finally
{
[Link]();
}

}
Hibernate Project :

[Link]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet"
href="[Link]
[Link]"
integrity="sha384-
xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNL
D69Npy4HI+N"
crossorigin="anonymous">

<style type="text/css">
body {
background-color: #5ad696;
}

form {
width: 500px;
font-size: 20px;
font-weight: bolder;
}

form button {
font-weight: bold;
}

h3 {
color: blue;
text-decoration: underline;
margin-top: 20px;
}
</style>
</head>
<body
class="d-flex flex-column justify-content-center align-items-
center">
<h1 class="text-center text-danger m-5">Employee
Registration</h1>

<form action="register" method="post">


<div class="form-group">
<label>Emp ID</label> <input type="text"
class="form-control"
placeholder="Enter employee id" name="id">
</div>
<div class="form-group">
<label>Name</label> <input type="text"
class="form-control"
placeholder="Enter name" name="name">
</div>
<div class="form-group">
<label>Department</label> <input type="text"
class="form-control"
placeholder="Enter department"
name="department">
</div>
<div class="form-group">
<label>Salary</label> <input type="text"
class="form-control"
placeholder="Enter salary" name="salary">
</div>
<div class="form-group">
<label>Email</label> <input type="email"
class="form-control"
placeholder="Enter Email Address"
name="email">
</div>
<div class="form-group">
<label>Password</label> <input type="password"
class="form-control"
placeholder="Enter password"
name="password">
</div>

<button type="submit" class="btn btn-


dark">Register</button>
</form>
<script

src="[Link]
[Link]"
integrity="sha384-
DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUe
w+OrCXaRkfj"
crossorigin="anonymous"></script>
<script

src="[Link]
[Link]"
integrity="sha384-
Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP
9dO5Vg3Q9ct"
crossorigin="anonymous"></script>
</body>
</html>

In controller package—[Link]

package [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/register")
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;

@Override
protected void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException {
int id = [Link]([Link]("id"));
String name = [Link]("name");
String department = [Link]("department");

long salary =
[Link]([Link]("salary"));

String email = [Link]("email");

String password = [Link]("password");

String hashPassword =
[Link](password);

Employee emp = new Employee(id, name, department,


salary, email, hashPassword);

// [Link](emp);

EmployeeDao empDao = new EmployeeDao();

boolean isSaved = [Link](emp);

PrintWriter out = [Link]();


[Link]("text/html");

if (isSaved) {
[Link]("saved successfully");
[Link]("<h3 class='mb-2 text-
success'>Registration successful</h3>");

[Link]("[Link]").include(req, resp);

} else {
[Link]("Internal server error");
[Link]("<h3 class='mb-2 text-error'>Internal
server error</h3>");
[Link]("[Link]").include(req, resp);
}
}

In util package- [Link]

package [Link];

import [Link];

public class Password {

// Method to hash a password


public static String hashPassword(String plainPassword) {
// Generate a salt for BCrypt
String salt = [Link]();

// Hash the password


String hashedPassword =
[Link](plainPassword, salt);

return hashedPassword;
}

// Method to check if a password matches the hashed


password
public static boolean checkPassword(String plainPassword,
String hashedPassword) {
// Check if the entered password matches the stored
hashed password
return [Link](plainPassword,
hashedPassword);
}

Connection class is imported from previous HibernateBasic Project automatically


In Dao package- [Link]

package [Link];

import [Link];

import [Link];

import [Link];

public class EmployeeDao {

Connection conn = new Connection();


Session session = [Link]();

public boolean SaveEmployee(Employee emp) {

try {

[Link](emp);

[Link]();

return true;
} catch (Exception e) {
return false;
} finally {
[Link]();
}

[Link]

<!--
[Link]
et-api -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>[Link]-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>

<!--

[Link]
[Link] -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>[Link]</artifactId>
<version>3.0.1</version>
</dependency>

<!--

[Link]
[Link]-api -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>[Link]-api</artifactId>
<version>3.0.0</version>
</dependency>

<!--
[Link]
core -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>hibernate-core</artifactId>
<version>[Link]</version>
</dependency>

<!-- [Link]
connector-j -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>

<!--
[Link] -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>jBCrypt</artifactId>
<version>0.4.3</version>
</dependency>

Student Management Project

[Link]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
body{
min-height: 100vh;
}
a{
font-size: 20px !important;
font-weight: bolder !important;
}
</style>
</head>
<body class="d-flex justify-content-center align-items-center bg-info">
<%@include file="./[Link]" %>

<div >
<h1 class="text-center text-white">Welcome to Student Management
System</h1>
<div class="d-flex justify-content-center align-items-center">
<a href="[Link]" class="btn btn-warning m-2">Login</a>
<a href="[Link]" class="btn btn-warning">New User</a>
</div>
</div>
</body>
</html>

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet"
href="[Link]
integrity="sha384-
xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N"
crossorigin="anonymous">

<style type="text/css">
body{
background-color: #5ad696;
}
form{
width: 500px;
font-size: 20px;
font-weight: bolder;
}
form button{
font-weight: bold;
}
h3{
color:blue;
text-decoration: underline;
margin-top: 20px;
}
</style>
</head>
<body class="d-flex flex-column justify-content-center align-items-center">
<h1 class="text-center text-danger m-5">User Login</h1>

<form action="AuthLogin" method="post">


<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-
describedby="emailHelp" placeholder="Enter Email Address" name="email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1"
placeholder="Enter Password" name="password">
</div>
<button type="submit" class="btn btn-dark">Login</button>
</form>

<script src="[Link]
integrity="sha384-
DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script
src="[Link]
integrity="sha384-
Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct"
crossorigin="anonymous"></script>
</body>

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>signup</title>
<link rel="stylesheet"
href="[Link]
integrity="sha384-
xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N"
crossorigin="anonymous">

<style type="text/css">
body{
background-color: #5ad696;
}
form{
width: 500px;
font-size: 20px;
font-weight: bolder;
}
form button{
font-weight: bold;
}
h3{
color:blue;
text-decoration: underline;
margin-top: 20px;
}
</style>
</head>
<body class="d-flex flex-column justify-content-center align-items-center">
<h1 class="text-center text-danger m-5">Create New User</h1>

<form action="signup" method="post">


<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-
describedby="emailHelp" placeholder="Enter Email Address" name="email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1"
placeholder="Enter Password" name="password">
</div>
<button type="submit" class="btn btn-dark">Sign Up</button>
</form>

<script src="[Link]
integrity="sha384-
DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script
src="[Link]
integrity="sha384-
Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct"
crossorigin="anonymous"></script>
</body>
</html>

[Link]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="[Link] %>
<%@page isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
form{
width: 500px;
font-size: 20px;
font-weight: bolder;
}
form button{
font-weight: bold;
}
</style>
</head>
<body>
<%@include file="./[Link]"%>
<%@ include file="[Link]"%>

<div class="d-flex justify-content-center align-items-center">


<div class="card mt-5">
<div class="card-body">

<c:if test="${student == null}">


<h1>Add Student</h1>
<form action="api/insert" method="post">

</c:if>
<c:if test="${student != null}">
<h1>Update Student</h1>
<form action="api/update" method="post">

<input type="hidden" name="id"


value="${[Link]}">
</c:if>

<div class="form-group">
<label>Name</label>
<input type="text" class="form-control"
aria-describedby="emailHelp" placeholder="Enter Email Address" name="name"
value="${[Link]}">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control"
aria-describedby="emailHelp" placeholder="Enter Email Address" name="email"
value="${[Link]}">
</div>
<div class="form-group">
<label>Course</label>
<input type="text" class="form-control"
aria-describedby="emailHelp" placeholder="Enter Email Address" name="course"
value="${[Link]}">
</div>

<c:if test="${student == null}">


<button type="submit" class="btn btn-
dark">Add Student</button>
</c:if>
<c:if test="${student != null}">
<button type="submit" class="btn btn-
dark">Update Student</button>
</c:if>

</form>
</div>
</div>
</div>
</body>
</html>

[Link]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="[Link] %>
<%@page isELIgnored="false"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>fgdfgd</title>
<style type="text/css">
tbody *{
font-size: 20px;
}
</style>

</head>
<body>
<%@include file="./[Link]" %>
<%@ include file="[Link]" %>

<h1 class="text-center mt-5">Student Info</h1>


<div class="d-flex justify-content-end align-items-center mr-5 ">
<a class="btn btn-success" href="api/new">Add New Student</a>
</div>

<table class="table container mt-5 text-center">


<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">NAME</th>
<th scope="col">EMAIL</th>
<th scope="col">COURSE</th>
<th scope="col" colspan="2">ACTION</th>
</tr>
</thead>
<tbody>

<c:forEach var="student" items="${allStudents}">


<tr>
<th scope="row">${[Link]}</th>
<td>${[Link]}</td>
<td>${[Link]}</td>
<td>${[Link]}</td>
<td><a href="/StudentManagemnt/api/edit?id=${[Link]}" class="btn btn-
warning">Edit</a></td>
<td><a href="/StudentManagemnt/api/delete?id=${[Link]}" class="btn btn-
danger">Delete</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>

[Link]
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Student Management System</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-
target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-
expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse " id="navbarNavAltMarkup">
<div class="navbar-nav ml-auto">
<a class="nav-link" href="/StudentManagemnt/api/list">Home</a>
<a class="nav-link" href="/StudentManagemnt/[Link]">Log Out</a>
</div>
</div>
</nav>

[Link]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Student | Error</title>
</head>
<body>

<h1>Error Found</h1>
<h1><%= [Link]() %></h1>

</body>
</html>

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<style type="text/css">
body{
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
background-color: black
}
.err{
font-size: 100px;
color:red;
}
.error{
color:white;
}
</style>
</head>
<body>
<h1 class="err">Error 404</h1>
<h1 class="error">Page Not Found</h1>
<a href="/StudentManagemnt/api/list">Go to Home Page</a>
</body>
</html>

[Link]
<!-- Bootstrap CSS -->
<link rel="stylesheet"
href="[Link]
integrity="sha384-
xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N"
crossorigin="anonymous">
<!-- Optional JavaScript -->
<!-- jQuery first, then [Link], then Bootstrap JS -->
<script src="[Link]
integrity="sha384-
DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script
src="[Link]
integrity="sha384-
Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct"
crossorigin="anonymous"></script>

[Link]

<!DOCTYPE web-app PUBLIC


"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"[Link] >

<web-app>
<display-name>Archetype Created Web Application</display-name>
<error-page>
<error-code>404</error-code>
<location>/[Link]</location>
</error-page>

<error-page>
<location>/[Link]</location>
</error-page>
</web-app>

Bean folder – [Link]


package [Link];

public class Student {


private int id;
private String name;
private String email;
private String course;
public Student(int id, String name, String email, String course) {
super();
[Link] = id;
[Link] = name;
[Link] = email;
[Link] = course;
}
public Student(String name, String email, String course) {
super();
[Link] = name;
[Link] = email;
[Link] = course;
}
public int getId() {
return id;
}
public void setId(int id) {
[Link] = id;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
[Link] = email;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
[Link] = course;
}

Dao project – [Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];

public class StudentDao {

private static final String username = "root";


private static final String password = "";
private static final String url =
"jdbc:mysql://localhost:3306/advjava";
private static final String driver =
"[Link]";

private static final String INSERT_STUDENT = "insert


into students (name, email, course) values(?,?,?)";
private static final String SELECT_STUDENT_BY_ID =
"select * from students where id = ?";
private static final String SELECT_ALL_STUDENT = "select
* from students";
private static final String DELETE_STUDENT = "delete
from students where id = ?";
private static final String UPDATE_STUDENT = "update
students set name = ?, email = ?, course = ? where id = ?";

private static final String GET_LOGIN_USER = "select *


from login where email = ? and password = ?";
private static final String ADD_NEW_USER = "insert into
login values(?,?)";

private Connection getConnection() {


Connection con = null;

try {
[Link](driver);
con = [Link](url, username,
password);
} catch (Exception e) {
[Link]();
}
return con;
}

public void insertStudent(Student student) {


try {
Connection con = getConnection();
PreparedStatement statement =
[Link](INSERT_STUDENT);
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
[Link]();
} catch (Exception e) {
[Link]();
}
}

public Student selectStudent(int id) {


Student student = null;
try {
Connection con = getConnection();
PreparedStatement statement =
[Link](SELECT_STUDENT_BY_ID);
[Link](1, id);
ResultSet rs = [Link]();

while([Link]()) {
String name = [Link]("name");
String email = [Link]("email");
String course = [Link]("course");
student = new Student(id, name, email,
course);
}
} catch (Exception e) {
[Link]();
}

return student;
}

public List<Student> selectAllStudents() {


List<Student> allStudents = new ArrayList<>();

try {
Connection con = getConnection();
PreparedStatement statement =
[Link](SELECT_ALL_STUDENT);
ResultSet rs = [Link]();

while([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
String email = [Link]("email");
String course = [Link]("course");
[Link](new Student(id, name, email,
course));
}
} catch (Exception e) {
[Link]();
}
return allStudents;
}

public boolean updateStudent(Student student) {


boolean rowUpdated=false;

try {
Connection con = getConnection();
PreparedStatement statement =
[Link](UPDATE_STUDENT);
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
[Link](4, [Link]());
rowUpdated = [Link]() > 0;
} catch (Exception e) {
[Link]();
}

return rowUpdated;
}

public boolean deleteStudent(int id) {


boolean rowDeleted=false;
try {
Connection con = getConnection();
PreparedStatement statement =
[Link](DELETE_STUDENT);
[Link](1, id);
rowDeleted = [Link]() > 0;
} catch (Exception e) {
[Link]();
}

return rowDeleted;
}

public boolean authLogin(String email, String password)


{
boolean validUser = false;

try {
Connection con = getConnection();
PreparedStatement statement =
[Link](GET_LOGIN_USER);
[Link](1, email);
[Link](2, password);

ResultSet rs = [Link]();
validUser = [Link]();
} catch (Exception e) {
[Link]();
}
return validUser;
}

public boolean createNewUser(String email, String


password) {
boolean newUser = false;

try {
Connection con = getConnection();
PreparedStatement statement =
[Link](ADD_NEW_USER);
[Link](1, email);
[Link](2, password);
newUser = [Link]() > 0;
} catch (Exception e) {
[Link]();
}
return newUser;
}
}

Web folder

[Link]

package [Link];

import [Link];
import [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/AuthLogin")
public class LoginServlet extends HttpServlet{
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request,


HttpServletResponse response) throws ServletException,
IOException {
String email = [Link]("email");
String password = [Link]("password");

StudentDao studentDao = new StudentDao();

boolean rs = [Link](email, password);

if(rs) {
[Link]("api/list").forward
(request, response);
}else {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h3>Invalid Credential</h3>");
[Link]("[Link]").inclu
de(request, response);
}
}
}

[Link]

package [Link];

import [Link];
import [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/signup")
public class NewUser extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request,


HttpServletResponse response) throws ServletException,
IOException {
String email = [Link]("email");
String password = [Link]("password");

[Link]("text/html");
PrintWriter out = [Link]();

if(![Link]().equals("") &&
![Link]().equals("")) {
StudentDao studentDao = new StudentDao();

boolean rs = [Link](email,
password);

if(rs) {
[Link]("<h3>Account created
successfully</h3>");
[Link]("[Link]").i
nclude(request, response);
}else {
[Link]("<h3>Internal server error</h3>");
[Link]("[Link]").
include(request, response);
}
} else {
[Link]("<h3>Email and Password cannot be
empty</h3>");
[Link]("[Link]").incl
ude(request, response);
}
}
}
[Link]

package [Link];

import [Link];
import [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/api/*")
public class StudentServlet extends HttpServlet{

private static final long serialVersionUID = 1L;

private StudentDao studentDao;

public void init() throws ServletException {


studentDao = new StudentDao();
}

protected void doPost(HttpServletRequest request,


HttpServletResponse response)throws ServletException,
IOException {
//for security purpose url is hidden
doGet(request, response);
}

protected void doGet(HttpServletRequest request,


HttpServletResponse response) throws ServletException,
IOException {
String route = [Link]();
[Link](route);
// / is for after api/
route = [Link]([Link]("/"));
[Link](route);

switch (route) {
case "/new":
newStudentForm(request, response);
break;
case "/insert":
insertStudent(request, response);
break;
case "/edit":
editStudentForm(request, response);
break;
case "/update":
updateUser(request, response);
break;
case "/delete":
deleteStudent(request, response);
break;
case "/list":
showAllStudent(request, response);
break;
default:
showError(request, response);
break;
}
}

private void newStudentForm(HttpServletRequest request,


HttpServletResponse response) throws ServletException,
IOException {
[Link]("/[Link]").for
ward(request, response);
}
private void insertStudent(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException{
String name = [Link]("name");
String email = [Link]("email");
String course = [Link]("course");

[Link](new Student(name, email,


course));
[Link]("/StudentManagemnt/api/list");
}

private void deleteStudent(HttpServletRequest request,


HttpServletResponse response) throws ServletException,
IOException {
int id =
[Link]([Link]("id"));
[Link](id);
[Link]("list");
}

private void editStudentForm(HttpServletRequest request,


HttpServletResponse response) throws ServletException,
IOException{
int id =
[Link]([Link]("id"));

Student existingStudent =
[Link](id);
[Link]("student", existingStudent);

[Link]("/[Link]").for
ward(request, response);
}

private void updateUser(HttpServletRequest request,


HttpServletResponse response) throws ServletException,
IOException {
int id =
[Link]([Link]("id"));
String name = [Link]("name");
String email = [Link]("email");
String course = [Link]("course");

[Link](new Student(id, name,


email, course));
[Link]("list");
}

private void showAllStudent(HttpServletRequest request,


HttpServletResponse response) throws ServletException,
IOException {
List<Student> allStudent =
[Link]();
[Link]("allStudents", allStudent);
[Link]("/[Link]").forward
(request, response);
}

private void showError(HttpServletRequest request,


HttpServletResponse response)throws ServletException,
IOException {
[Link]("/StudentManagemnt/PageNotFoun
[Link]");
}
}
Spring Boot
Why spring:-
Spring makes programming java quicker, easier, and safer for everybody.
Springs focus on speed, simplicity, And productivity has made it the world’ s
most popular java framework.

Feature of Spring:-
[Link] is everywhere
[Link] is flexible
[Link] is protective
[Link] is fast
[Link] is secure
[Link] is supported

What spring can do:-


[Link]
[Link]
[Link]
[Link] app
[Link]
[Link] Driven
[Link]

SpringSpring Boot
Spring is open -source lightweight framework widely used to develop
enterprise application. Spring Boot is built on top of the conventional spring
framework, widely used to develop REST API’s
The most imp feature of the spring framework is dependency [Link]
most important feature of the spring boot is autoconfiguration
Difference between Spring and Spring Boot

Spring Spring Boot

Spring is an open-source lightweight Spring Boot is built on top of the


framework widely used to develop conventional spring framework,
enterprise applications. widely used to develop REST APIs.

The most important feature of the


The most important feature of the
Spring Framework is dependency
Spring Boot is Autoconfiguration.
injection.

It helps to create a loosely coupled It helps to create a stand-alone


application. application.

To run the Spring application, we Spring Boot provides embedded


need to set the server explicitly. servers such as Tomcat and Jetty etc.

To run the Spring application, a There is no requirement for a


deployment descriptor is required. deployment descriptor.

To create a Spring application, the


It reduces the lines of code.
developers write lots of code.

It doesn’t provide support for the It provides support for the in-
in-memory database. memory database such as H2.

Developers need to write In Spring Boot, there is reduction in


boilerplate code for smaller tasks. boilerplate code.
Spring Spring Boot

Developers have to define


[Link] file internally handles the
dependencies manually in the
required dependencies.
[Link] file.

Installation: Help>Eclipse Marketplace>Search Spring>Select Spring


4.24>install
Create Project: File>New>Others>Spring
Run method returns the ConfigurableApplicationContext object and it
acts as spring container
@SpringBootApplication
The @SpringBootApplication annotation is a convenience annotation
that combines the @EnableAutoConfiguration, @Configuration and
the @ComponentScan annotations

● The Main class has the @SpringBootApplication annotation


● It simply invokes the [Link] method. This starts the
spring application as a standalone application, runs the embedded
servers and loads the beans.
● Normally, such a main class is placed in a root package above other
packages. This enables component scanning to scan all the sub-
packages for beans.

Spring core annotations


1. @Component
It indicates that an annotated class is a “spring bean/ component”.
It tells the spring container to automatically create spring bean.
By default spring container give the name to spring bean as a class
name but the first letter of class name in a lowercase.
We can also explicitly give a name to spring bean by passing value.

2. @Autowired
It is used to inject the bean automatically.
It is used in constructor injection, setter injection and field injection.
3. @Qualifier
It is used in conjunction with Autowired to avoid confusion when we
have two or more beans configured for same type.

4. Primary
To give higher preference to a bean when there are multiple beans of
the same type.
5. @Bean
It indicates that a method produces a bean to be managed by the
spring container. It is usually declared in configuration class to create
spring bean definitions.
It is used in java based configuration.
By default spring container will give a name to spring bean as a
method name.
We can give explicitly name by providing value in name attribute.
1. @Component

[Link]

[Link]

package [Link];

import [Link];

//@Component
@Component("pizzacomponent")
public class Pizza {

public String getPizza()


{
return "hot pizza";
}

public String vegPizza()


{
return "Veg Pizza";
}
}

[Link]

package [Link];

import [Link];
import
[Link]
on;
import
[Link]
;

@SpringBootApplication
public class Main {

public static void main(String[] args) {


// TODO Auto-generated method stub

ConfigurableApplicationContext context=
[Link]([Link], args);

//using classname --- [Link]


Pizza pizza=[Link]([Link]);
[Link]([Link]());

//using default name of spring bean -- using


classname
//error will be there since twicely class is
called
Pizza p=(Pizza)[Link]("pizza");
[Link]([Link]());
//using userdefined component
// object=typecast();
Pizza
pz=(Pizza)[Link]("pizzacomponent");
[Link]([Link]());

2. @Autowired

[Link]

Copy [Link] since we are using it

[Link]

package [Link];

import
[Link];
import [Link];

@Component
public class VegPizza {

//using field injection


@Autowired
private Pizza pizza;

public String getVegPizza()


{
return [Link]();
}
}

[Link]

package [Link];

import [Link];
import
[Link]
on;
import
[Link]
;

@SpringBootApplication
public class Main {

public static void main(String[] args) {


// TODO Auto-generated method stub
ConfigurableApplicationContext context=
[Link]([Link], args);

VegPizza pz=[Link]([Link]);

[Link]([Link]());

2. using constructor based injection

//constructor based injection


@Autowired
public VegPizza(Pizza pizza)
{
[Link]=pizza;
}

[Link] setter method

//using setter injection


@Autowired
public void setPizza(Pizza pizza) {
[Link] = pizza;
}

3. @Qualifier : If you have many methods with same interface in bean folder then to prioritize the
class we use qualifier

Interface – [Link]

package [Link];

public interface Burger {

String getBurger();

[Link]

package [Link];

import [Link];

@Component
public class VegBurger implements Burger {

@Override
public String getBurger() {
// TODO Auto-generated method stub
return "You have ordered VEG Burger";
}

[Link]

package [Link];

import [Link];

@Component
public class NonVegBurger implements Burger {

@Override
public String getBurger() {
// TODO Auto-generated method stub
return "You have ordered NON-VEG Burger";
}

[Link]

package [Link];

import
[Link];
import [Link];

@Component
public class BurgerController {

private Burger burger;

// VegBurger is a class but since we are using


@Component vegBurger obj will be created automatically
// public BurgerController(@Qualifier("vegBurger")
Burger burger) {
// super();
// [Link] = burger;
// }

public BurgerController(@Qualifier("nonVegBurger")
Burger burger) {
super();
[Link] = burger;
}

public String getBurger()


{
return [Link]();
}

[Link]

package [Link];

import [Link];
import
[Link]
on;
import
[Link]
;

@SpringBootApplication
public class Main {

public static void main(String[] args) {


// TODO Auto-generated method stub

ConfigurableApplicationContext context=
[Link]([Link], args);

BurgerController
bc=[Link]([Link]);
[Link]([Link]());
}

4. Primary

[Link]

@Component
//will always run this file since it is primary
@Primary
public class VegBurger implements Burger {

@Override
public String getBurger() {
// TODO Auto-generated method stub
return "You have ordered VEG Burger";
}

[Link]

//only for primary annotations


public BurgerController(Burger burger) {
super();
[Link] = burger;
}

API In Spring

[Link]

<?xml version="1.0" encoding="UTF-8"?>


<project
xmlns="[Link]
xmlns:xsi="[Link]
instance"
xsi:schemaLocation="[Link]
rg/POM/4.0.0
[Link]
[Link]">
<modelVersion>4.0.0</modelVersion>
<parent>

<groupId>[Link]</groupI
d>
<artifactId>spring-boot-starter-
parent</artifactId>
<version>3.3.2</version>
<relativePath/> <!-- lookup parent
from repository -->
</parent>
<groupId>[Link]</groupId>
<artifactId>SpringController</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringController</name>
<description>Demo project for Spring
Boot</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<[Link]>21</[Link]>
</properties>
<dependencies>
<dependency>

<groupId>[Link]</groupI
d>
<artifactId>spring-boot-starter-
web</artifactId>
</dependency>

<dependency>

<groupId>[Link]</groupI
d>
<artifactId>spring-boot-starter-
test</artifactId>
<scope>test</scope>
</dependency>

<!--
[Link]
.tomcat/tomcat-jasper -->
<dependency>

<groupId>[Link]</groupId>
<artifactId>tomcat-embed-
jasper</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>

<groupId>[Link]</groupI
d>
<artifactId>spring-boot-maven-
plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

Note : To use jsp we need to compulsory use jasper embed dependency

Demo package

[Link]

package [Link];

import
[Link];
import
[Link]
pping;
import
[Link];
import
[Link];

@Controller
public class WebController {

@GetMapping("/")
public String homefun()
{
return "[Link]";
}

@GetMapping("/employee")
public ModelAndView showemployee(
HttpServletRequest request, ModelAndView mv)
{
Employee emp=new Employee();
[Link]("Spark");
[Link]("spark@[Link]");
// [Link]("employee", emp);
[Link]("[Link]");
[Link]("employee", emp);
return mv;
// return "[Link]";
}
}

[Link]
package [Link];

import
[Link];

@Component
public class Employee {

private String name;


private String email;
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
[Link] = email;
}

Webapp

[Link]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1>Welcome to Home Page</h1>


</body>
</html>

[Link]
<%@ page language="java"
contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Employee</h1>
${[Link]()}
</body>
</html>

Rest API in Spring


Lombok

Stable ([Link])

Download it and install it and restart IDE

Resources - [Link]

[Link]=SpringRestAPI
[Link]=jdbc:mysql://localhost:3306/springdb
[Link]=root
[Link]=

[Link]=[Link]
ect.MySQL8Dialect
[Link]-auto=update
[Link]-sql=true

[Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

@Entity

public class Student {

@Id
@GeneratedValue(strategy = [Link])
private int id;
private String name;
private String email;

public Student() {
super();
// TODO Auto-generated constructors stub
}
public int getId() {
return id;
}
public void setId(int id) {
[Link] = id;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
[Link] = email;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ",
email=" + email + "]";
}

Interface-

[Link]

package [Link];

import [Link];

import
[Link];

// JpaRepository<Student classname , Integer unique


identification of id>
public interface StudentRepository extends
JpaRepository<Student, Integer> {

public Optional< Student> findByEmail(String email);


}

[Link]
package [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@RestController
//change this to @RestController
@RequestMapping("/student")
public class StudentController {

@Autowired
//without using new keyword obj is created using autowired
private StudentRepository studentrepo;
//get all
@GetMapping
public List<Student> getAll()
{
return [Link]();
}
//get by id
@GetMapping("/{id}")
public Optional <Student> getById(@PathVariable int id)
{
return [Link](id);
}
//save student
@PostMapping
public Student saveStudent(@RequestBody Student student)
{
return [Link](student);
}
//delete student
@DeleteMapping("/{id}")
public String deleteStudent(@PathVariable int id)
{
[Link](id);
return "deleted successfully";
}
//update
@PutMapping("/update/{id}")
public Student updateStudent(@RequestBody Student student,@PathVariable int id)
{
Student existingstudent=[Link](id).get();
[Link]([Link]());
[Link]([Link]());
return [Link](existingstudent);
}
}

To run --- Click on [Link] file – run as spring boot

Send enteries from postman


=================================================================================

EmployeeRestAPI

MySQL Project

Model package – [Link]


package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@Entity
@Data
public class Employee {
@Id
@GeneratedValue(strategy = [Link])
private int id;
private String firstName;
private String lastName;
private String mobile;
private String city;
private String designation;

In resource folder – applicationproperties

[Link]=StudentRestAPI
[Link]=jdbc:mysql://localhost:3306/s
pringdb
[Link]=root
[Link]=

[Link]=[Link]
[Link].MySQL8Dialect
[Link]-auto=update
[Link]-sql=true

create package repository

interface – EmployeeRepository

package [Link];

import
[Link]
ry;

import [Link];

public interface EmployeeRepository extends


JpaRepository<Employee, Integer> {

Controller package -- [Link]

package [Link];

import [Link];

import [Link];
import
[Link]
ng;
import
[Link];
import
[Link]
e;
import
[Link]
;
import
[Link];
import
[Link]
;
import
[Link]
ing;
import
[Link]
ler;

import [Link];

@RestController
@RequestMapping("/api/employee")
public class EmployeeController {
@PostMapping
public ResponseEntity<Employee>
saveEmployee(@RequestBody Employee employee)
{
return null;
}
//get all employee
@GetMapping
public ResponseEntity<List<Employee>>
getallEmployee()
{
return null;
}
//get emp by id
@GetMapping("{id}")
public ResponseEntity<Employee>
getEmployeeById(@PathVariable int id)
{
return null;
}
//update emp by id
@PutMapping("{id}")
public ResponseEntity<Employee>
updateEmployeeById(@PathVariable int id)
{
return null;
}
//delete emp by id
@DeleteMapping("{id}")
public ResponseEntity<Employee>
deleteEmployeeById(@PathVariable int id)
{
return null;
}

Exception package

[Link]

package [Link];

import [Link];
import
[Link]
tus;

@ResponseStatus(value=HttpStatus.NOT_FOUND)
public class EmployeeNotFound extends
RuntimeException{
private static final long serialVersionUID = 1L;

public EmployeeNotFound(int id)


{
super("No EMployee Record Found for Id :!"+id);
}
}

Package service— write all interface

EmployeeService

package [Link];

import [Link];

import [Link];

public interface EmployeeService {

List<Employee> getAllEmployee();
Employee getEmployeeById(int id);
Employee addEmployee(Employee employee);
Employee updateEmployeeById(int id, Employee
employee);
void deleteEmployeeById(int id);

Service package—impl package – [Link]

package [Link];

import [Link];
import
[Link]
red;
import [Link];
import [Link];
import [Link];
import [Link];
public class EmployeeServiceimpl implements
EmployeeService {

@Autowired
private EmployeeRepository emprepo;
@Override
public List<Employee> getAllEmployee() {
// TODO Auto-generated method stub
return [Link]();
}

@Override
public Employee getEmployeeById(int id) {
// TODO Auto-generated method stub
return [Link](id).orElseThrow(()-> new
EmployeeNotFound(id));
}

@Override
public Employee addEmployee(Employee employee) {
// TODO Auto-generated method stub
return [Link](employee);
}

@Override
public Employee updateEmployeeById(int id, Employee
employee) {
// TODO Auto-generated method stub
Employee oldEmployee =
[Link](id).orElseThrow(() -> new
EmployeeNotFound(id));
if([Link]() != null) {
[Link]([Link]());
}
if([Link]() != null) {
[Link]([Link]());
}
if([Link]() != null) {
[Link]([Link]());
}
if([Link]() != null) {
[Link]([Link]());
}
if([Link]()!= null) {
[Link]([Link](
));
}
return [Link](oldEmployee);
}

@Override
public void deleteEmployeeById(int id) {
// TODO Auto-generated method stub
[Link](id).orElseThrow(()-> new
EmployeeNotFound(id));
[Link](id);
}

Responsetype package – [Link]

package [Link];

import [Link];
import [Link];

@Data
@AllArgsConstructor
public class SendMessage {
private String message;
}

[Link]

package [Link];

import [Link];

import
[Link]
red;
import [Link];
import [Link];
import [Link];
import
[Link]
ng;
import
[Link];
import
[Link]
e;
import
[Link]
;
import
[Link];
import
[Link]
;
import
[Link]
ing;
import
[Link]
ler;
import [Link];
import [Link];
import [Link];

@RestController
@RequestMapping("/api/employee")
public class EmployeeController {
@Autowired
private EmployeeService empservice;
@PostMapping
public ResponseEntity<Employee>
saveEmployee(@RequestBody Employee employee)
{
Employee saveemp=[Link](employee);
return
[Link]([Link]).body(save
emp);
}
//get all employee
@GetMapping
public ResponseEntity<List<Employee>>
getallEmployee()
{
List <Employee>
employees=[Link]();
return
[Link]([Link]).body(employees
);
}
//get emp by id
@GetMapping("{id}")
public ResponseEntity<Employee>
getEmployeeById(@PathVariable int id)
{
Employee empid=[Link](id);
return
[Link]([Link]).body(empid);
}

//update emp by id
@PutMapping("{id}")
public ResponseEntity<Employee>
updateEmployeeById(@PathVariable int
id,@RequestBody Employee employee)
{
Employee
empupdate=[Link](id,employee
);
return
[Link]([Link]).body(empupdate
);
}
//delete emp by id
@DeleteMapping("{id}")
public ResponseEntity<SendMessage>
deleteEmployeeById(@PathVariable int id)
{ [Link](id);
return
[Link]([Link]).body(new
SendMessage("Employee Deleted Successfully!"));
}

To give the error on the frontend only i.e. minimum error shown

Exception package – [Link]

package [Link];

import [Link];
import [Link];
import
[Link]
ndler;
import
[Link]
lerAdvice;

import [Link];

@RestControllerAdvice
public class AllExceptionHandler {
@ExceptionHandler(value=[Link])
public ResponseEntity<SendMessage>
EmployeeNotFoundException(EmployeeNotFound e)
{
return
[Link](HttpStatus.NOT_FOUND).body(ne
w SendMessage("Employee Not FOund !"));
}

AllExceptionError

Default Exception error

package [Link];

import [Link];
import [Link];
import
[Link]
ndler;
import
[Link]
lerAdvice;
import [Link];

@RestControllerAdvice
public class AllExceptionHandler {
@ExceptionHandler(value=[Link])
public ResponseEntity<SendMessage>
EmployeeNotFoundException(EmployeeNotFound e)
{
return
[Link](HttpStatus.NOT_FOUND).body(ne
w SendMessage("Employee Not FOund !"));
}
@ExceptionHandler(value=[Link])
public ResponseEntity<SendMessage>
Exception(Exception e)
{
return
[Link](HttpStatus.NOT_FOUND).body(ne
w SendMessage("Internal Server Error !"));
}

}
Spring Projects
[Link]

[Link]=BankManagementSystem
[Link]=jdbc:mysql://localhost:3306/b
anking_app
[Link]=root
[Link]=
[Link]=[Link]
[Link].MySQL8Dialect
[Link]-auto=update
[Link]-sql=true

[Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@Getter
@Setter
@Entity
public class Account {

@Id
@GeneratedValue(strategy = [Link])
private Long id;
private String accountHolderName;
private double balance;
}

Create interface

package [Link];

import
[Link]
ry;

public interface AccountRepository extends


JpaRepository<Account, Long> {

Create service

package [Link];

import [Link];

import
[Link]
red;
import [Link];
@Service
public class AccountService {

@Autowired
private AccountRepository accountRepository;

public Account createAccount(Account account) {


return [Link](account);
}

public Optional<Account> getAccount(Long id) {


return [Link](id);
}

public Account deposit(Long id, double amount) {


Account account = getAccount(id).orElseThrow(() ->
new RuntimeException("Account not found"));
[Link]([Link]() + amount);
return [Link](account);
}

public Account withdraw(Long id, double amount) {


Account account = getAccount(id).orElseThrow(() ->
new RuntimeException("Account not found"));
if ([Link]() < amount) {
throw new RuntimeException("Insufficient funds");
}
[Link]([Link]() - amount);
return [Link](account);
}
}

Create restapi

package [Link];
import [Link];

import
[Link]
red;
import
[Link];
import
[Link]
e;
import
[Link]
;
import
[Link]
;
import
[Link]
ing;
import
[Link]
ler;

@RestController
@RequestMapping("/api/accounts")
public class AccountController {
@Autowired
private AccountService accountService;

@PostMapping
public Account createAccount(@RequestBody Account
account) {
return [Link](account);
}

@GetMapping("/{id}")
public Account getAccount(@PathVariable Long id) {
return [Link](id).orElseThrow(()
-> new RuntimeException("Account not found"));
}

@PostMapping("/{id}/deposit")
public Account deposit(@PathVariable Long id,
@RequestBody Map<String, Double> request) {
Double amount = [Link]("amount");
return [Link](id, amount);
}

@PostMapping("/{id}/withdraw")
public Account withdraw(@PathVariable Long id,
@RequestBody Map<String, Double> request) {
Double amount = [Link]("amount");
return [Link](id, amount);
}

Run Main file

Create a db in xamp

Send enteries from postman

[Link] account details


[Link] specific detail
[Link] amount

4. withdraw money

You might also like