Servlet

Servlet Life Cycle

HTTP methods — doGet and doPost

package com.hello;

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

public class HelloServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
public void init() throws ServletException {
// Servlet initialization code here
super.init();
}

@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

// Set response content type
response.setContentType("text/html");

// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>Hello</h1>");
}

@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

}

@Override
public void destroy() {
// resource release
super.destroy();
}
}

Deployment Description (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"
version="4.0">
</web-app>
<servlet>
<servlet-name>servlet</servlet-name>
<servlet-class>com.hello.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

JavaServer Pages (JSP)

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP - Hello World</title>
</head>
<body>
<%
String hello = "Hello";
%>
<h1><%= hello %></h1>
<br/>
</body>
</html>
Syntax:- 
<%! Dec variable %>
Example:-
<%! int variable = 10; %>
Syntax:- 
<% java code %>
Syntax:- 
<%= expression %>
Example:-
<% num1 = num1+num2 %>
<h1><%= expression %></h1>
Syntax:- 
<% -- Comments %>

Full Stack Web Application and Software Developer