Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
75 views91 pages

Servlet JSP

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views91 pages

Servlet JSP

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 91

Servlet

Web Component
|
|-- Servlet
|
|-- JSP

JAVA SE (JAVA Standard Edition)


+ Console Application Window Application

JAVA EE (Enterprise Application)


+ Web Application

+ Servlet JSP

Web Server
---------
+ Apache Tomcat

Web Server= WebContainer + Extra Services

Example:
Tomcat Enhydra Lotus etc

Download
------------
+ https://tomcat.apache.org/download-90.cgi
After Download Extract it

+++++++++++++++++++++++++

Make Sure Eclipse has Java EE plugin

if not

1: Go TO Google JAVA EE Download

2: Click On Eclipse open it


Go To TAB HELP
Inside HELP --> ECLIPSE MARKETPLACE
AND Search --> JAVA EE

find --> Eclipse Enterprise JAVA And Web Developer

-------------------------------------------------------------
----------------

Apache Tomcat
-------------
bin --> scripts to start server and stop server
conf --> contains xml file contains configuration of web server
lib --> libraries [a lot jar files] [what is jar---> java archive file ]
logs --> for maintaining logs
temp --> for temp files
webapps --> Hot deployment directory -- where web application deployed
work --> associated with jsp file
+++++++++++++++++++++++++++

1: Add Server to Your Eclipse Workspace

2: Just Click On Open Perspective

3: Select JAVA EE

4:Then You will find below server Tab(previously console )

5:Click On IT

6:[You Will Get Message No Server Click To ADD]

7:Click ON IT Select Proper Apache Tomcat Version (That You have


Downloaded)

8:And Just Browse And Select Folder Name

9:Confirm

-------------------------------------------------------------
------

What is a web application?

+ Collection of web pages.

+ Web pages can be static (HTML) or dynamic (servlet/jsp)


HTTP Request
--------------------------

from Browser to server

http://servername:portNo/app/webpage

for ex==> http://localhost:8080/MyFirstApp/hello.html

Request Content:
----------------------
1: Server Name & port no --> localhost 8080

2:Request Identifier --> /appName/webpage for ex


MyFirstApp/hello.html

3:Request Method --> GET / POST

4:Request Length

5:Request Header ---> (info about client (Browser))

6: Cookies

7:Request Body

HTTP Response
--------------

From Server to Browser


Response Contents:

1: Resp Status Code [404 ,403,200,500 etc ]

2: Content Type --> text/html image/png audio/mp3 etc

3: Response Length

4: Response Header (info about the server)

5: Cookies

6: Response Body

------------------------------------------------
HTTP Request Method

1: GET

2: POST

Q Diff between get and post?

GET POST

Limited Data UNLIMITED DATA

NOT SECURE SECURE

data is sent via data is sent via req body


url
-------------------------------------------------------------
---

Servlet(I)

Servlet
------

Servlet is a java class ,which is executed within web container when client
makes request and it generates response is sent to the client

interface javax.servlet.Servlet{

void init(ServletConfig config)

void service(ServletRequest req,ServletResponse resp)


void destroy()

public ServletConfig getServletConfig()

public String getServletInfo()

Example
--------

MyServlet.java
------------------
package pack;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class MyServlet implements Servlet {

@Override
public void destroy() {
System.out.println("Destroy Method Executes");
}

@Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}

@Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}

@Override
public void init(ServletConfig config) throws ServletException {

System.out.println("init First Executes");

@Override
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException {

System.out.println("Service Executes");

--------------------------

HOW TO REGISTER SERVLET


-------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>MyFirstApp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<servlet>

<servlet-name>MyServlet</servlet-name>
<servlet-class>pack.MyServlet</servlet-class>

</servlet>

<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/visit</url-pattern>
</servlet-mapping>

</web-app>

-------------------------------------------------
void init(ServletConfig config)

+ For the first request from the client , web container loads servlet class
in
a memory and creates its Object

+ Immediately init() method called

(only once called in life cycle of Servlet)

void service(Servletrequest req,ServletResponse res)

For each request web container calls service() method

void destroy()

When Servlet Object is no longer needed or server is shutdown


at this time destroy method calls
(only once called in life cycle of Servlet)

--------------------------------------------------------

1: By using interface javax.servlet.Servlet.

2: By using abstract class GenericServlet.

3: By using class HTTPServlet

--------------------------------------------------
Example

Form.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="FirstServlet" method="get">

Name: <input type="text" name="uname">

<input type="submit" value="OK">

</form>

</body>
</html>

++++++++++++++++++++++++++++++++++++

package p1;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class FirstServlet
*/
@WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public FirstServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

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

String n=request.getParameter("uname");
out.print("<h1>");
out.print(n.toUpperCase());
out.print("</h1>");
}

++++++++++++++++++++++++++++++++++++
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>SecondApp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

All Form Fields

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="ReadData" method="get">


<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>

<label for="cars">Choose a car:</label>


<select id="cars" name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>

<br>
Languages:
<br>
<input type="radio" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label>

<br>
Belonging :
<br>
<input type="checkbox" id="vehicle1" name="vehicle" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle" value="Boat">
<label for="vehicle3"> I have a boat</label>

<br>
Comment BOX:
<br>
<textarea name="message" rows="7" cols="20">
The cat was playing in the garden.
</textarea>
<br>
<input type="submit" value="Submit">
<input type="reset">
</form>

</body>
</html>

++++++++++++++++++++++++++++++

package p1;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

public ReadData() {
super();
// TODO Auto-generated constructor stub
}

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

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

out.print("<body>");
out.print("<b> Name "+ request.getParameter("fname")+" </b> <br>");
out.print("<b> Last Name "+ request.getParameter("lname")+" </b> <br>");
out.print("<b> CARS "+ request.getParameter("cars")+" </b> <br>");
out.print("<b> FAV Language "+ request.getParameter("fav_language")+"
</b> <br>");
out.print("<b> Message "+ request.getParameter("message")+" </b> <br>");

out.print("Vechiles : <br>");
String vechile[]=request.getParameterValues("vehicle");

for (String string : vechile) {


out.print(" "+string+" <br>");
}

out.print("</body>");

}
++++++++++++++++++++++++++++++++++++++++++++

BOOK Project

Model

package model;
// Bean Class Entity Model class POJO
public class Book {
private int id;
private String name;
private double price;

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

public Book(int id, String name, double price) {


super();
this.id = id;
this.name = name;
this.price = price;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}
public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


this.price = price;
}

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

+++++++++++++++++++++++++++++
Html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="InsertData" method="get">

Book ID : <input type="text" name="bid"> <br>


Book Name: <input type="text" name="bname"> <br>
Book Price: <input type="text" name="bprice"><br>
<input type="submit" value="Save">

</form>

</body>
</html>

++++++++++++++++++

Utility

package utility;
import java.sql.Connection;
import java.sql.DriverManager;

public class DBUtilities {

public Connection getDBConnection() {


Connection con=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/junejuly",
"root", "root");
}catch (Exception e) {
// TODO: handle exception
}

return con;
}
}

++++++++++++++++++++++++

InsertServlet
controller

package controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BookDAO;
import model.Book;

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

BookDAO dao;
@Override
public void init() throws ServletException {

dao=new BookDAO();

public InsertData() {

}
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();

String id=request.getParameter("bid");
int bId=Integer.parseInt(id);
String name=request.getParameter("bname");
String price=request.getParameter("bprice");
double bPrice=Double.parseDouble(price);

Book book=new Book(bId, name, bPrice);

int i=dao.insertBook(book);

++++++++++++++++++++++++++++++

Dao

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import model.Book;
import utility.DBUtilities;

public class BookDAO {


DBUtilities db = new DBUtilities();

public int insertBook(Book book) {


int i = 0;
Connection con = db.getDBConnection();
String sql = "insert into book values(?,?,?)";
try {
PreparedStatement ps = con.prepareStatement(sql);

ps.setInt(1, book.getId());
ps.setString(2, book.getName());
ps.setDouble(3, book.getPrice());

i = ps.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
}
if (i >= 1) {
return 1;
} else {
return 0;
}

public int deleteBook(Book book) {


int i = 0;
Connection con = db.getDBConnection();
String sql = "delete from book where id=?";
try {
PreparedStatement ps = con.prepareStatement(sql);

ps.setInt(1, book.getId());

i = ps.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
}
if (i >= 1) {
return 1;
} else {
return 0;
}

public int updateBook(Book book) {


int i = 0;
Connection con = db.getDBConnection();
String sql = "update book set name=? , price=? where id=?";
try {
PreparedStatement ps = con.prepareStatement(sql);

ps.setInt(3, book.getId());
ps.setString(1, book.getName());
ps.setDouble(2, book.getPrice());

i = ps.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
}
if (i >= 1) {
return 1;
} else {
return 0;
}
}

public List<Book> getAllBooks() {

ArrayList<Book> list = new ArrayList<Book>();


Connection con = db.getDBConnection();
String sql = "Select * from book";

try {
PreparedStatement ps = con.prepareStatement(sql);

ResultSet rs = ps.executeQuery();

while (rs.next()) {
Book book = new Book();
book.setId(rs.getInt(1));
book.setName(rs.getString(2));
book.setPrice(rs.getDouble(3));

list.add(book);
}

rs.close();
} catch (Exception e) {
// TODO: handle exception
}

return list;
}

}
+++++++++++++++++++++++++++++++++

RequestDispatcher(I)
---------------------

forward()
include()
------------------------------------------
Methods of RequestDispatcher interface
The RequestDispatcher interface provides two methods. They are:

public void forward(ServletRequest request,ServletResponse response)throws


ServletException,java.io.IOException

:Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file)
on the server.

public void include(ServletRequest request,ServletResponse response)throws


ServletException,java.io.IOException:

Includes the content of a resource (servlet, JSP page, or HTML file) in the response.
-------------------------------------------------------------------------

RequestDispatcher(I)

// RequestDispatcher
RequestDispatcher rd=request.getRequestDispatcher("SecondServlet");

rd.include(request, response);
ServletConfig And ServletContext
package p1;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class First
*/
//@WebServlet("/First")
public class First extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public First() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {

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

ServletConfig config=getServletConfig();

String mob=config.getInitParameter("mobile");

pw.print(mob+"<br>");

ServletContext context=getServletContext();
String value=context.getInitParameter("fruit");
pw.print(value);

+++++++++++++++++++
Web.xml

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


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
id="WebApp_ID" version="4.0">
<display-name>ServletConfigDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<context-param>
<param-name>fruit</param-name>
<param-value>Mango</param-value>

</context-param>

<servlet>
<servlet-name>First</servlet-name>
<servlet-class>p1.First</servlet-class>

<init-param>
<param-name>mobile</param-name>
<param-value>123456789</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>First</servlet-name>
<url-pattern>/First</url-pattern>

</servlet-mapping>

</web-app>

NOTE

ServletConfig (I)
--------------------------------

+ In Order to access values as init param form web.xml then will use
ServletConfig

+ How To read it

1: ServletConfig config=getServletConfig();
// Here We are Getting Servet Config Object

2: String value=config.getInitParameter("anykey");

Remember one Thing ServletConfig Object is created for FirstServlet

ServletContex (I)
-------------------
1: This Object is created only once and this Object is Singleton

In Web.xml

How To Define Context Param

<context-param>

<param-name>language</param-name>
<param-value>java</param-value>
</context-param>

+ How To Use This Param Name and Value among(multiple Servlet)

ServletContext context=getServletContext();

String name=context.getInitParameter("language");

// Basically If we want to share among multiple Servlet

Q What is Diff Between ServletConfig And ServletContext

1: For ServletConfig multiple Object are created

2: For ServletContext only one Object are created

++++++++++++++++++++++++++++++++++++++++++++++++

out.print("<form action='UpdateData'>");

out.print("ID: <input type='hidden' name='id' value="+book.getId()+"><br>");


out.print("NAME : <input type='text' name='name' value="+book.getName()+"><br>");

out.print("PRICE: <input type='text' name='price' value="+book.getPrice()+"><br>");

out.print("<input type='submit' value='UPDATE'" + ">");

out.print("</form>")

++++++++++++++++++++++++++++++++++++++++++++++++++++++++

JSP

JSP
-------------------

SERVLET
[Servlet is used to create dynamic web page Basically Servlet is java class]

[JAVA CODE + HTML]

JAVA SERVER PAGES

HTML + JAVA CODE

JSP differentiate presentation logic and business logic

Generally we write presentation logic in jsp

And Business logic in Servlet

Scriptlet Tag

<% %>

Expression
<%= %>

Declaration Tag

<%! %>

EX NO 1:

<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<h1 style="color: blue;font-family: cursive;">


<%
out.print("Hello JSP");
%>

<br>
DATE:
<% out.print(new Date()); %>

</h1>

<hr>

<% String name="JAVA"; %>

<h2 style="color: gray">


<%= name %>

<hr>

<%! int x=11; %>

<%=x %>
</h2>

</body>
</html>

LIFE CYCLE OF JSP


INPUT

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="form.jsp" method="get">

Name : <input type="text" name="uname"> <br>

LastName : <input type="text" name="lname"> <br>

<input type="submit" value="CLICK">

</form>

</body>
</html>

+++++++++++++++
Form.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<%
String name=request.getParameter("uname");
String lName=request.getParameter("lname");
%>

<h3>
<%= name+" "+lName %>
</h3>

</body>
</html>

<%
request.getRequestDispatcher("show.jsp").include(request,
response); %>

++++++++++++++++++++++++

Scope

Index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="form.jsp" method="get">

Name : <input type="text" name="uname"> <br>

LastName : <input type="text" name="lname"> <br>

<input type="submit" value="CLICK">

</form>

</body>
</html>

++++++++++++++

From.jsp

<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<%
String name = request.getParameter("uname");
String lName = request.getParameter("lname");
%>

<h3>
<%=name + " " + lName%>
</h3>

<%
ArrayList<String> list = new ArrayList<String>();
list.add("HI");
list.add("BYE");
list.add("COOL");

request.setAttribute("words", list);
%>

<%
request.getRequestDispatcher("show.jsp").forward(request, response);
%>

</body>
</html>

+++++++++++++++
Show.jsp

<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="green">

<h1>SHOW PAGE</h1>

<%
ArrayList<String> list=(ArrayList<String>)request.getAttribute("words"); %>

<%
for(String val : list){
out.print(val);
%>
<br>
<% }
%>

</body>
</html>

Following MVC Design Pattern


Book APP

—------------------------

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="InsertData" method="get">

Book ID : <input type="text" name="bid"> <br>


Book Name: <input type="text" name="bname"> <br>
Book Price: <input type="text" name="bprice"><br>
<input type="submit" value="Save">

</form>

</body>
</html>

++++++++++++++++++++++++++++++++++++

InserData

package controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BookDAO;
import model.Book;

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

BookDAO dao;
@Override
public void init() throws ServletException {

dao=new BookDAO();

public InsertData() {

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();

String id=request.getParameter("bid");
int bId=Integer.parseInt(id);
String name=request.getParameter("bname");
String price=request.getParameter("bprice");
double bPrice=Double.parseDouble(price);

Book book=new Book(bId, name, bPrice);

int i=dao.insertBook(book);
if(i>=1) {
out.print("<h2> BOOK ADDED SUCCES !!! </h2>");
request.getRequestDispatcher("view.jsp").include(request,
response);
}

+++++++++++++++++++++++++++

View.jsp

<%@page import="java.util.Iterator"%>
<%@page import="model.Book"%>
<%@page import="java.util.List"%>
<%@page import="dao.BookDAO"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid white;
border-collapse: collapse;
}
th, td {
background-color: #96D4D4;
}
</style>
</head>
<body>
<%!BookDAO dao = null;

public void init() throws ServletException {

dao = new BookDAO();


}%>

<%
List<Book> listBooks = dao.getAllBooks();
%>

<table style="width:100%">
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>DELETE</th>
<th>UPDATE</th>
</tr>

<%
Iterator<Book> itr = listBooks.iterator();
while (itr.hasNext()) {
Book book = itr.next();

%>
<tr>
<td><%=book.getId()%></td>
<td><%=book.getName()%></td>
<td><%=book.getPrice()%></td>
<td><a href="DeleteData?id="<%book.getId();%>>Delete</a></td>
<td><a href="UpdateData">Update</a></td>
<tr>

<%
}
%>
</table>
</body>
</html>

+++++++++++++++++++++++++++++++++
Model

package model;
// Bean Class Entity Model class POJO
public class Book {
private int id;
private String name;
private double price;

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

public Book(int id, String name, double price) {


super();
this.id = id;
this.name = name;
this.price = price;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


this.price = price;
}

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

+++++++++++++++++++++++++++++++

Dao

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import model.Book;
import utility.DBUtilities;

public class BookDAO {


DBUtilities db = new DBUtilities();

public int insertBook(Book book) {


int i = 0;
Connection con = db.getDBConnection();
String sql = "insert into book values(?,?,?)";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, book.getId());
ps.setString(2, book.getName());
ps.setDouble(3, book.getPrice());

i = ps.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
}
if (i >= 1) {
return 1;
} else {
return 0;
}

public int deleteBook(Book book) {


int i = 0;
Connection con = db.getDBConnection();
String sql = "delete from book where id=?";
try {
PreparedStatement ps = con.prepareStatement(sql);

ps.setInt(1, book.getId());

i = ps.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
}
if (i >= 1) {
return 1;
} else {
return 0;
}

public int updateBook(Book book) {


int i = 0;
Connection con = db.getDBConnection();
String sql = "update book set name=? , price=? where id=?";
try {
PreparedStatement ps = con.prepareStatement(sql);

ps.setInt(3, book.getId());
ps.setString(1, book.getName());
ps.setDouble(2, book.getPrice());

i = ps.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
}
if (i >= 1) {
return 1;
} else {
return 0;
}

public List<Book> getAllBooks() {

ArrayList<Book> list = new ArrayList<Book>();


Connection con = db.getDBConnection();
String sql = "Select * from book";

try {
PreparedStatement ps = con.prepareStatement(sql);

ResultSet rs = ps.executeQuery();

while (rs.next()) {
Book book = new Book();
book.setId(rs.getInt(1));
book.setName(rs.getString(2));
book.setPrice(rs.getDouble(3));
list.add(book);
}

rs.close();
} catch (Exception e) {
// TODO: handle exception
}

return list;
}

public Book getBookById(int id) {


Connection con = db.getDBConnection();
String sql = "Select * from book where id=?";
Book book = new Book();
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, id);

ResultSet rs = ps.executeQuery();

while (rs.next()) {

book.setId(rs.getInt(1));
book.setName(rs.getString(2));
book.setPrice(rs.getDouble(3));
}
rs.close();
} catch (Exception e) {
// TODO: handle exception
}
return book;
}

+++++++++++++++++++++++++++++++++
DeleteServlet

package controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class DeleteData
*/
@WebServlet("/DeleteData")
public class DeleteData extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public DeleteData() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {

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

System.out.println("======>"+id);
}

+++++++++++++++++++++++++++++++

Utilities

package utility;
import java.sql.Connection;
import java.sql.DriverManager;

public class DBUtilities {

public Connection getDBConnection() {


Connection con=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bookdetails",
"root", "root");
}catch (Exception e) {
// TODO: handle exception
}

return con;
}

+++++++++++++++++++++++++++++++++

JSP ACTION Element


jsp:forward
Ex No 1:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1> In ONE JSP PAGE</h1>

<jsp:forward page="two.jsp"></jsp:forward>
</body>
</html>

+++++++++++++++++

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<h1> In TWO JSP PAGE</h1>

</body>
</html>

Ex No 2:
jsp:include

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1> In ONE JSP PAGE</h1>

<jsp:include page="two.jsp"></jsp:include>

</body>
</html>

+++++++++++++++++

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<h1> In TWO JSP PAGE</h1>

</body>
</html>
++++++++++++++++++++++++++++++++++++++++

<jsp:usebean id=”objName” class=”package.className”>


<jsp:setProperty property=”classfield” name=”objName” param=”dabbaName”?
<jsp:getProperty property=”classfield” name=”objName”>

Ex

package model;

import java.io.Serializable;

// JAVA BEAN CLASS


// A class which has private fields Setter Getter Default Constructor
// And implements Serilizable called as JAVA BEAN CLASS

// Hibernate --> Entity Class Domain Class


// Spring --> Spring Bean POJO class Plain Old JAVA OBJECT

public class CapBean implements Serializable {

private String word;

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

public String getWord() {


return word;
}

public void setWord(String word) {


this.word = word;
}

public String getCapital() {


return word.toUpperCase();
}

@Override
public String toString() {
return "CapBean [word=" + word + "]";
}

++++++++++

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="action.jsp" method="get">

Word : <input type="text" name="inword"> <br>

<input type="submit" value="CLICK">


</form>

</body>
</html>

++++++++++++++++++=
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="model.CapBean" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<jsp:useBean id="bean" class="model.CapBean"></jsp:useBean>

<jsp:setProperty property="word" name="bean" param="inword"/>

<h2>
<jsp:getProperty property="word" name="bean"/>
</h2>
<br>

<h2>
<%= bean.getCapital() %>
</h2>
</body>
</html>

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
NOTES
Difference between RequestDispatcher and SendRedirect

SendRedirect
● This is the method of object HttpServletResponse.
● Request is redirected to the client (Browser), and it will process the new
URL.
● End User can see on which page, url is redirected.
● In Nutshell, Processing done at client side.

RequestDispatcher
● This object can be accessed from HttpServletRequest.
● Servlet will internally forward the request to another servlet or jsp page.
● End user doesn't know which page is processed internally.
● In Nutshell, Processing done at server side.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Sate Management
—----------------

Every request treats as new Request so we need to maintain state of


client(browser)

State Management
-------------------

Client Side State Management:

+ the state/info of client is stored on client machine

+ less secure

+ Ways --> Cookie , QueryString (URL Rewriting ), hidden form fields

Server Side State Management:


------------------------------

+ the state/info of client is stored on server machine

+ it requires space

+ More secure

+ Ways --> Session

------------------------------------------------------------------

Cookie
----------

+ To store info of clients .


+ Cookie can store only text data up to max 4 KB

+ Cookie information stored in Key-Value Format

Cookie Type
------------

+ Temporary Cookie

cookie is stored in browser memory and will be destroyed when


browser close

+ Persistent Cookie

cookie is stored in browser memory (client machine) as text file and


will be persist even if browser close

javax.servlet.http.Cookie{

Cookie(String name,String val);

}
--------------------------------

How To Create Cookie

Cookie ck=new Cookie("Key","Value"); // Cookie create

response.addCookie(ck); //

---------------------------------------------

How to get Cookies?


Cookie ck[]=request.getCookies();

for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of
cookie
}

—-----------------------------------------------------

How to delete Cookie?

Cookie ck=new Cookie("user","");//deleting value of cookie

ck.setMaxAge(0);//changing the maximum age to 0 seconds

response.addCookie(ck);//adding cookie in the response

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="login.jsp" >

User Name : <input type="text" name="uname"> <br>


Password : <input type="text" name="pass"> <br>

<input type="submit" value="Login">

</form>

</body>
</html>

++++++++++++++++++++

Login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1" autoFlush="false" buffer="8kb"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<b style="font-family: fantasy;color: blue; font-size: large;">
<a href="index.html"> Login</a> &nbsp;&nbsp;
<a href="profile.jsp"> Profile</a>&nbsp;&nbsp;
<a href="logout.jsp"> LogOut</a>&nbsp;&nbsp;
</b>

<br>
<%
String name=request.getParameter("uname");
String pass=request.getParameter("pass");
out.print(name);
out.print(pass);
%>
<br>
<h1>
<% if(pass.equals("123")){

out.print("Welcome "+name);
Cookie ck=new Cookie("ckid",name);
response.addCookie(ck);
}
else{
out.print("Invalid Password !!! "+request.getContextPath());
%>

<jsp:include page="index.html"></jsp:include>
<%
}
%>
</h1>

</body>
</html>

+++++++++++++++++++++++++++++++++++++

Profile.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<b style="font-family: fantasy;color: blue;">


<a href="index.html"> Login</a> &nbsp;&nbsp;
<a href="profile.jsp"> Profile</a>&nbsp;&nbsp;
<a href="logout.jsp"> LogOut</a>&nbsp;&nbsp;
</b>

<h1>
<%
boolean flag=false;
Cookie ck[]=request.getCookies();

if(ck!= null){

for(int i=0;i<ck.length;i++){

if(ck[i].getName().equals("ckid") && !(ck[i].getValue().equals("")) &&


(ck[i].getValue()!=null))
{
out.print("Welcome To Profile " +ck[i].getValue());
flag=true;
break;
}
}

if(flag){

}
else{
out.print("Session Expires Please Relogin Again !!!!!");
%>

<jsp:include page="index.html"></jsp:include>
<%}
}
%>
</h1>

</body>
</html>

++++++++++++++++++++++++++++++++++++++++++++++++
Logout.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<b style="font-family: fantasy;color: blue;">


<a href="index.html"> Login</a> &nbsp;&nbsp;
<a href="profile.jsp"> Profile</a>&nbsp;&nbsp;
<a href="logout.jsp"> LogOut</a>&nbsp;&nbsp;
</b>

<h3 style="align-content: center;">YOU ARE SUCESSFULLY LOGOUT</h3>

<%
Cookie ck=new Cookie("ckid","");
ck.setMaxAge(0);
response.addCookie(ck);
%>

</body>
</html>

+++++++++++++++++++++++++++++++++++++++

Question
1) How many objects of a servlet is created?

2) What is the life-cycle of a servlet?


Servlet is loaded
servlet is instantiated
servlet is initialized
service the request
servlet is destroyed

3) What are the life-cycle methods for a servlet?


Method Description
public void init(ServletConfig config) It is invoked only once when first request
comes for the servlet. It is used to initialize the servlet.
public void service(ServletRequest request,ServletResponse)throws
ServletException,IOException It is invoked at each request.The service()
method is used to service the request.
public void destroy() It is invoked only once when servlet is unloaded.

4) Who is responsible to create the object of servlet?


The web container or servlet container.

5) When servlet object is created?


At the time of first request.

6) What is difference between Get and Post method?


Get Post
1) Limited amount of data can be sent because data is sent in header. Large
amount of data can be sent because data is sent in body.
2) Not Secured because data is exposed in URL bar. Secured because data is not
exposed in URL bar.
3) Can be bookmarked Cannot be bookmarked
4) Idempotent Non-Idempotent
5) It is more efficient and used than Post It is less efficient and used
7) What is difference between PrintWriter and ServletOutputStream?
PrintWriter is a character-stream class where as ServletOutputStream is a byte-
stream class. The PrintWriter class can be used to write only character-based
information whereas ServletOutputStream class can be used to write primitive
values as well as character-based information.

8) What is difference between GenericServlet and HttpServlet?


The GenericServlet is protocol independent whereas HttpServlet is HTTP protocol
specific. HttpServlet provides additional functionalities such as state management
etc.

9) What is servlet collaboration?


When one servlet communicates to another servlet, it is known as servlet
collaboration. There are many ways of servlet collaboration:

RequestDispacher interface
sendRedirect() method etc.

10) What is the purpose of RequestDispatcher Interface?


The RequestDispacher interface provides the facility of dispatching the request to
another resource it may be html, servlet or jsp. This interceptor can also be used
to include the content of antoher resource.

11) Can you call a jsp from the servlet?


Yes, one of the way is RequestDispatcher interface for example:

RequestDispatcher rd=request.getRequestDispatcher("/login.jsp");
rd.forward(request,response);

12) Difference between forward() method and sendRedirect() method ?


forward() method sendRedirect() method
1) forward() sends the same request to another resource. 1) sendRedirect()
method sends new request always because it uses the URL bar of the browser.
2) forward() method works at server side. 2) sendRedirect() method works at
client side.
3) forward() method works within the server only. 3) sendRedirect() method
works within and outside the server.
13) What is difference between ServletConfig and ServletContext?
The container creates object of ServletConfig for each servlet whereas object of
ServletContext is created for each web application.

14) What is Session Tracking?


Session simply means a particular interval of time.

Session Tracking is a way to maintain state of an user.Http protocol is a stateless


protocol.Each time user requests to the server, server treats the request as the
new request.So we need to maintain the state of an user to recognize to particular
user.

15) What are Cookies?


A cookie is a small piece of information that is persisted between the multiple
client requests. A cookie has a name, a single value, and optional attributes such
as a comment, path and domain qualifiers, a maximum age, and a version number.

16) What is difference between Cookies and HttpSession?


Cookie works at client side whereas HttpSession works at server side.

17) What is filter?


A filter is an object that is invoked either at the preprocessing or postprocessing
of a request. It is pluggable.

18) How can we perform any action at the time of deploying the project?
By the help of ServletContextListener interface.

19) What is the disadvantage of cookies?


It will not work if cookie is disabled from the browser.

20) How can we upload the file to the server using servlet?
One of the way is by MultipartRequest class provided by third party.

21) What is load-on-startup in servlet?


The load-on-startup element of servlet in web.xml is used to load the servlet at
the time of deploying the project or server start. So it saves time for the
response of first request.

22) What if we pass negative value in load-on-startup?


It will not affect the container, now servlet will be loaded at first request.

23) What is war file?


A war (web archive) file specifies the web elements. A servlet or jsp project can
be converted into a war file. Moving one servlet project from one place to another
will be fast as it is combined into a single file.

24) How to create war file?


The war file can be created using jar tool found in jdk/bin directory. If you are
using Eclipse or Netbeans IDE, you can export your project as a war file.

To create war file from console, you can write following code.

jar -cvf abc.war *


Now all the files of current directory will be converted into abc.war file.

25) What are the annotations used in Servlet 3?


There are mainly 3 annotations used for the servlet.

@WebServlet : for servlet class.


@WebListener : for listener class.
@WebFilter : for filter class.
26) Which event is fired at the time of project deployment and undeployment?
ServletContextEvent.

27) Which event is fired at the time of session creation and destroy?
HttpSessionEvent.
28) Which event is fired at the time of setting, getting or removing attribute
from application scope?
ServletContextAttributeEvent.

29) What is the use of welcome-file-list?


It is used to specify the welcome file for the project.

30) What is the use of attribute in servlets?


Attribute is a map object that can be used to set, get or remove in request,
session or application scope. It is mainly used to share information between one
servlet to another.

++++++++++++++++++++++++++++++++++++++++++++++

HiddenFormField
JSP EL

JSP EL

The Expression Language (EL) simplifies the accessibility of data stored in the Java
Bean component, and other objects like request, session, application etc.

Syntax for Expression Language (EL)

${ expression }

Three Scope

Request
Session
Application (Servlet Context)

JSP EL (Expression Language)

<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" session="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<% request.setAttribute("name", "Kalpesh"); %>

Request Scope = <%= (String)request.getAttribute("name") %>

<hr>
<h2>
${ requestScope.name }
</h2>

<% session.setAttribute("sessionid", "123456"); %>

<% ArrayList<Integer>list=new ArrayList<Integer>();


list.add(11);list.add(22);list.add(33);list.add(44);list.add(55);

%>
<% application.setAttribute("list", list); %>

<hr>

<h2>
<a href="process.jsp"> Process</a>
</h2>

</body>
</html>

++++++++++++++++++++++++++++++
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" session="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<h3>Session Value : ${sessionScope.sessionid }</h3>

<br>
<h2>Application Scope : ${applicationScope.list }</h2>
</body>
</html>

+++++++++++++++++++++++++++++++

JSTL

JSTL
---------------------------

To use jstl we need jstl jar

https://mvnrepository.com/artifact/javax.servlet/jstl/1.2
1 step to use jstl download jstl jar

2 Create Dynamic web Project

3: ADD jstl jar in lib folder (make sure jar must be extract (not a zip))

4: Create JSP Page Add page taglib

In Order to use taglib add into jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

5: USE JSTL TAGS

+++++++++++++++++++++

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>JSTL</h1>

<br>

<c:out value="${' Hi WELCOME TO JSTL' }"></c:out>

<br>

<c:set var="num" value="500"></c:set>

<hr>
<b> <c:out value="${num }"></c:out>
</b>

</body>
</html>

+++++++++++++++++++++++++

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<h1>JSTL</h1>

<br>

<c:out value="${' Hi WELCOME TO JSTL' }"></c:out>

<br>

<c:set var="num" value="1000"></c:set>

<hr>
<b> <c:out value="${num }"></c:out>
</b>
<hr>

<c:if test="${ num>500 }">

<c:out value="${ 'NUM IS GREATER THAN 500' }"></c:out>

</c:if>

<br>

<c:choose>

<c:when test="${num>1000 }">

<c:out value="${ 'NUM IS GREATER THAN 1000' }"></c:out>


</c:when>

<c:otherwise>

<c:out value="${ 'NUM IS LESS THAN 1000' }"></c:out>


</c:otherwise>

</c:choose>

<hr>

</body>

</html>

+++++++++++++++++++
COMPLETE
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<h1>JSTL</h1>

<br>

<c:out value="${' Hi WELCOME TO JSTL' }"></c:out>

<br>

<c:set var="num" value="1000"></c:set>

<hr>
<b> <c:out value="${num }"></c:out>
</b>

<hr>

<c:if test="${ num>500 }">

<c:out value="${ 'NUM IS GREATER THAN 500' }"></c:out>

</c:if>

<br>

<c:choose>

<c:when test="${num>1000 }">

<c:out value="${ 'NUM IS GREATER THAN 1000' }"></c:out>


</c:when>
<c:otherwise>

<c:out value="${ 'NUM IS LESS THAN 1000' }"></c:out>


</c:otherwise>

</c:choose>

<hr>

<c:forEach var="i" begin="1" end="5">


<b> <c:out value="${i}"></c:out></b>
<hr>
</c:forEach>

<hr>

<c:forTokens items="Hello-I-Love-India" delims="-" var="name">


<h3 style="color: green; font-family: cursive;">
<c:out value="${name}"></c:out>
<br>
</h3>

</c:forTokens>

<hr>

<c:set var="x" value="500"></c:set>

<h3 style="color: green; font-family: cursive;">


<c:out value="${x}"></c:out>
<br>
</h3>

<hr>
<c:remove var="x"/>

<h3 style="color: green; font-family: cursive;">


<c:out value="${x}"></c:out>
<br>
</h3>

</body>

</html>

++++++++++++++++++++++++++++++++++++++++

JSTL

—---

package model;

import java.io.Serializable;

// JAVA BEAN
public class Employee implements Serializable {

int id;

String name;

String role;

public Employee() {
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getRole() {


return role;
}

public void setRole(String role) {


this.role = role;
}

//
}

+++++++++++++++++++++

package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Employee;

/**
* Servlet implementation class EmployeeController
*/
@WebServlet("/EmployeeController")
public class EmployeeController extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

// Step Emp Object


// Object Add
// List
Employee emp=new Employee();
emp.setId(11);
emp.setName("Kalpesh");
emp.setRole("Programmer");

Employee emp2=new Employee();


emp2.setId(22);
emp2.setName("Ashutosh");
emp2.setRole("Learner");

List<Employee> empList=new ArrayList<Employee>();


empList.add(emp);
empList.add(emp2);

request.setAttribute("empList", empList);

RequestDispatcher rd=request.getRequestDispatcher("home.jsp");

rd.forward(request, response);

++++++++++++++++++++++++

<%@page import="model.Employee"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>


<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>

<style type="text/css">
td,th{
border: 2px solid black;
}

</style>

</head>
<body>

<table >

<thead>
<tr>

<th><b>ID</b></th>
<th><b>Name</b></th>
<th><b>Role</b></th>

</tr>
</thead>
<c:forEach items="${requestScope.empList }" var="emp">
<tr>

<td><c:out value="${ emp.id }"></c:out></td>


<td> <c:out value="${ emp.name }"></c:out>
</td>

<td><c:out value="${ emp.role }"></c:out>


</td>

</tr>
</c:forEach>

</table>

</body>
</html>

++++++++++++++++++++++++++++++++++++++++

Implicit Object
1: request
2: response
3: out JSPWriter
4: config (ServletConfig)
5: application (ServletContext)
6: session (HttpSession)
7: page (this)
8: exception (Throwable)

[Need to revise excpetion hierachy]

exception

Ex-

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="process.jsp" method="get">

N1: <input type="text" name="n1"><br>

N2: <input type="text" name="n2"><br>

<input type="submit" value="GO">

</form>

</body>
</html>

++++++++++++++

process.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" errorPage="error.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<%
int n1=Integer.parseInt(request.getParameter("n1"));
int n2=Integer.parseInt(request.getParameter("n2"));

%>
<b>
DIV IS :

<%= n1/n2 %>

</b>
</body>
</html>

++++++++++++++++++++++++++++++++

error.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1" isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<h1>This is an exception Occures Below Details</h1>


<br>
<h2 style="color: red; font: italic;">
<%=exception%>
</h2>
</body>
</html>

++++++++++++++++++++++++++

Question

What is JSP?

What are the life-cycle methods for a JSP?

advantages of using JSP.

What are the JSP implicit objects?

---------------------------
View --> Presention Logic -->JSP Page
Model --> JAVA BEAN ex-> Customer Employee User
Controller --> Servlet / Filter

-------------------------------------

Introduction to MVC
---------------------
Model-View-Controller (MVC) is a pattern used in software engineering
to separate the application logic from the user interface. As the name
implies,
the MVC pattern has three layers.

The Model defines the business layer of the application,


the Controller manages the flow of the application,
and the View defines the presentation layer of the application.

In a Java context, the Model consists of simple Java classes, the


Controller consists of servlets and the View consists of JSP pages.

Here're some key features of the pattern:

It separates the presentation layer from the business layer


The Controller performs the action of invoking the Model and sending data
to View

The Model Layer


This is the data layer which contains business logic of the system, and also
represents the state of the application.

It's independent of the presentation layer, the controller fetches the data
from the Model layer and sends it to the View layer.

The Controller Layer


Controller layer acts as an interface between View and Model. It receives
requests from the View layer and processes them, including the necessary
validations.

The requests are further sent to Model layer for data processing, and once
they are processed, the data is sent back to the Controller and then
displayed on the View.

The View Layer


This layer represents the output of the application, usually some form of
UI. The presentation layer is used to display the Model data fetched by
the Controller.

+++++++++++++++++++++++++++++++++++++++++++++++

Model

package com.empcrud.model;

public class Employee {


private int id;
private String name;
private double salary;

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

public Employee(int id, String name, double salary) {


super();
this.id = id;
this.name = name;
this.salary = salary;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}

public double getSalary() {


return salary;
}

public void setSalary(double salary) {


this.salary = salary;
}

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

++++++++++++++++++++++++++++++

Register.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="RegisterServlet" method="get">

Id: <input type="text" name="id"> <br>


Name: <input type="text" name="uname"> <br>
Salary: <input type="text" name="salary"> <br>

<input type="submit" value="Register">

</form>

</body>
</html>

+++++++++++++++++++++++++++++++++++

Controller

package com.empcrud.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.empcrud.dao.EmployeeDAO;
import com.empcrud.model.Employee;

/**
* Servlet implementation class RegisterServlet
*/
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

EmployeeDAO dao;
@Override
public void init() throws ServletException {
dao=new EmployeeDAO();
}

public RegisterServlet() {
super();
// TODO Auto-generated constructor stub
}

protected void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

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

int id=Integer.parseInt(request.getParameter("id"));
String name=request.getParameter("uname");
double
salary=Double.parseDouble(request.getParameter("salary"));

Employee emp=new Employee();


emp.setId(id);
emp.setName(name);
emp.setSalary(salary);

try {
dao.saveEmployee(emp);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
+++++++++++++++++++++++++++++++++++++

Dao

package com.empcrud.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import com.empcrud.model.Employee;
import com.empcrud.utility.DBConnection;

public class EmployeeDAO {

public void saveEmployee(Employee emp) throws


ClassNotFoundException, SQLException {

Connection con=DBConnection.getDBConnection();
String sql="insert into employee values (?,?,?)";

PreparedStatement ps=con.prepareStatement(sql);
ps.setInt(1, emp.getId());
ps.setString(2, emp.getName());
ps.setDouble(3, emp.getSalary());

ps.executeUpdate();

con.close();

void updateEmployee(Employee emp) {

}
void deleteEmployeeById(int id) {

List<Employee> getAllEmployee() {

return null;
}

++++++++++++++++++++++++++++++++++++

package com.empcrud.utility;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {

public static Connection getDBConnection() throws


ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");

return
DriverManager.getConnection("jdbc:mysql://localhost:3306/empinfo", "root",
"root");

+++++++++++++++++++++++++++++++++++++++
THANK YOU !!!

Extra Save Image in DB

http://www.java2s.com/Code/Jar/c/Downloadcosjar.htm

Index.html

<html>
<body>
<form action="fileuploadservlet" method="post" enctype="multipart/form-data">
Select File:<input type="file" name="photo"/><br/>
<input type="submit" value="upload"/>
</form>
</body>
</html>

++++++++++++++++++

package p1;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet(name = "FileUpLoader", urlPatterns = { "/fileuploadservlet" })


@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
maxFileSize = 1024 * 1024 * 10, // 10 MB
maxRequestSize = 1024 * 1024 * 100 // 100 MB
)
public class FileUpLoader extends HttpServlet {
private static final long serialVersionUID = 1L;

private static final String url = "jdbc:mysql://localhost:3306/media";


private static final String user = "root";
private static final String password = "root";
private static final String sql = "INSERT INTO users (photo) values (?)";

protected void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {

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

InputStream inputStream = null; // input stream of the upload file

String message = null;


// obtains the upload file part in this multipart request
Part filePart = request.getPart("photo");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());

// obtains input stream of the upload file


inputStream = filePart.getInputStream();

} else {
System.out.println("*****************");
}

int row = 0;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

try (Connection connection = DriverManager.getConnection(url, user,


password);
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement =
connection.prepareStatement(sql)) {

if (inputStream != null) {
// fetches input stream of the upload file for the blob
column
preparedStatement.setBlob(1, inputStream);
}

// sends the statement to the database server


row = preparedStatement.executeUpdate();

} catch (SQLException e) {
System.out.println(e);
}

}
+++++++++++++++++++++++++++++++

You might also like