740 likes | 752 Views
Высшая школа ИТИС. Лекция 2 – Технология Java Servlet 9 октября 2013. Веб-разработка на Java. Алина Витальевна Васильева доцент факультета Компьютерных Наук Латвийский Университет инженер-разработчик, Одноклассники, Mail.ru Group alina.vasiljeva@gmail.com. Introduction.
E N D
Высшая школа ИТИС Лекция 2 – Технология Java Servlet 9 октября 2013 Веб-разработка на Java Алина Витальевна Васильева доцент факультета Компьютерных Наук Латвийский Университет инженер-разработчик, Одноклассники, Mail.ru Group alina.vasiljeva@gmail.com
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
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/
Java Web Application Technologies Java Servlet technology is the foundation of all web application technologies
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
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/
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
Maven Web Project Structure <root>/src/main/webapp/ - directory structure for a web module
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
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
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
Web Module Structure • classes: server-side classes: • servlets • utility classes • JavaBeans components • tags: tag files, which are • implementations of • tag libraries
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
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
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>
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
Packaging using Maven • Executing the command mvn package creates a WAR file in a “target” directory
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>
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
Opening the Application Open your web browser to http://localhost:8080/
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
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
Opening the Application Open your web browser to http://localhost:8080/
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
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>
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
Develop • Import project and create servlets in src/main/java
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(); } }
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>
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
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
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
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
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!");
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
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(); } }
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>
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"); } }}
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()
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()
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
Debug configuration in Eclipse > Run > Debug Configurations…
Debugging • Start Jetty • Launch Debug configuration in Eclipse
Debugging • Add breakpoint, e.g. in Servlet code and send HTTP request • Server will stop at breakpoint
Домашнее задание 1 Реализовать веб-приложение «Калькулятор», используя только технологии HTML и Java Servlet (JSP использовать нельзя). Базовая HTML страница должна содержать форму, которая включает в себя: • два поля, куда пользователь вводит два числа • четыре кнопки арифметических действий: + - * / Сервлет принимает запрос, совершает арифметическую операцию и возвращает пользователю HTML, содержащий: • результат вычислений • ссылку возврата к странице калькулятора Решение до 10 октября 17:00 = 5 пунктов Решение до 14 октября 17:00 = 3 пункта
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
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
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); } }