Introduction to Servlets

Slides:



Advertisements
Similar presentations
Servlets & JSPs - Sharad Ballepu.
Advertisements

Apache Tomcat as a container for Servlets and JSP
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Java Servlet & JSP © copyright 2005 SNU OOPSLA Lab.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
WEB1P servintro1 Introduction to servlets and JSP Dr Jim Briggs.
An introduction to Java Servlet Programming
Chapter 4 Servlets Concept of Servlets (What, Why, and How) Servlet API Third-party tools to run servlets Examples of Using Servlets HTML tag with GET.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
SE-2840 Dr. Mark L. Hornick1 Java Servlet-based web apps Servlet Architecture.
CSCI 6962: Server-side Design and Programming History and Background.
Introduction to Java web programming Dr Jim Briggs JWP intro1.
Chapter 10 Servlets and Java Server Pages. A servlet is a Java class designed to be run in the context of a special servlet container An instance of the.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Copyright © 2012 Accenture All Rights Reserved.Copyright © 2012 Accenture All Rights Reserved. Accenture, its logo, and High Performance Delivered are.
111 Java Servlets Dynamic Web Pages (Program Files) Servlets versus Java Server Pages Implementing Servlets Example: F15 Warranty Registration Tomcat Configuration.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
JSTL Lec Umair©2006, All rights reserved JSTL (ni) Acronym of  JavaServer Pages Standard Tag Library JSTL (like JSP) is a specification, not an.
Java Servlets Lec 27. Creating a Simple Web Application in Tomcat.
Chapter 2 Web app architecture. High-level web app architecture  When a client request coming in and needs servlet to serve dynamic web content, what.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
JSP Pages. What and Why of JSP? JSP = Java code imbedded in HTML or XML –Static portion of the page is HTML –Dynamic portion is Java Easy way to develop.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
1 Web Programming with Servlets & JSP ASSIGNMENT GUIDELINE.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
Vakgroep Informatietechnologie – Onderzoeksgroep (naam) Web Centric Design of Distributed Software.
 Java Server Pages (JSP) By Offir Golan. What is JSP?  A technology that allows for the creation of dynamically generated web pages based on HTML, XML,
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Speaker Name Speaker Title Speaker Title Oracle Corporation Olivier Le Diouris Principal Product Manager Oracle Corporation Building Servlet and JSP Applications.
Helpers, Data Validation
Introduction to Servlets
Sockets, Routing, Sessions, Handlers
ASP.NET Essentials SoftUni Team ASP.NET MVC Introduction
Web API - Introduction AJAX, Spring Data REST SoftUni Team Web API
Introduction to MVC SoftUni Team Introduction to MVC
Cookies, Sessions, Bootstrap
Deploying Web Application
Thymeleaf and Spring Controllers
PHP Fundamentals Course Introduction SoftUni Team Technical Trainers
ASP.NET Integration Testing
ASP.NET Unit Testing Unit Testing Web API SoftUni Team ASP.NET
State Management Cookies, Sessions SoftUni Team State Management
Browser Routing Design Patterns in JS
JSP: Actions elements and JSTL
EF Code First (Advanced)
PHP MVC Frameworks MVC Fundamentals SoftUni Team Technical Trainers
Spring Filters Spring Interceptors SoftUni Team Spring Interceptors
Registration, Login, Thymeleaf
C#/Java Web Development Basics
MVC Architecture. Routing
The Right Way Control Flow
MVC Architecture, Symfony Framework for PHP Web Apps
Net-centric Computing
Databases Advanced Course Introduction SoftUni Team Databases Advanced
C# Web Development Basics
Best practices and architecture
Spring Boot Introduction
Java Servlets.
Design & Module Development
Extending functionality using Collections
Scheduled Tasks and Web Socket
CSS Transitions and Animations
JavaScript: ExpressJS Overview
Sessions.
Servlets and Java Server Pages
Servlets and JSP 20-Nov-18 servletsJSP.ppt.
J2EE Lecture 1:Servlet and JSP
Presentation transcript:

Introduction to Servlets Tomcat, Servlets, JSP Introduction to Servlets SoftUni Team Technical Trainers Software University http://softuni.bg

Table of Contents Apache Tomcat Java Servlets JSP Routing State Management MVC JSP JSTL EL

Have a Question? sli.do #JavaWeb

Apache Tomcat

What is a Apache Tomcat? Open-source Java Servlet Container developed by the Apache Software Foundation Implements Java Servlet, JSP, Java EL, WebSockets Provides HTTP Server Download Tomcat from: https://tomcat.apache.org/download-80.cgi © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Tomcat Setup Add Tomcat Tomcat Server URL Default Action HTTP Port

Java EE Support Web Support Web XML

Java Servlets

Java Servlets Programs that run on a Web/Application server and act as a middle layer between a request coming from a web browser Web Client Web Server Request Request Servlet Database Data Response Response © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Maven Dependencies pom.xml <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency>

Servlet Example URL pattern Handle Post requests Handle Get requests Servlet.java @WebServlet("/home") public class Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, Handle Post requests Handle Get requests

URL Patterns @WebServlet("/") – default servlet. Listens to everything that doesn’t match other patterns. @WebServlet("/*") – listen to everything and overrides othe paths. @WebServlet("") – listen to only application root @WebServlet("/home") – listen to only /home route. @WebServlet("/*.html") – extention mapping

Servlet Lifecycle Java Virtual Machine Web Server init() Thread 1 Servlet Container init() Thread 1 Thread 2 service() Thread 3 destroyed() Requests

Print Header Servlet.java @WebServlet("/header") public class Servlet extends HttpServlet { protected void doGet(…) { PrintWriter out = response.getWriter(); Enumeration<String> headerNames = request.getHeaderNames(); out.println("Header:"); while (headerNames.hasMoreElements()) { String element = headerNames.nextElement(); String value = request.getHeader(element); out.println(element + " : " + value); }

Print Header

Read Parameter Param name Param name Servlet.java @WebServlet("/param") public class Servlet extends HttpServlet { protected void doGet(…) { PrintWriter out = response.getWriter(); String name = request.getParameter("name"); out.println("Param:" + name); } Param name Param name

Manipulate Cookies Create Cookie Add Cookie Get Cookie Servlet.java @WebServlet("/cookies") public class Servlet extends HttpServlet { protected void doGet(…) { PrintWriter out = response.getWriter(); Cookie languageCookie = new Cookie("lang", "EN"); response.addCookie(languageCookie); Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { //TODO: Print the cookies } Create Cookie Add Cookie Get Cookie It is possible to invalidate a cookie by invoking the method languageCookie.setMaxAge(0); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Manipulate Sessions (1) Servlet.java @WebServlet("/setsession") public class Servlet extends HttpServlet { protected void doGet(…) { HttpSession session = request.getSession(); session.setAttribute("username", "java@softuni.bg"); } Get Session Set Attribute It is possible to invalidate a cookie by invoking the method languageCookie.setMaxAge(0); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Manipulate Sessions (2) Servlet.java @WebServlet("/getsession") public class Servlet extends HttpServlet { protected void doGet(…) { HttpSession session = request.getSession(); String username = session.getAttribute("username").toString(); //TODO: Print the attribute } Get Session Get Attribute It is possible to invalidate a cookie by invoking the method languageCookie.setMaxAge(0); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Forwarding Forward to form.html Servlet.java @WebServlet("/form") public class Servlet extends HttpServlet { protected void doGet(…) { request .getRequestDispatcher("form.html") .forward(request, response); } Forward to form.html It is possible to invalidate a cookie by invoking the method languageCookie.setMaxAge(0); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Read Form Data Servlet.java @WebServlet("/form") public class Servlet extends HttpServlet { protected void doPost(…) { String logIn = request.getParameter("login"); if(logIn != null) { String username = request.getParameter("username"); String password = request.getParameter("password"); form.html <form method="post"> <input type="text" name="username"> <input type="password" name="password"> <input type="submit" name="login" value="Log In"> </form>

Redirect Redirect to /home Servlet.java @WebServlet("/form") public class Servlet extends HttpServlet { protected void doGet(…) { response.sendRedirect("/home"); } } Redirect to /home It is possible to invalidate a cookie by invoking the method languageCookie.setMaxAge(0); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

MVC Design pattern with three independent components Model – manages data and application logic View – presentation layer Controller – converts the input into commands and sends them to the view or the model

Response (html, json, xml) MVC – Control Flow Web Client Request Controller Response (html, json, xml) Update Model User Action Update View Notify Model View

Overall Architecture Repository Service Controller View Entities Database View Entities Models/ DTO Back-end

JSP, JSTL, EL

JSP Technology for developing web pages that support dynamic content Web Client Read Web Server Request Generate Servlet Response Response

JSP Example Page Directive Java Code index.jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>JSP</title> </head> <body> <%= new String("Hi From JSP")%> </body> </html> Page Directive Java Code

Syntax Scriplet – nest Java code Declaration Tag – define variables Expression Tag – print java variables Comment Tag – add comments <% System.out.println("Message in the Console"); %> <%! int x = 5; %> <%= x%> <%-- This is JSP comment --%>

Simple JSP Loop Declare Variable Prepare Loop Print Value index.jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <body> <%! int elements = 10;%> <% for (int i = 0; i < elements; i++) {%> <div style="color: green"> <%=i%> </div> <%}%> </body> </html> Declare Variable Prepare Loop Print Value

JSP Conditional Statement index.jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <body> <%! int readBooks = 3;%> <% if(readBooks < 20) {%> <%= new String("You are poor")%> <%} else {%> <%= new String("You are rich")%> <%}%> </body> </html>

JSP Actions JSP Include Action include.jsp <body> <p>- Carlos Ruiz Zafón, The Prisoner of Heaven </p> </body> index.jsp <body> <p>We only remember what never happened</p> <jsp:include page="include.jsp"></jsp:include> </body> JSP Include Action

JSTL Collection of useful JSP tags which encapsulates core functionality common to many JSP applications index.jsp <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> ... <c:set var="apples" value="${5}"/> <div> Apple Count: <c:out value="${apples}"/> </div> Declare Variable Assign Value Print Variable

JSTL Simple Loop Declare Variable index.jsp <c:forEach items="rock,scissor,paper" var="item"> <div> <c:out value="${item}"/> </div> </c:forEach>

JSTL Conditional Statement index.jsp <c:set var="goalsScored" value="${14}"/> <c:choose> <c:when test="${goalsScored > 200}"> <div> Messi </div> </c:when> <c:otherwise> Bozhinov </c:otherwise> </c:choose>

Expression Language (1) JSP EL makes it possible to easily access application data Servlet.java protected void doGet(…) { List<String> weekdays = new ArrayList() { { add("Monday"); add("Tuesday"); … } }; request.setAttribute("weekdaysParam", weekdays); request.getRequestDispatcher(“index.jsp").forward(request,response);

Expression Language (2) index.jsp <c:set var="weekdays" value="${weekdaysParam}"/> <c:forEach items="${weekdays}" var="weekday"> <div> <c:out value="${weekday}"></c:out> </div> </c:forEach>

Summary Servlets are programs that run on a Web/Application server and act as a middle layer JSP is a technology for developing web pages that support dynamic content

Web Development Basics – Course Overview https://softuni.bg/courses/ © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University @ YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.