Advance Java Notes
Advance Java Notes
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.
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:
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
Finish
The Server pop up window should open and display this.
Create a package in
1.
</form>
</body>
</html>
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@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
[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];
@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>
[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];
[Link]("sum" , Sum);
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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>
.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];
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link]("text/html");
PrintWriter out = [Link]();
}
[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>
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.
Cookies stored data in text file. Session save data in encrypted form.
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];
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];
[Link]("text/html");
PrintWriter out = [Link]();
}
[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];
[Link]("text/html");
PrintWriter out = [Link]();
String n=[Link]("userName");
[Link]("Welcome "+n);
[Link]("cookie2");
[Link]();
}catch(Exception e){[Link](e);}
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[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];
String n=[Link]("userName");
[Link]("Welcome "+n);
[Link]();
}catch(Exception e){[Link](e);}
}
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[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
.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];
[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 :
.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{
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("Welcome to Servlet Annotations");
}
}
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.
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.
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.
• 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.
The scripting elements provide the ability to insert Java code inside the JSP.
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.
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
<html>
<body>
Converting a string to uppercase:
<%=new String("Hello World").toUpperCase()%>
</body>
</html>
2. JSP scriptlets
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
<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]
</body>
</html>
Post method :
Get method:
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]
<%
int
n1=[Link]([Link]("n1"));
int
n2=[Link]([Link]("n2"));
int sum=n1+n2;
[Link]("Addition is :"+sum);
%>
</body>
</html>
[Link]
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]
<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]
6. [Link]
[Link]
[Link]
[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]
<%
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
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.
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.
[Link]
%>
<%
String str = null;
%>
</body>
</html>
[Link]
<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]
</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]" %>
<%
Random random = new Random();
int rd = [Link]();
%>
[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]
<%
String name = [Link]("name");
[Link]("name", name);
[Link]("[Link]");
%>
</body>
</html>
[Link]
[Link] in jsp
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
</form>
</body>
</html>
[Link]
<%
String name = [Link]("name");
String email = [Link]("email");
String city = [Link]("city");
String number = [Link]("number");
%>
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: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:redirect It redirects the browser to a new URL and supports the context-relative URLs.
[Link]
<%
[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>
</body>
</html>
[Link]
using cookies
<h1>Email: ${[Link]}</h1>
</body>
</html>
15. CoreJstltags
<%@ 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>
<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 -->
<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: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);
%>
<%
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: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
<!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]
<!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:trim('str')</h3>
It removes the blank spaces from both the ends
of a string.
<h2>${fn:trim(testStr)}</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
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]
<!-- or -->
</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]
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]");
}
}
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]();
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
[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
[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>
<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];
@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 sp=new
Student(2,"Raj","raj@[Link]","mumbai");
//only once
[Link]();
[Link]();
}
}
In HibernateBasic package
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
Session session=[Link]();
Transaction transaction=[Link]();
In Method package
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
try
{
Session session=[Link]();
Student sp=new
Student(4,"vijay","vijay@[Link]","nagpur");
//persist -- create a persitance state to save
object
[Link](sp);
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
try
{
Session session=[Link]();
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
try
{
Session session=[Link]();
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
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];
@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
@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];
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);
<mapping class="[Link]"></mapping>
Mapping in Hibernate
One to one mapping
Unidirectional
Bidirectional
[Link] Mapping
Unidirectional
[Link]—bean folder
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@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 {
public EmployeeAddress() {
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "EmployeeAddress [id=" + id + ", address=" +
address + "]";
}
}
[Link] – [Link] package
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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]();
[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]
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]
.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
}
@Override
public String toString() {
return "StudentDetails [id=" + id + ", name=" + name + ",
address=" + 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
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
StudentDetails st=new
StudentDetails(1,"Kartiki",list);
// ==================bidirectional data
===========================
[Link](st);
[Link](st);
[Link](ad1);
[Link](ad2);
[Link](st);
[Link]();
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
}
[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
}
@Override
public String toString() {
return "WorkerAddress [id=" + id + ", address=" +
address + ", details=" + details + "]";
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
Session session=[Link]();
WorkerAddress wa1=new
WorkerAddress(1,"Pune");
WorkerAddress wa2=new
WorkerAddress(2,"Mumbai");
[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>
********************************************************************************
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.
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
}
@Override
public String toString() {
return "StudentHQL [id=" + id + ", name=" + name + ",
address=" + address + "]";
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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);
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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);
for(StudentHQL student:students4)
{
[Link](student);
}
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 {
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];
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>
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 hashPassword =
[Link](password);
// [Link](emp);
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);
}
}
package [Link];
import [Link];
return hashedPassword;
}
package [Link];
import [Link];
import [Link];
import [Link];
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>
[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>
<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>
<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]"%>
</c:if>
<c:if test="${student != null}">
<h1>Update Student</h1>
<form action="api/update" method="post">
<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>
</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]" %>
[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]
<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>
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
try {
[Link](driver);
con = [Link](url, username,
password);
} catch (Exception e) {
[Link]();
}
return con;
}
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;
}
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;
}
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;
}
return rowDeleted;
}
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;
}
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;
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 {
[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{
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;
}
}
Student existingStudent =
[Link](id);
[Link]("student", existingStudent);
[Link]("/[Link]").for
ward(request, response);
}
Feature of Spring:-
[Link] is everywhere
[Link] is flexible
[Link] is protective
[Link] is fast
[Link] is secure
[Link] is supported
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
It doesn’t provide support for the It provides support for the in-
in-memory database. memory database such as H2.
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 {
[Link]
package [Link];
import [Link];
import
[Link]
on;
import
[Link]
;
@SpringBootApplication
public class Main {
ConfigurableApplicationContext context=
[Link]([Link], args);
2. @Autowired
[Link]
[Link]
package [Link];
import
[Link];
import [Link];
@Component
public class VegPizza {
[Link]
package [Link];
import [Link];
import
[Link]
on;
import
[Link]
;
@SpringBootApplication
public class Main {
VegPizza pz=[Link]([Link]);
[Link]([Link]());
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];
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 {
public BurgerController(@Qualifier("nonVegBurger")
Burger burger) {
super();
[Link] = burger;
}
[Link]
package [Link];
import [Link];
import
[Link]
on;
import
[Link]
;
@SpringBootApplication
public class Main {
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]
API In Spring
[Link]
<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>
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 {
Webapp
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
[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>
Stable ([Link])
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
@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];
[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);
}
}
EmployeeRestAPI
MySQL Project
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;
[Link]=StudentRestAPI
[Link]=jdbc:mysql://localhost:3306/s
pringdb
[Link]=root
[Link]=
[Link]=[Link]
[Link].MySQL8Dialect
[Link]-auto=update
[Link]-sql=true
interface – EmployeeRepository
package [Link];
import
[Link]
ry;
import [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;
EmployeeService
package [Link];
import [Link];
import [Link];
List<Employee> getAllEmployee();
Employee getEmployeeById(int id);
Employee addEmployee(Employee employee);
Employee updateEmployeeById(int id, Employee
employee);
void deleteEmployeeById(int id);
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);
}
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
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
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;
Create service
package [Link];
import [Link];
import
[Link]
red;
import [Link];
@Service
public class AccountService {
@Autowired
private AccountRepository accountRepository;
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);
}
Create a db in xamp
4. withdraw money