Java EE Servlets

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
(Новая: In this part of the JEE tutorials we will introduce servlets. Servlets are backbones of the java web applications. A <b>servlet</b> is a specialized Java class. It is used to create dyn...)
(нарушало авторские права)
 
Строка 1: Строка 1:
-
In this part of the JEE tutorials we will introduce servlets. Servlets are backbones of the java web applications.
 
-
A <b>servlet</b> is a specialized Java class. It is used to create dynamic web applications.
 
-
The servlets work on a request - response programming model. They accept requests and create response to the clients. We will work with <b>HttpServlet</b>. It is an abstraction of all the details of the HTTP protocol.
 
-
 
-
By using servlets, we can separate business logic from the presentation part of the application.
 
-
We have access to the rich set of various java libraries.
 
-
 
-
== Simple Servlet ==
 
-
The following example will create a very basic java servlet. We define a form in our JSP file.
 
-
The form will send a request to the servlet. The servlet will output the parameters, we have specified  in the form.
 
-
<source lang="java">
 
-
* { font-size: 12px; font-family: Verdana }
 
-
input { border: 1px solid #ccc }
 
-
</source>
 
-
 
-
This is a simple stylesheet, that we use in this example.
 
-
 
-
<source lang="java">
 
-
 
-
<%@page contentType="text/html" pageEncoding="UTF-8"%>
 
-
 
-
<html>
 
-
<head>
 
-
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
-
<title>Simple Servlet</title>
 
-
<link rel="stylesheet" href="style.css" type='text/css'>
 
-
</head>
 
-
<body>
 
-
 
-
<form action="SimpleServlet" method="post">
 
-
<table>
 
-
<tr>
 
-
<td>Name</td>
 
-
<td><input type="text" name="name"></td>
 
-
</tr>
 
-
 
-
<tr>
 
-
<td>Message</td>
 
-
<td><input type="text" name="message"></td>
 
-
</tr>
 
-
</table>
 
-
<br>
 
-
<input type="submit" value="submit">
 
-
 
-
</form>
 
-
</body>
 
-
</html>
 
-
</source>
 
-
 
-
In this JSP file, we define a simple form. We have two parameters, name and message. These will be sent to the servlet in  the request object.
 
-
 
-
<source lang="java">
 
-
<form action="SimpleServlet" method="post">
 
-
</source>
 
-
 
-
This time we don't send a request to a JSP page. We send it to a servlet.
 
-
 
-
<source lang="java">
 
-
 
-
<?xml version="1.0" encoding="UTF-8"?>
 
-
<web-app>
 
-
    <servlet>
 
-
        <servlet-name>SimpleServlet</servlet-name>
 
-
 
-
        <servlet-class>com.zetcode.SimpleServlet</servlet-class>
 
-
    </servlet>
 
-
    <servlet-mapping>
 
-
        <servlet-name>SimpleServlet</servlet-name>
 
-
        <url-pattern>/SimpleServlet</url-pattern>
 
-
 
-
    </servlet-mapping>
 
-
    <welcome-file-list>
 
-
        <welcome-file>index.jsp</welcome-file>
 
-
    </welcome-file-list>
 
-
</web-app>
 
-
</source>
 
-
 
-
To use a servlet we must configure it in the web.xml. We define a servlet and a servlet mapping.
 
-
 
-
<source lang="java">
 
-
 
-
<?xml version="1.0" encoding="UTF-8"?>
 
-
 
-
<sun-web-app>
 
-
  <context-root>/servlets</context-root>
 
-
 
-
</sun-web-app>
 
-
</source>
 
-
 
-
Here we define the <b>context root</b>. The context root uniquely identifies a web application in a JEE server.
 
-
We can have several modules deployed on the server. The context root is their id.
 
-
 
-
<source lang="java">
 
-
protocol://host:port/contextroot/servletname
 
-
http://localhost:8080/servlets/SimpleServlet
 
-
</source>
 
-
 
-
This is the path to our servlet. This path will be in the location bar of the web browser if we click on the submit button of our form. We can call the servlet manually by simply typing the path to the location bar. In this case,  we won't have any output, because the parameters are not set.
 
-
 
-
<source lang="java">
 
-
package com.zetcode;
 
-
 
-
import java.io.*;
 
-
import java.net.*;
 
-
 
-
import javax.servlet.*;
 
-
import javax.servlet.http.*;
 
-
 
-
 
-
public class SimpleServlet extends HttpServlet {
 
-
 
-
 
-
    protected void processRequest(HttpServletRequest request,
 
-
                                  HttpServletResponse response)
 
-
                                      throws ServletException, IOException {
 
-
        response.setContentType("text/html;charset=UTF-8");
 
-
 
-
        PrintWriter out = response.getWriter();
 
-
 
-
        String name = request.getParameter("name");
 
-
        String message = request.getParameter("message");
 
-
 
-
        try {
 
-
            out.println("<html>");
 
-
            out.println("<head>");
 
-
            out.println("<title>SimpleServlet</title>"); 
 
-
            out.println("<link rel='stylesheet' href='style.css' type='text/css'>");
 
-
            out.println("</head>");
 
-
            out.println("<body>");
 
-
            if (name!=null && message!=null) {
 
-
                out.println(name + " Says:");
 
-
                out.println(message);
 
-
            }
 
-
            out.println("</body>");
 
-
            out.println("</html>");
 
-
 
-
        } finally {
 
-
            out.close();
 
-
        }
 
-
    }
 
-
 
-
    protected void doGet(HttpServletRequest request,
 
-
                        HttpServletResponse response)
 
-
                            throws ServletException, IOException {
 
-
        processRequest(request, response);
 
-
    }
 
-
 
-
 
-
    protected void doPost(HttpServletRequest request,
 
-
                          HttpServletResponse response)
 
-
                              throws ServletException, IOException {
 
-
        processRequest(request, response);
 
-
    }
 
-
}
 
-
 
-
</source>
 
-
 
-
This is the servlet that will handle the request from the client. The template of the class was created automatically by the Netbeans IDE. I have simplified it a bit.
 
-
We can have two HTTP methods. GET and POST. The <b>doGet()</b> method reacts to the GET method and  <b>doPost()</b> to the POST method. Usually we don't distinguish between them, so each of the two methods calls the <b>processRequest()</b> method. The doGet() and doPost() methods are called <b>service methods</b>. There are 4 other service methods, but they are not used often.
 
-
 
-
<source lang="java">
 
-
protected void processRequest(HttpServletRequest request,
 
-
                              HttpServletResponse response)
 
-
</source>
 
-
 
-
The method takes two parameters. The request object and the response object. The job of a service  method is to extract data from the request, access external resources if nessasary (e.g. a database) and populate a respose object.
 
-
 
-
<source lang="java">
 
-
response.setContentType("text/html;charset=UTF-8");
 
-
</source>
 
-
 
-
Here we specify the mime type and encoding. We will send back to the client html content in UTF-8 encoding.
 
-
 
-
<source lang="java">
 
-
PrintWriter out = response.getWriter();
 
-
</source>
 
-
 
-
We get the output stream. The html data is textual data. That's why we work with <b>PrintWriter</b>
 
-
If we need to work with binary data, we use a <b>ServletOutputStream</b> class. (For example, when we want to send an image.)
 
-
 
-
<source lang="java">
 
-
String name = request.getParameter("name");
 
-
String message = request.getParameter("message");
 
-
</source>
 
-
 
-
We get the parameters from the request, that we have sent from the form in the index.jsp page.
 
-
 
-
<source lang="java">
 
-
out.println("<html>");
 
-
out.println("<head>");
 
-
out.println("<title>SimpleServlet</title>"); 
 
-
out.println("<link rel='stylesheet' href='style.css' type='text/css'>");
 
-
out.println("</head>");
 
-
out.println("<body>");
 
-
if (name!=null && message!=null) {
 
-
    out.println(name + " Says:");
 
-
    out.println(message);
 
-
}
 
-
out.println("</body>");
 
-
out.println("</html>");
 
-
 
-
</source>
 
-
 
-
We create a html page by calling <b>println()</b> method on the output stream.
 
-
 
-
== Using NetBeans ==
 
-
We will use NetBeans to create, build and deploy our example.
 
-
 
-
[[image: java_ee_faq_newwebapp.png| center]]
 
-
 
-
 
-
First by clicking on the File - New Project... or pressing Ctrl + Shift + N we start a new project in NetBeans IDE.
 
-
NetBeans will create a new standard project. It will create ant scripts to automatically build, run and debug our project.
 
-
 
-
[[image: java_ee_faq_appname.png| center]]
 
-
 
-
Next we select a name and location for our project. We also can select a Java EE version and server name.
 
-
We can choose among Tomcat and GlassFish by default. We will work with GlassFish. We won't work with frameworks for now, so we can already click on the finish button. Frameworks will be menioned later in our JEE tutorials
 
-
 
-
[[image: java_ee_faq_newservlet.png| center]]
 
-
 
-
By right clicking on the name of the web application in the Projects window, we can select a new Servlet.
 
-
 
-
[[image: java_ee_faq_namelocat.png| center]]
 
-
 
-
We specify the name of a servlet and a location path. The name of our servlet will be SimpleServlet.
 
-
We also provide a package name for this servlet.
 
-
 
-
[[image: java_ee_faq_configureservlet.png| center]]
 
-
 
-
Here we specify the servlet mapping. This will be written to the web.xml file.
 
-
 
-
[[image: java_ee_faq_run.png| center]]
 
-
 
-
Finally we run the application. Press the green triangle in the build toolbar, or press <b>F6</b>.
 
-
This will build the application, start a server if necesarry and deploy it on the server.
 
-
 
-
[[Категория:Java]]
 

Текущая версия на 11:36, 7 апреля 2009