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

Servlet and JSP

The document discusses various concepts related to Java web development using servlets and JSP such as: 1) How servlets handle HTTP requests and responses and can pass data between each other using request dispatching, sessions, cookies etc. 2) The basics of JSP technology including common tags, implicit objects, and exception handling. 3) How to connect JSP pages to databases using JDBC and work with result sets. 4) Other related topics like MVC architecture, JSTL, servlet filters are also briefly covered.

Uploaded by

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

Servlet and JSP

The document discusses various concepts related to Java web development using servlets and JSP such as: 1) How servlets handle HTTP requests and responses and can pass data between each other using request dispatching, sessions, cookies etc. 2) The basics of JSP technology including common tags, implicit objects, and exception handling. 3) How to connect JSP pages to databases using JDBC and work with result sets. 4) Other related topics like MVC architecture, JSTL, servlet filters are also briefly covered.

Uploaded by

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

1)query string is sending req from client to server

ex;http://localhost:7810/Al13/add?+num1=2&+num2=5

2)getting dataa from server use 'get'

fetch data from server use 'post'

post wont put your data in url


above are examples of my initial sevlets using get method ,u can see url has data init
above is with post request so no data in addresbar n also !!! HTML IS WHITESPACE SENSITIVE!!!

3) CALLING SARVLET FROM A SARVLET


req dispatcher or redrect
4) session management is way of snding data from one servelt to another
REDIRECT
REDIRECT APPLIED ABOVE

4)HttpServletResponse and HttpServletRequest= both are objexts in which data is embedded to talk btw
server and user

5) httpsession= //if we put our k value in a session we can use it for long in multiple
servlets //provided u dont delete it
6) cOOKI IS ALT TO SESSION
above example hav cookie and session htoh done

7) servlet config and servlet context = context-we set up initial parameter

Config- is data shared by all serverlets

We can put speciic data for a sercvlet by adding param under name of servlet in xtl file
Conig with diffeerent data
*) SERVLET ANNOTATION AND CONFIGURATION = shorthand to remove need of xml file completelty bt
remember to keep your xml file completely clean for this

JSP = writing j java in html code n its a way to avoid servlet methods n all bt still more to come
<% %> scriptlets ,anytiing inside it will go to service method
<%! %. Declaration tag and anyhing init will go outside servcice method ;like we want to make a integer
or anything else lik a method will all go into this tag

<%@ %> import a package is done with this ex; <%@ page import =”java.util.date,java.sql.stm,...” &>
deractive tag

Want tot print something <%= k %> will rpint k ,expresssion tag

Directive tag = 3Types @page,@include and @taglib

@page examples

<%@ attribute=”value”, attribute=”value”, .... >

Attribute list language=”scripting language” java ; extends=”className” ; import=”importList” ;


session=”trueFalse” ; autoFlush=”tru eFalse” ; contentType=”ctinfo” ; errorPage=”error_url”

isErrorPage=”trueFalse” ; info=”information” ; isELIgnored=”trueFalse”; isThreadSafe=”trueFalse”

@include example
This ex is to show we made a 2nd jsp file called j2Al18 and included it as a file in jAl18 to get its code

@taglib example

<%@ taglib url=”url of a library” prefix”fx” %>

<fx:Chris> its lik we are making our own tag with customized skin using library

*) Implicit object in jsp

Request (HttpServletRequest) ; response(HttpServletResponse) ; pageContext(PageContext)

Session(HttpSession) ; application(ServletContext) ; config(ServletConfig)

out(JspWriter) ~ PrintWriter object

session scope last for whole session and pageContext scope last for a page BUT

pageContext.setAttribute("name","Chris",PageContext.SESSION_SCOPE); MEANS name has


value chris and it last for session as its scope is now as name says
*) EXCEPTION HANDLING IN JSP
Also we should mak an errorpage(here its j2Al18) which is gonna hav exception object and
isErrorPage=”true” method. So when jAl18 is having an exception abov page wl run
JDBC IN JSP= CONNECTING PAGES TO DATABASES

1 import java.sql.*
2 load and register driver

3
2ND SOURCE

Web brousers are also called clients

Website’s collection of webpages viz are internet programs

Static webpages – pages stored on servers and which provide same response to
any user are called static webpages-used html,css,js

Dynamic webpages – pages not stored on server but we write program and put it
on server which controls the information coming in at run time – this programs
gives a way for coming in data to db and embeddes the sitting static pages with
useful data

Java is server independent and machine independent

Servlet are server side programs written in java/its an interface/its an api for
server side programming/its used to generate dyn web page

HOW TO MAKE SERVLET

Extend yor class with HttpServlet

We made service(HttpServletResponse res,HttpServletRequest req){

// and we used an obj of PrintWriter to print on webpage

We made a html page with form action = add

We also did mapping in xml file using

<servlet><name,class> and <servlet-mapping><name,url-pattern> of html page


‘add’ and servlet ‘addservlet’
GET AND POST METHOD

Get to fetch and post to give data wrt server

By default its get if nothing metioned in form

Post wont put data in url

CALLING A SERVLET FROM A SERVLET

RequestDispatcher(rd)

In first servlert We made an obj of RD but as RD is an interface we have to pass a


method to a req obj i.e req.gerRequestDispatcher(“sq”);and
rd.forward(req, res);
Now that “Sq” we use in the mapping xml file as url-pattern ‘/sq’ and we
connected first servlet to second servlet

Now we see passing data from one servlet to other servlets

We set value of req in first servlet by

req.setAttribute("refermewiththis", d);
then in second servlet we extract value by

int k =(int) req.getAttribute(“refermewiththis”); // we type casted it here

and we use k , its that simple

but requestdisptcher doesnt inform brouwser tht its getting redirected so to do


so we have sendredirect

now requestdipatcher forwards the same req to another servlet that holds our
data but in sendredirect thats not the case so we use session management
concept to transfer data

SendRedirect

url changing method

res.sendRedirect("sq");
in first servlet – we use the sendredirect method which is of res obj so we
combine it with it and use that name ‘sq’ used in mapping

in second servlet – something changing url

Session method

In first servlet-We make a HttpSession obj and as its an interface we use req obj
to initialize it

HttpSession session = req.getSession();

Then

session.setAttribute(“refermebythisinnextsrvlet”,k);

In second servlet- HttpSession


session = req.getSession();
intk=(int)session.getAttribute("refermebythisinnextse
rvlet");

and thats how we do it

Cookie method

First servlet - In cookie method we make Cookie cookie obj and call its
constructor add in name of value and value

Then give that to res obj by using addCookie method

Cookie cookie = new Cookie(“myname”,k);

Res.addCookie(cookie);

Second servlet – her we make an array of cookies as the client will send all the
cookies its having with it and we need to accept the one we want so we will use a
for special loop

Cookie[] cookie = req.getCookie();

For(Cookie c:cookie){

If(c.getName.equals(“myname”) tada freaking da

}
ServletConfig and ServletContext

We need this both to get initial values for app or the servlet

Servlet Configuration Annotation

We try to kick deploymetn descriptor out of picture

@WebServlet(“name”) thats it

NOW JSP

We write java inside html

No need for complex coding conventions

JSP converts into servlet by using tags

Declaration tag <%! CREATING METHODS,DECL VARIABLES %>

Scriplet tag <% things here will go into service() %>

Directive tag <%@ page import=”java.util...”,”java.sql....” %>

Expression tag <%= whatever in it will go in into out.print i.e wl b printed %>

Now taking about those tags indivisually

For DIRECTIVE

<%@ X attribute=”value” %>

X=can be page / include / taglib


‘Page’ can used for attributes such as

<%@ page attribute=”value....” attribute=”value”...... %>

Language=”scripting language”

Extends=”className”

Import=”ImportLiat”

Session=”true/false”

autoFlush=”true/false”

contentType=”ctinfo”

errorPage=”error_url”

info=”information”

isThreadSafe=”true/false”

‘include’

<%@ include file=”filename” %>

IMPLICIT(build-in) OBJECT IN JSP used in scriptlet and expression tags

Request

Response

PageContext

Out

Session
Application

Config

We dont have to instantiate them as they are already done at backend

EXCEPTION HANDLING IN JSP

In page where we are getting error go in <%@ %> tag and add
errorPage=”nameofthepagewhereyouhavealtthingstoshow” thats it

JDBC IN JSP

We use scriptlet tag

<% Class.forName("com.mysql.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/profile";
Connection con=
DriverManager.getConnection(url,"root","chris");
Statement stm = con.createStatement();
String sql = "select * from data where ID=1";

ResultSet rs = stm.executeQuery(sql);

rs.next();
%>
ID : <%= rs.getString(1) %> <br>
Name : <%= rs.getString(2) %> <br>
Cell : <%= rs.getString(3) %> <br>
MVC USING SERVLET AND JSP

JSTL = JSP STANDARD TAG LIBRARY

It’s set of libs where we get tags to be used in jsp

Like ${} can be used to fetch the data sent btwn servlet and jsp

Servlet- String name = "Chris";


request.setAttribute("n", name);
RequestDispatcher rd =
request.getRequestDispatcher("display.jsp");
rd.forward(request, response);

jsp – Holla ${n} will do the trick

using jstl lib

<%@ taglib prefix=”c” uri=” /crl+space/ ” %>

Down in jsp body

<c: /crl+space/ value=”” /> crl+space will give magic tags

We have to make bin(*java class) By making getters and setters with a


construstor

JSTL SQL tags

Data source tag


<sql:setDataSource var="db"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/profile" user="root"
password="chris"/>

<sql:query var="rs" dataSource="${db}"> select *


from data </sql:query>

<c:forEach items="${rs.rows}" var="d">


<c:out value="${d.ID}" ></c:out> :
<c:out value="${d.NAME}"></c:out> :
<c:out value="${d.cell}"></c:out>
</c:forEach

JSTL FUNCTION TAGS


<%@ taglib prefix="fn"
uri="http://java.sun.com/jsp/jstl/functions" %>
Functions do work

1)<c:set var="st" value="YOYOYO DOGGO" ></c:set>


Length calculated by function is : $
{fn:length(st)}
2)<c:forEach items=”${fn:split(st,” “)” value=”s” >

${s}

</c:forEach>
SERVLET FILTERS

Class extends ServletFilter AND ADD @WebFilter("/ass")

It has doFilter(ServletRequest request ,ServletResponse response,Chaing objs )

Filter acts as a barrier for request before it reaches to use servlet

We mak HttpServletRequest obj here and check our conditions as such by if/else

HttpServletRequest req = (HttpServletRequest)


request;

LOGIN

We can access videos on a website easily by using url for that page . So to stop it
we use logic of session where credentials of a user are carried throughout whole
time until he doesnt logout

Here we make HttpSession obj = request.getSession();


Obj.setAttribute(“ThisNameGoesOnAndOnInTheWholeSessionLikeAGhost”,valu);

Then in anothere we gotta check this by using if stm and obj.getAttribute()

LOGIN.JAVA

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


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

if(name.equals("Chris") &&
pass.equals("Rock")) {
HttpSession session =
request.getSession();
session.setAttribute("A", name);

response.sendRedirect("welcome.jsp");
}
else {
response.sendRedirect("about.jsp");
}
WELCOME.JSP AND VIDEOS.JSP
<%

if(session.getAttribute("A")==null)
{
response.sendRedirect("login.jsp");
}

%>
LOGOUT.JAVA
HttpSession session = request.getSession();
session.removeAttribute("A");
session.invalidate();

response.sendRedirect("login.jsp");

HOW TO PREVENT BACK BUTTON WITH LOGOUT


Sending to server use POST
Getting from server use GET
response.setHeader("Cache-Control","no-cahce, no-
store, must-revalidate");

This is browser specific so copy paste it

LOGIN USING SERVLET,JSP AND JDBC

We made a diff class with database code and later we made a nobject of it in our
login.java of it and checked all of that

Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection(url,"root","chris");
PreparedStatement stm =
con.prepareStatement(sql);
stm.setString(1, name);
stm.setString(2, pass);
ResultSet rs =stm.executeQuery();
if(rs.next()) {
return true;
}

You might also like