Servlets and JSP

Servlets and JSP

Servlets

A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model.

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Addition of two numbers</title>
</head>
<body>
<form action="AddServlet">
// here the AddServlet is the servlet anotation which we mentioned in servlet
<input type = "text" name="input1">
<input type = "text" name="input2">
<input type="submit">
</form>
</body>
</html>
package com.servlets;

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;


@WebServlet("/AddServlet")
// here the AddServlet is anotation which is used instead of giving url-pattern
// in the web.xml
public class AddServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public void service(HttpServletRequest req, HttpServletResponse res) {
        int i = Integer.parseInt(req.getParameter("input1"));
        int j = Integer.parseInt(req.getParameter("input2"));
        int k = i + j;
        System.out.println(k);
    }
}

the above code is printed in the terminal to get the output on the html page we uses PrintWriter.

package com.servlets;

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("/AddServlet")
// here the AddServlet is anotation which is used instead of giving url-pattern
// in the web.xml
public class AddServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public void service(HttpServletRequest req, HttpServletResponse res) throws IOException {
        int i = Integer.parseInt(req.getParameter("input1"));
        int j = Integer.parseInt(req.getParameter("input2"));
        int k = i + j;
        PrintWriter out = res.getWriter();
        out.println("result is" + k);
    }
}

we need to mention the html tags in println() to get the tag values in console.

Methods

we can use the request in two ways there are :
1. Get
2. Post

get :
by using method = "get" in the form of the html.
the data given input is displayed in address-bar
by default the get method is considered
we can use the doGet method instead of the service method which works only for the get method.

post:
by using method = "post" in the form of the html.
the data given input is not displayed in address-bar
we can use the doPost method instead of the service method which works only for the get method.
service method will work for both methods.

RequestDispatcher

RequestDispatcher is used for forward the data from servlet to another servlet the content by using the getRequestDispatcher method.

@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
        int i = Integer.parseInt(req.getParameter("input1"));
        int j = Integer.parseInt(req.getParameter("input2"));
        int k = i + j;
        req.setAttribute("k", k);
        RequestDispatcher rd = req.getRequestDispatcher("Rr");
        rd.forward(req, res);

    }
}

// another servlet : 
@WebServlet("/Rr")
public class RequestServ_dis extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        int k = (int) req.getAttribute("k");
        k = k * k;
        PrintWriter out = res.getWriter();
        out.println("k square is " + k);
    }
}

sendRedirect

we can do it by sendRedirect method but here browser also know about the redirecting. browser will not accept it.so,we need to provide the query in the method itself.

res.sendRedirect("Rr/k=" + k);
// also knows as url-rewriting.

Session

using session we can use the variables or attributes in different servlets.

// Get the HttpSession object from the request
HttpSession session = request.getSession();

// Store a value in the session
session.setAttribute("username", "John");

// Retrieve a value from the session in another servlet
String username = (String) session.getAttribute("username");

// removing session : 
session.removeAttribute("username");

Cookies

similarly we can use cookies on client side which stores the data at client side.

Cookie c = new Cookie(key: value);
//creating the cookie
res.addCookie(c);
// in another servlet
Cookie k = req.getCookies();
// return the array of cookies we need to get value using loops of values in cookie.

JSP( Java Server Page)

here the we basically write the java code inside the tags.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>My JSP Page</title>
</head>
<body>
    <%  
        int i = Integer.parseInt(request.getParameter("input1"));
// here the request is given by the jsp.
        int j = Integer.parseInt(request.getParameter("input2"));
        int k = i + j;
        PrintWriter out = res.getWriter();
        out.println("result is" + k);
    %>
</body>
</html>

the jsp is represented using 4 different tags.

I. Directives

it provides global information about the jsp page.
there are 3 different types of directives:

1.page

define-page - used for error handling and buffer requirements, contentType, import, session etc...

<%@ page errorPage="error.jsp" %>
// the tag written on the top of page which used to forward if any error occured.
<%@ page buffer="20kb" %>
// if the page has completed the size of buffer then  the content that has been 
//accumulated in the buffer will be automatically flushed to the client's browser,
// and a new buffer will be created to continue buffering the remaining content.
// we can use none value for the no buffer limit
<%@ page import="package1.class1, package2.class2, ..." %>
// import the packages.
// if any error is occured then jsp forward to this page to show error
<%@ page isErrorPage="true" %>
<html>
<head>
    <title>Error Page</title>
</head>
<body>
    <h1>Error Occured</h1>
    <p>An error occurred: <%= exception.getMessage() %></p>
</body>
</html>
// the error page

2.Includes

it used to include the content of another file in the current JSP during translation phase. it is two types :
static include : the content is included before the compilation of the page. it makes the changes in the page.(file is used for static).

<%@ include file="fileName.jsp"%>
//it is also known as include directive

dynamic include : the content is inserted after the page is compilation of the page. it doesn't make change the page. (page is used for dynamic).

<%@ include page="fileName.jsp"%>
// it is also knnown as include action.

3.taglib

it is used to declare the tag library that defines custom tags used in the page.

<%@ taglib uri="http://example.com/tags" prefix="ex" %>
<html>
<head><title>Custom Taglib Example</title></head>
<body>
    <ex:customTag attribute1="value1" attribute2="value2" />
</body>
</html>

II. Declarations

it is used to declare the variables or methods.
they are placed between <%! %>

<%!
    public int Format(int x){
        sout(x);
        return x;
    }
%>

III. Scriptlets

used to write logic of java code

<%
   int x = sc.nextInt();
   sout(x);
%>

IV. Expressions

In JSP, an expression is used to insert the value of a java expression directly into the output HTML.

<%
    String name = sc.next();
%>
<p><%= name%></p>

V. Comments

comments are used to describe the code.

<%-- comment --%>