1 / 74

Веб-разработка на Java

Высшая школа ИТИС. Лекция 2 – Технология Java Servlet 9 октября 2013. Веб-разработка на Java. Алина Витальевна Васильева доцент факультета Компьютерных Наук Латвийский Университет инженер-разработчик, Одноклассники, Mail.ru Group alina.vasiljeva@gmail.com. Introduction.

Download Presentation

Веб-разработка на Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Высшая школа ИТИС Лекция 2 – Технология Java Servlet 9 октября 2013 Веб-разработка на Java Алина Витальевна Васильева доцент факультета Компьютерных Наук Латвийский Университет инженер-разработчик, Одноклассники, Mail.ru Group alina.vasiljeva@gmail.com

  2. Introduction • Servlets are Java programs that run on a Web server, handle HTTP requests and build Web pages • Servlet specification versions • [version 1.0]June 1997 • [version 2.4 – Java2EE 1.4] November 2003 • [version 2.5 – Java EE 5] September 2005 • [version 3.0 –Java EE 6] December 2009 • [version 3.1 –Java EE 7] May 2013

  3. Java Enterprise Edition • Java EE is a comprehensive platform for multi-user, enterprise-wide applications • It is based on Java SE and adds APIs for Internet-based server-side computing http://docs.oracle.com/javaee/7/tutorial/doc/

  4. Web Application Internals

  5. Java Web Application Technologies Java Servlet technology is the foundation of all web application technologies

  6. What is a Servlet? • Java™ object which is based on a Servletframework and APIs and extends thefunctionality of a HTTP server • Mapped to URLs and managed bya container with a simple architecture • Available and running on all majorweb servers and application servers • Platform and server independent

  7. Creating a Project • A convenient way to develop, build, deploy and run Web application is by using: • Maven build tool http://maven.apache.org/ • Jetty web server http://www.mortbay.org/

  8. Creating a Project • Maven supports the notion of creating a complete project template with a simple command • To create a Web project template you need to use maven-archetype-webapp archetype • Type in a single line: mvn archetype:create -DgroupId=com.my-servlet-app -DartifactId=my-servlet-app -DarchetypeArtifactId=maven-archetype-webapp

  9. Maven Web Project Structure <root>/src/main/webapp/ - directory structure for a web module

  10. Web Module • According to Java EE architecture and Java Servlet Specification: • Web components and static web content files such asimages are called web resources • A web module is the smallest deployable andusable unit of web resources • Web module corresponds to a webapplication • A web module has a specific structure

  11. Web Module Structure • The top-level directory of a web moduleis the document root of the application • The document root contains: • JSP pages • client-side classes • client-side archives • static web resources

  12. Web Module Structure • The document root contains a subdirectory /WEB-INF/ • web.xml: web application deployment descriptor • lib: JAR archives of libraries called by server-side classes

  13. Web Module Structure • classes: server-side classes: • servlets • utility classes • JavaBeans components • tags: tag files, which are • implementations of • tag libraries

  14. Deployment • The process of running a web application is different from a traditional stand-alone Java classes • Web applications have to be installed or deployed to the web container • Aspects of web application behaviour can be configured during application deployment • The configuration information is maintained in a XML file called a web application deployment descriptor

  15. Deployment Descriptor: web.xml • Web applications are configured via deployment descriptor /WEB-INF/web.xml • Configuration options: • Map URLs to web components • Set initialization parameters • Map errors to error screens • Declare welcome files • Declare resource references

  16. web.xml in a Maven Project • A project generated by Maven already has a default “empty” web.xml file <web-app> <display-name> Archetype Created Web Application </display-name> </web-app>

  17. WAR Files • A web module can be deployed as an unpacked file structure or it can be packaged in an archive file known as a Web Archive File (WAR) • WAR file can be created by: • executing jar command • using Ant target • using IDE (Eclipse for instance) • using Maven

  18. Packaging using Maven • Executing the command mvn package creates a WAR file in a “target” directory

  19. Running with Jetty • Add the Jetty plugin to the pom.xml <build> <finalName>maven2example_webapp</finalName> <plugins> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>8.1.13.v20130916</version> </plugin> </plugins> </build>

  20. Running with Jetty • Execute mvn jetty:run command >mvn jetty:run [INFO] Scanning for projects... [INFO] ------------------------------------------------------- [INFO] Building maven2example_webapp Maven Webapp 1.0-SNAPSHOT [INFO] ------------------------------------------------------- [INFO] >>> jetty-maven-plugin:8.1.13.v20130916:run (default-cli) @ maven2example_webapp >>> ... ... 2013-10-01 12:14:02.035:INFO:oejs.AbstractConnector:Started SelectChannelConnector@0.0.0.0:8080 [INFO] Started Jetty Server Stop by Ctrl+C

  21. Opening the Application Open your web browser to http://localhost:8080/

  22. Setting a Context Root • A context rootidentifies a web application in a Java EE server • The server is responsible for mapping URL’s that start with a specific prefix to the location of a web application • Usually this is done with a web server configuration file

  23. Configuring a Context Root <build> <finalName>maven2example_webapp</finalName> <plugins> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>8.1.13.v20130916</version> <configuration> <scanIntervalSeconds>10</scanIntervalSeconds> <webApp> <contextPath>/my-super-app</contextPath> </webApp> </configuration> </plugin> </plugins> </build> Now valid URL is: http://localhost:8080/my-super-app

  24. Opening the Application Open your web browser to http://localhost:8080/

  25. Adding Java sources to a Project • Manually create a folder for Java classes \your_webapp\src\main\java • Servlet classes and other Java classes may be placed into this folder

  26. Adding Servlets to a Project • Add dependencies to Maven configuration file \your_webapp\pom.xml Servlet: <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> JSTL: <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> </dependency>

  27. Create Settings for Eclipse • In a project root execute: mvn eclipse:eclipse • This command will create Eclipse-related files: • \your_webapp\.project • \your_webapp\.classpath

  28. Develop • Import project and create servlets in src/main/java

  29. A Servlet that generates plain text import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class HelloServlet extendsHttpServlet { public void doGet(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Hello World!"); out.close(); } }

  30. Mapping Servlet to URL • When a request is received by the web container it must determine which web component should handle the request • Need to add a servlet definition and a servlet mapping for each servlet to web.xml file <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>my.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>

  31. Servlet 3.0 mapping style import java.io.*; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; @WebServlet("/hello2") public class HelloServlet2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body><h1>"+ "Hello World!</h1></body></html>"); out.close(); } } Deployment descriptor (web.xml) is optionalsince version 3.0

  32. What does Servlet do? • Receives a client request • mostly in the form ofHTTP request • Extracts some information from the request • Does content generation or business logic processing(possibly by accessing database, invoking EJBs,etc) • Creates and sends a response to a client (mostly in theform of HTTP response) or forwards the request toanother servlet or JSP page

  33. Requests and Responses • What is a request? • Information that is sent from client to a server • Who made the request • What user-entered data is sent • Which HTTP headers are sent • What is a response? • Information that is sent to client from a server • Text (HTML, plain) or binary (image) data • HTTP headers, cookies, etc

  34. Things to do in doGet() & doPost() • Extract client-sent information (HTTP parameter) from HTTP request • Set (save) and get (read) attributes to/from Scope objects • Perform some business logic or access database • Optionally forward the request to other Web components (Servlet or JSP) • Populate HTTP response message and send it to client

  35. Steps of Populating HTTP Response • Fill response headers • Set some properties of the response • Buffer size • Get an output stream object from the response • Write body content to the output stream PrintWriter out = response.getWriter(); out.println("Hello World!");

  36. Getting Request Parameters • A request can come with any number ofparameters • Parameters are sent from HTML forms: • GET: as a query string, appended to a URL • POST: as encoded POST data, not appeared in the URL • getParameter("paramName") • Returns the value of paramName • Returns null if no such parameter is present • Works identically for GET and POST requests

  37. Example 1: Welcome message @WebServlet("/welcome") public class WelcomeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ String name = request.getParameter("name"); if (name == null || "".equals(name.trim())){ name = "guest"; } PrintWriter out = response.getWriter(); out.println("<html><body><h1>" + "Welcome " + name + "!" + "</h1></body></html>"); out.close(); } }

  38. Example 2: User login • login.html <html> <head><title>Login</title></head> <body> <form action="/my-super-app/login" method="POST"> <p><label for="login">Login:</label><br> <input id="login" name="login" size="30" type="text"/></p> <p><label for="password">Password:</label><br> <input id="password" name="password" type="password"/></p> <p><input type="submit" value="Login"/></p> </form> </body> </html>

  39. Example 2: User login • LoginServlet.java @WebServlet("/login") publicclass LoginServlet extends HttpServlet { publicvoid doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ String login = request.getParameter("login"); String password = request.getParameter("password"); boolean isValid = checkPassword(login, password); String path = request.getContextPath(); if (isValid){ response.sendRedirect(path + "/login_ok.html"); } else{ response.sendRedirect(path + "/login_failed.html"); } }}

  40. Getting additional information • Client information • String request.getRemoteAddr() • String request.getRemoteHost() • Server information • String request.getServerName() • int request.getServerPort() • Misc • ServletInputStream getInputStream() • BufferedReader getReader() • String getProtocol() • String getContentType() • boolean isSecure()

  41. Getting additional information • Client information • String request.getRemoteAddr() • String request.getRemoteHost() • Server information • String request.getServerName() • int request.getServerPort() • Misc • ServletInputStream getInputStream() • BufferedReader getReader() • String getProtocol() • String getContentType() • boolean isSecure()

  42. Debugging Web App on Jetty • Set environment variable MAVEN_OPTS with value -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n • E.g. create a BAT file for running Jetty: set MAVEN_OPTS=-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n mvn jetty:run

  43. Debug configuration in Eclipse > Run > Debug Configurations…

  44. Debugging • Start Jetty • Launch Debug configuration in Eclipse

  45. Debugging • Add breakpoint, e.g. in Servlet code and send HTTP request • Server will stop at breakpoint

  46. Debugging

  47. Домашнее задание 1 Реализовать веб-приложение «Калькулятор», используя только технологии HTML и Java Servlet (JSP использовать нельзя). Базовая HTML страница должна содержать форму, которая включает в себя: • два поля, куда пользователь вводит два числа • четыре кнопки арифметических действий: + - * / Сервлет принимает запрос, совершает арифметическую операцию и возвращает пользователю HTML, содержащий: • результат вычислений • ссылку возврата к странице калькулятора Решение до 10 октября 17:00 = 5 пунктов Решение до 14 октября 17:00 = 3 пункта

  48. Demo Project [Option 1] Git repository: git clone https://github.com/avasiljeva/servlet_jsp_demo.git [Option 2] SVN repository: http://www.ante.lv/svn/files-ante-lv/trunk/servlet_jsp_demo SVN username/password: student/student

  49. RequestDispatcher • Applications are often composed of many Servlets working together • Forwarding a request to another Servlet is possible using RequestDispatcher • RequestDispatcherprimary functions • forward - complete transfer of control to another Servlet • include - insert result from running another Servlet into response

  50. Dispatching to another component publicclass ServletForward extends HttpServlet { publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ // pathname is relative to invoking servlet RequestDispatcher dispatcher = request.getRequestDispatcher("another_servlet"); dispatcher.forward(request, response); } }

More Related