The HttpSession interface can be used to view and manipulate information about a session such as the session identifier and creation time, and to bind objects to the session. A new session object may be created
The session.setAttribute and session.getAttribute methods are used to bind objects to the session.
A servlet may forward a request to another servlet if further processing is required. You can achieve this by dispatching the request to a different resource using RequestDispatcher, which can be obtained from HttpServletRequest.getRequestDispatcher or ServletContext.getRequestDispatcher. The former can accept a relative path, whereas the latter can accept a path relative to the current context only
In this code, bank is another servlet deployed in the same context.
The ServletContext.getContext method can be used to obtain ServletContext for foreign contexts. It can then be used to obtain a RequestDispatcher, which can dispatch requests in that context.
In servlet - part 01 we use anotation for servlet to mapping servlet. In here we use xml for those purpose. This xml file we call as deployment descriptor of the web application (web.xml). That file responsible for mapping the servlet for the requests. This xml contain the description abouth the application's servlets. keep it remember like that.
Ok lest get understanding about web.xml by an example. Open the netbeans IDE and create a java web application project like i said before in the part 01. Then create a servlet. Befor you create a servlet you should do this as following.
After you did this got to webpages » WEB-INF » web.xml
this is my web.xml for the newly created "NewServlet"
in the "servlet" tag you define a servlet class and defind a name for that. Then Servlet container knows where the our NewServlet is located. in "servlet-mapping" tag define the mapping part for the servlet definded in the "servlet" tag. Using the definded servlet name set a url pattern for it.
can u remember that how u did this with anotation in servlet-part-01 ? i feel it is easy than this. :) .
Before we concern about servlet containr we need to know what is the server?
ok when we load a web page using a web browser that web page comming from a web server. Web servers use HTTP protocal for transfer data between server and the client (browser).
generally web server send us to a static pages. That is not enough. Because we don't need always static pages. We need to dynamic pages ( web page based on user input). So that is done by servlet container (genarate dynamic pages).
So u can see that servlet container embeded inside Web Server. Servlet generate dynamic pages based on user input that pages send to the client by web server.
So a servlet is a component that is hosted in a servlet container to generate pages. The client interact with servlet by request/response.
The servlet container is responsible for the life cycle of the servlet, receives requests and sends responses, and performs any other encoding/decoding required as part of that.
POJO is a normal Java object class (that is, not a JavaBean, EntityBean etc.) and does not serve any other special role nor does it implement any special interfaces of any of the Java frameworks.
A servlet is defined using the @WebServlet annotation on a POJO, and must extend the
javax.servlet.http.HttpServlet class.
This is a sample definition of a servlet
1: @WebServlet("/hello")
2: public class HelloServlet extends javax.servlet.http.HttpServlet {
3: //. . .
4: }
Acording to above servlet client can interact with "HelloServlet" using the url "www.example.com/hello".
in here "/hello" is the url pattern. A servlet can have multiple url pattern. That kind of servlet can be definne as follow.
1: @WebServlet(urlPatterns={"/hello", "/helloworld"})
2: public class HelloServlet extends javax.servlet.http.HttpServlet {
3: //. . .
4: }
Then client can interact with this servlet by using two url pattern ("hello","helloworld").
HTTPServlet interface has some methods to override for handling the http requests.So what are http request types ?
Request Type
Description
Get
The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data.
POST
A POST request is used to send data to the server, for example, customer information, file upload, etc. using HTML forms.
HEAD
Same as GET, but transfers the status line and header section only.
PUT
Replaces all current representations of the target resource with the uploaded content.
DELETE
Removes all current representations of the target resource given by a URI.
CONNECT
Establishes a tunnel to the server identified by a given URI.
OPTIONS
Describes the communication options for the target resource.
TRACE
Performs a message loop-back test along the path to the target resource.
so you can handle these request by servlet by overriding "doGet() , doPost() , doPut() ... ". Web developer more concern about the Get and Post method. So following example shows you how you handle Get request.
@WebServlet("/hello")
public class Hello extends javax.servlet.http.HttpServlet {
@Override
protected void doGet(HttpServletRequest request,HttpServletResponse response) {
//. . .
}
}
in here you can see that doGet method has two parameter
HttpServletRequest - capture web client request
HttpServletResponse - capture the web client response
The request parameters; HTTP headers; different parts of the path such as host,port, and context; and much more information is available from HttpServletRequest.
The developer is responsible for populating the HttpServletResponse, and the container then transmits the captured HTTP headers and/or the message body to the client.
Following example show you how to populate sample response to client for a get request
in this example response object has method call getWriter(). That method returns PrintWriter object using that object we can create dynamic page content.
So, Now you now how to handle http request. So Now you think how to create dynamic page content acording to the user input. ok. one thing you need to know is there is a way to get request parameter. Request paramter is user data which is client send to server.
Following example will clear your doutes about above mentioned.
We are doing this example with NetBeans IDE. If you haven't it download from here.
First step open the netbean IDE and go to file -> New project -> click Java Web -> Wen Application then Click Next. Then Put a Name for the project then click next. Then click finish.
Then expand the project and Right Click on Source Packages -> New -> Servlet->Put a name and package name and finish. Now Your project will look like this.
Now you can run the project. Makesure "urlPattern = {"/"}" . Result will look like this.
Now modify the processRequest() method.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Index</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Index at " + request.getContextPath() + "</h1>");
if(request.getParameter("name") != null){
out.println("<h1>My name is " + request.getParameter("name")+ "</h1>");
}
out.println("</body>");
out.println("</html>");
}
}
Now Run the project again. Now project result is Look like before. Now change the url by appending " ?name=Text". Check the following screenshot.
This Tutorial Series based on the "Java EE 7 Essentials" by Arun Gupta.
JEE provides a standards-based platform for developing web and enterprise applications. These applications are typically designed as multitier applications, with a frontend tier consisting of a web framework, a middle tier providing security and transactions, and a backend tier providing connectivity to a database or a legacy system. These applications should be responsive and capable of scaling to accommodate the growth in user demand. The Java EE platform defines APIs for different components in each tier, and also provides some additional services such as naming, injection, and resource management that span across the platform. These components are deployed in containers that provide runtime support. Containers provide a federated view of the underlying Java EE APIs to the application components. Java EE application components never interact directly with other Java EE application components. They use the protocols and methods of the container for interacting with each other and with platform services. Interposing a container between the application components and the Java EE services allows the container to transparently inject the services required by the component, such as declarative transaction management, security checks, resource pooling, and state management. This container-based model and abstraction of resource access allows the platform to offload the developer from common infrastructure tasks.
Java EE architecture
Different components can be logically divided into three tiers: backend tier, middle tier, and web tier. This is only a logical representation, and the components can be restricted to a different tier based upon the application’s requirements.
JPA and JMS provide the basic services such as database access and messaging. JCA allows connection to legacy systems. Batch is used for performing noninteractive, bulk-oriented tasks.
Managed Beans and EJB provide a simplified programming model using POJOs to use the basic services.
CDI, Interceptors, and Common Annotations provide concepts that are applicable to a wide variety of components, such as type-safe dependency injection, addressing cross-cutting concerns using interceptors, and a common set of annotations. Concurrency Utilities can be used to run tasks in a managed thread. JTA enables Transactional Interceptors that can be applied to any POJO.
CDI Extensions allow you to extend the platform beyond its existing capabilities in a standard way. Web Services using JAX-RS and JAX-WS, JSF, JSP, and EL define the programming model for web applications. Web Fragments allow automatic registration of thirdparty web frameworks in a very natural way. JSON provides a way to parse and generate JSON structures in the web tier. WebSocket allows the setup of a bidirectional, full-duplex communication channel over a single TCP connection.
Bean Validation provides a standard means to declare constraints and validate them across different technologies.
The main features of JEE 7
Java API for WebSocket
Enables a WebSocket client and server endpoint to be defined declaratively via annotations on a POJO, or programmatically via interface implementation.
Provides server-specific configuration, such as mapping that identifies a Web‐Socket endpoint in the URI space of the container, subprotocols supported by the endpoint, and extensions required by the applications.
Offers client-specific configurations such as providing custom configuration algorithms.
Enables packaging and deployment on JDK or web containers.
Allows for integration with existing Java EE technologies.
Java API for JSON Processing
The streaming API provides a way to parse and generate JSON in a streaming fashion.
The Object Model API creates a random-access, tree-like structure that represents the JSON data in memory.
Batch Applications for Java Platform
Allows for description of a Batch Job using Job Specification Language defined by an XML schema. It defines a complete execution sequence of the jobs.
Features the Batch Programming Model using interfaces, abstract classes, and field annotations.
Offers the Chunked and Batchlet job-processing styles.
Concurrency Utilities for Java EE
Provides concurrency capabilities to Java EE application components, without compromising container integrity.
Defines managed objects: ManagedExecutorService, ManagedScheduledExecutorService, ContextService, and ManagedThreadFactory.
Java API for RESTful Web Services
Offers a new Client API that can be used to access web resources and providesintegration with JAX-RS providers.
Supports asynchronous processing in both the Client API and the Server API.
Defines Message Filters and Entity Interceptors as extension points to customize the request/response processing on the client and server side.
Supports new server-side content negotiation using qs factor.
Enables declarative validation of fields, properties, and parameters injected using @HeaderParam, @QueryParam, etc. Resource classes may be annotated with constraint annotations.
Java Message Service
Several changes have been made to make the API simpler and easier to use. For example, Connection, Session, and other objects with a close method now implement the java.lang.Autocloseable interface to allow them to be used in a Java SE 7 try-with-resources statement. New methods have been added to create a session without the need to supply redundant arguments. A new method, getBody, has been added to allow an application to extract the body directly from a Message without the need to cast it first to an appropriate subtype.
A message producer can now specify that a message must not be delivered until after a specified time interval.
New send methods have been added to allow an application to send messages asynchronously.
JMS providers must now set the JMSXDeliveryCount message property.
Expression Language
Expression Language (EL) is a specification of its own. It can be configured and used outside of a Java EE container using ELProcessor.
The lambda syntax is now included in EL. Using lambdas, a complete set of collection operations, such as map and filter is now supported.
In addition to the usual arithmetic and comparison operators, new operators —such as an assignment operator and string concatenation operator—have been added to make EL more expressive.
Enterprise JavaBeans
Support for EJB 2.1, EJB QL, and JAX-RPC-based Web Service endpoints and client view is now optional.
Enhanced message-driven beans (MDBs) contract with a no-method message listener interface to expose all public methods as message listener methods. This will allow custom Resource Adapters for future MDBs.
EJB API Groups have been defined with clear rules for an EJB Lite Container to support other API groups. This will help define how EJB features beyond EJB Lite can be officially added to a product that does not support full Java EE Profile.
Asynchronous session bean invocations and nonpersistent EJB Timer Service are included in EJB Lite.
An option has been added to disable passivation of stateful session beans.
Servlets
Defines a standard mechanism to upgrade existing HTTP connection to a different
protocol using HttpUpgradeHandler.
Offers nonblocking request and response processing for async servlets.
Defines rules for which HTTP methods are covered by .
JavaServer Faces
Faces Flow provides an encapsulation of related views/pages with applicationdefined entry and exit points.
Resource Library Contracts enable developers to apply facelet templates to an entire application in a reusable and interchangeable manner.
HTML5-friendly markup allows near-total control over the user experience of each individual element in the view.
Stateless Views mean developers no longer have to save the UIComponent state. This allows applications with JavaScript components to manage the state instead of JSF doing it for them.
Java Persistence
Database schema and tables may be generated by using javax.persistence.schema-generation.* properties.
Unsynchronized Persistence Contexts mean a persistence context does not have to be enlisted in a transaction. Such persistence contexts can explicitly join a transaction.
Bulk update/delete is supported via Criteria API.
Predefined and user-defined functions can be invoked using FUNCTION.
Stored procedures can be invoked using StoredProcedureQuery and @NamedStoredProcedureQuery.
Interceptors
Associating interceptors using InterceptorBinding is now part of this specification, instead of CDI.
@AroundConstruct designates an interceptor method that receives a callback when the target class constructor is invoked.
Method-level interceptors can be extended to life-cycle callbacks, adding constructor-level interceptors.
Priority ranges can be dedicated for ordering interceptors using interceptorbinding.
Contexts and Dependency Injection
Allows for automatic enabling of CDI for beans with a scope annotation, and EJBs, in Java EE.
Supports global ordering and enabling of interceptors, decorators, and alternatives using the @Priority annotation.
Adds the @Vetoed annotation, allowing easy programmatic disabling of classes.
Bean Validation
Validation constraints can be applied to the parameters and return values of arbitrary methods and constructors.
Integration points with CDI have been increased and reworked.
The targeted group can be altered when validation cascading is happening.
Java Transaction
@Transactional provides the application to declaratively control transaction boundaries on CDI-managed beans, as well as classes defined as managed beans by the Java EE specification, at both the class and method level where method-level annotations override those at the class level.
@TransactionScoped is a new CDI scope that defines bean instances whose life cycle is scoped to the currently active JTA transaction.
JavaMail
@MailSessionDefinition and @MailSessionDefintions defines MailSession to be registered with JNDI.
Java EE Connector Architecture
Provides @AdministeredObjectDefinition, @AdministeredObjectDefintions, @ConnectorFactoryDefinition, and @ConnectorFactoryDefinitions to define a connector-administered object and factory to be registered in JNDI.