Язык Java. JSP..

Slides:



Advertisements
Similar presentations
STRING AN EXAMPLE OF REFERENCE DATA TYPE. 2 Primitive Data Types  The eight Java primitive data types are:  byte  short  int  long  float  double.
Advertisements

Apache Tomcat as a container for Servlets and JSP
Introduction to Servlets Based on: Hall, Brown, Core Servlets and JavaServer Pages.
Servlets. A form The HTML source Chapter 1 Please enter your name and password then press start Name: Password: In Netbeans you can graphically create.
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.
Servlets Stoney Jackson
CSE 190: Internet E-Commerce Lecture 7. HTML Templates Designed to separate server side logic from HTML presentation Key features –Escapes from HTML into.
An introduction to Java Servlet Programming
Программирование на стороне сервера. Языки для программирования на стороне сервера Языки программирования: Perl PHP Java Технология Microsoft для использования.
JSP Java Server Pages Reference:
June 1, 2000 Object Oriented Programming in Java (95-707) Advanced Topics 1 Lecture 10 Object Oriented Programming in Java Advanced Topics Servlets.
Синтаксис языка Java.
Servlets. A form The HTML source Chapter 1 Please enter your name and password then press start Name: Password: In Netbeans you can graphically create.
Пользовательские действия (custom actions) в JSP. JSTL.
2/16/2004 Dynamic Content February 16, /16/2004 Assignments Due – Message of the Day Part 1 Due – Reading and Warmup Work on Message of the Day.
Proposed 1 Modify the count servlet in order to generate an answer showing the IP addresses of ALL computer that have accessed it –Use a vector or an array.
Servlets Replace Common Gateway Interface Scripts Extend Server Functionality Modules (software components) Like applets to browsers No GUI.
Servlet Session Tracking II Session API All material and examples are from
Java Servlets and JSP.
Servlets, Sessions, and Cookies Lecture 8 cs193i – Internet Technologies Summer 2004 Kelly Shaw, Stanford University.
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
Examples of Using Servlets and JSP Representation and Management of Data on the Internet.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
Introduction to JSP Based on: Marty Hall, Larry Brown, Core Servlets and JavaServer Pages.
CSC 2720 Building Web Applications
Java Servlets and Java Server Pages Carol Wolf Computer Science.
111 Java Servlets Dynamic Web Pages (Program Files) Servlets versus Java Server Pages Implementing Servlets Example: F15 Warranty Registration Tomcat Configuration.
DataBases and SQL INFSY 547 Spring Course Wrap Up April 12: Complete Work on Servlets Review of Team Projects Close of Portfolio Work April 19:
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Java Servlets & Java Server Pages Lecture July 2013.
J2EE Servlets Ch. 10 (Architecture) Ch. 12 (21 Days)
CSC 2720 Building Web Applications JavaServer Pages (JSP) The Basics.
Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
S ERVLETS Hits Counter 21-Nov-15. S ERVLETS - H ITS C OUNTER Many times you would be interested in knowing total number of hits on a particular page of.
Top right corner for field-mark, customer or partner logotypes. See Best practice for example. Slide title 40 pt Slide subtitle 24 pt Text 24 pt Bullets.
S ERVLETS Cookies Handling 5-Dec-15. S ERVLETS - C OOKIES H ANDLING Cookies are text files stored on the client computer and they are kept for various.
Slides © Marty Hall, book © Sun Microsystems Press 1 Handling Cookies Core Servlets & JSP book: More.
Cookies. Cookie A cookie is a piece of textual information Send by the Web server to the client browser Every time the browser visits the Web site again,
Fall 2007cs4201 Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering
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.
Introduction to Servlets. Introduction Servlet is a language to develop the server side applications, and it is also server side component. It can develop.
J2EE T ECHNOLOGIES These are the technologies required to build large scale distributed applications, can be divided into – Component Technologies eg.
Java Servlets Java Server Pages (JSP)
Configuration Web Server Tomcat - Install JDK Install Tom cat Configure Tom cat for running Servlet C:\Program Files\Apache Software Foundation\Tomcat.
Java Servlets and Java Server Pages
Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory.
Introduction To HTML Dr. Magdi AMER. HTML elements.
ClaRA web services V. Gyurjyan Clas12 Software Meeting
JSP JavaServer Pages. What is JSP? Java based technology that simplifies the development of dynamic web sites JSP pages are HTML pages with embedded code.
A Introduction to Computing II Lecture 1: Java Review Fall Session 2000.
J2EE/Java EE Apache Tomcat v9 IBM Websphere v8 Redhat JBoss EAP v6 Oracle Weblogic v12 Fusion Web Tier ServletsJSPJSF Business Tier JMXJMSEJB.
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
Java Database Connectivity JDBC. Open Database Connectivity developed by Microsoft to provide interaction with databases using SQL. Use the JDBC-ODBC.
Introduction to Servlets
Servlets Hits Counter 20-Jul-18.
Strings and File I/O.
HTTP request message two types of HTTP messages: request, response
Java Servlets II: Session Tracking
Servlet.
Jagdish Gangolly State University of New York at Albany
Servlets and JSP 20-Nov-18 servletsJSP.ppt.
null, true, and false are also reserved.
An Introduction to Java – Part I, language basics
Servlets.
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Basic servlet structure
Presentation transcript:

Язык Java. JSP.

Java. Синтаксис. Перевод строчки эквивалентен пробелу Регистр в именах различается // Комментарии до конца строки /* Многострочные комментарии */

Типы данных Примитивные типы данных: Объекты boolean char – 2 байта byte – 1 байт: целое -128 ÷ 127 short – 2 байта: целое -215 ÷ 215 -1 int – 4 байта: целое -231 ÷ 231 -1 long – 8 байт: целое -263 ÷ 263 -1 float – 4 байта double – 8 байт void Объекты

Определение новых типов данных class имя_класса { тело_класса } тело_класса – объявления полей и методов класса Поля: данные любого типа (ссылки) Методы: возвращаемый_тип имя_метода(аргументы) { тело возвращение значения – return значение

Переменные Объявления переменных: Создание объекта: Поля объекта: тип имя_переменной; тип имя_переменной = значение; Объявление не создаёт экземпляра объекта! Создание объекта: имя_переменной = new тип(аргументы); - вызов конструктора Поля объекта: имя_переменной.имя_поля

Пример программы // HelloDate.java import java.util.*; public class HelloDate { public static void main(String[] args) { System.out.println("Hello, it's: "); System.out.println(new Date()); }

Сервлеты import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Hello extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html"); out.println( "<head><title>Hello!</title></head>"); out.println("<body><h1>Hello!</h1></body>"); out.println("</html>"); }

Классы сервлетов Пакет javax.servlet: HttpServlet HttpServletRequest HttpServletResponse Cookie Session и т.д.

Предопределённые объекты page типа java.lang.Object config типа ServletConfig out типа jsp.JspWriter application типа ServletContext session типа http.HttpSession pageContext типа jsp.PageContext response типа HttpServletResponse request типа HttpServletRequest

Типичное использование предопределённых объектов <%@ page import="java.util.*" %> <%@ page contentType="text/html; charset=Windows-1251" %> <%@ page session="false" %> <% Cookie[] cs = request.getCookies(); %> <% Enumeration flds = request.getParameterNames(); %> <% String str=request.getParameter("name"); %> <% response.addCookie(cookie); %> <% response.setContentType("image/gif"); %> <% response.setHeader("Content-disposition","attachment; filename=data.txt"); %> <% out.println(str); %> <% Session ses = session.getId() %> <% session.setAttribute("My dog", new String("Ralph")); %> <% Str dogName = session.getAttribute("My dog") %>

Директивы include и forward <%@ include file="url" %> = <jsp:directive.include file="url"/> – подключает файл при трансляции JSP в сервлет <jsp:include page="относительный URL" flush="true"/> – подключает файл при обработке запроса <jsp:forward page="относительный URL"/> – перенаправляет запрос на другую страницу

Пример: опрос За какую партию Вы намерены голосовать: 1. Единая Россия 2. Справедливая Россия 3. КПРФ 4. ЛДПР

Рисование формы <%@ page import="java.util.*" %> <%@ page contentType="text/html; charset=Windows-1251" %> <html><body> <H2>Опрос: выборы в Госдуму</H2> <%! String[] parties = {"Единая Россия", "Справедливая Россия", "КПРФ", "ЛДПР"}; %> <form method="GET" action="anketa.jsp"> <P>За какую партию Вы намерены голосовать:</P><BLOCKQUOTE> <% for(int i = 0; i < parties.length; i++) { <INPUT type="radio" id="party<%=i+1%>" name="party" value="<%=i+1%>"> <LABEL for="party<%=i+1%>"> <%=i+1%>. <%=parties[i]%></LABEL><BR> } </BLOCKQUOTE><P><INPUT TYPE=submit value="Проголосовать"></form> </H3></body></html>

Обработка формы <%@ page import="java.util.*" %> <%@ page import="java.io.*" %> <%@ page contentType="text/html; charset=Windows-1251" %> <html><body> <H2>Опрос: выборы в Госдуму</H2> <%! String dataFile = "data.txt"; %> <% if(request.getParameter("party") != null){ String vote=request.getParameter("party"); if(vote!=null){ BufferedWriter save = new BufferedWriter(new FileWriter(dataFile,true)); save.write(vote+"\n"); save.close(); <P>Ваше мнение учтено.</P> } </H3></body></html>

Показ результатов опроса <%@ page import="java.util.*" %> <%@ page import="java.io.*" contentType="text/html; charset=Windows-1251" %> <html><body> <H2>Опрос: выборы в Госдуму</H2> <%! String dataFile = "data.txt"; %> <% if(request.getParameter("display") != null){ int[] votes = new int[parties.length+1]; BufferedReader data = new BufferedReader(new FileReader(dataFile)); String str; while( (str=data.readLine()) != null ){ int n = Integer.parseInt(str); if((n>0) && (n<=parties.length)){ votes[n]++; } } data.close(); <H3>Результаты опроса:</H3><OL> for(int i = 0; i < parties.length; i++) { <LI><%=parties[i]%>: <%=votes[i]%> голосов </H3></body></html>

Полный текст <%@ page import="java.util.*" %> <%@ page import="java.io.*" %> <%@ page contentType="text/html; charset=Windows-1251" pageEncoding="Windows-1251" %> <html><body><H2>Опрос: выборы в Госдуму</H2> <%! String dataFile = "data.txt"; String[] parties = {"Единая Россия", "Справедливая Россия", "КПРФ", "ЛДПР"}; %> <% Enumeration flds = request.getParameterNames(); if(!flds.hasMoreElements()) { // No fields <form method="GET" action="anketa.jsp"> <P>За какую партию Вы намерены голосовать:</P><BLOCKQUOTE> for(int i = 0; i < parties.length; i++) { <INPUT type="radio" id="party<%=i+1%>" name="party" value="<%=i+1%>"> <LABEL for="party<%=i+1%>"> <%=i+1%>. <%=parties[i]%></LABEL><BR> } </BLOCKQUOTE><P><INPUT TYPE=submit value="Проголосовать"></form> } else { if(request.getParameter("party") != null){ String vote=request.getParameter("party"); if(vote!=null){ BufferedWriter save = new BufferedWriter(new FileWriter(dataFile,true)); save.write(vote+"\n"); save.close(); <P>Ваше мнение учтено.</P> if(request.getParameter("display") != null){ int[] votes = new int[parties.length+1]; BufferedReader data = new BufferedReader(new FileReader(dataFile)); String str; while( (str=data.readLine()) != null ){ int n = Integer.parseInt(str); if((n>0) && (n<=parties.length)){ votes[n-1]++; data.close(); <H3>Результаты опроса:</H3><OL> <LI><%=parties[i]%>: <%=votes[i]%> голосов } } } </H3></body></html> Полный текст

Добавляем проверку повторного голосования. Рисование. <%@ page import="java.util.*" contentType="text/html; charset=Windows-1251" %> <html><body> <H2>Опрос: выборы в Госдуму</H2> <%! String[] parties = {"Единая Россия", "Справедливая Россия", "КПРФ", "ЛДПР"}; %> <% Cookie[] cookies = request.getCookies(); boolean voted = false; if(cookies != null){ for(int i=0;i<cookies.length;i++){ if(cookies[i].getName().equals("voted")){ voted = (cookies[i].getValue() != null); } }} if(voted){ out.println(“<P>Вы уже голосовали!</P>”);} else{ %> <form method="GET" action="anketa.jsp"><P>За какую партию Вы намерены голосовать:</P><BLOCKQUOTE> for(int i = 0; i < parties.length; i++) { <INPUT type="radio" id="party<%=i+1%>" name="party" value="<%=i+1%>"> <%=i+1%>. <%=parties[i]%><BR> </BLOCKQUOTE><P><INPUT TYPE=submit value="Проголосовать"></form> <% } %> </H3></body></html>

Установка Cookie <% if(request.getParameter("party") != null){ if(voted){ %> <P>Вы пытаетесь проголосовать повторно.</P> } else{ String vote=request.getParameter("party"); if(vote!=null){ Cookie cookie = new Cookie("voted","1"); cookie.setMaxAge(10*60*60*24); response.addCookie(cookie); BufferedWriter save = new BufferedWriter(new FileWriter(dataFile,true)); save.write(vote+"\n"); save.close(); <P>Ваше мнение учтено.</P>

Окончательный текст <%@ page import="java.util.*" %> <%@ page import="java.io.*" %> <%@ page contentType="text/html; charset=Windows-1251" pageEncoding="Windows-1251" %> <html><body> <H2>Опрос: выборы в Госдуму</H2> <%! String dataFile = "data.txt"; String[] parties = {"Единая Россия", "Справедливая Россия", "КПРФ", "ЛДПР"}; %> <% Cookie[] cookies = request.getCookies(); boolean voted = false; if(cookies != null){ for(int i=0;i<cookies.length;i++){ if(cookies[i].getName().equals("voted")){ voted = (cookies[i].getValue() != null); } }} Enumeration flds = request.getParameterNames(); if(!flds.hasMoreElements()) { // No fields if(voted){ <P>Вы уже голосовали!</P> else{ <form method="GET" action="anketa_cookie.jsp"> <P>За какую партию Вы намерены голосовать:</P><BLOCKQUOTE> for(int i = 0; i < parties.length; i++) { <INPUT type="radio" id="party<%=i+1%>" name="party" value="<%=i+1%>"> <LABEL for="party<%=i+1%>"> <%=i+1%>. <%=parties[i]%></LABEL><BR> </BLOCKQUOTE><P><INPUT TYPE=submit value="Проголосовать"></form> } else { if(request.getParameter("party") != null){ <P>Вы пытаетесь проголосовать повторно.</P> String vote=request.getParameter("party"); if(vote!=null){ Cookie cookie = new Cookie("voted","1"); cookie.setMaxAge(10*60*60*24); response.addCookie(cookie); BufferedWriter save = new BufferedWriter(new FileWriter(dataFile,true)); save.write(vote+"\n"); save.close(); <P>Ваше мнение учтено.</P> if(request.getParameter("display") != null){ int[] votes = new int[parties.length+1]; BufferedReader data = new BufferedReader(new FileReader(dataFile)); String str; while( (str=data.readLine()) != null ){ int n = Integer.parseInt(str); if((n>0) && (n<=parties.length)){ votes[n-1]++; data.close(); <H3>Результаты опроса:</H3><OL> <LI><%=parties[i]%>: <%=votes[i+1]%> голосов </H3></body></html>