Servlets

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

How do you remove an attribute from the session?

// gets current session HttpSession session = request.getSession(); // removes saved object session.removeAttribute("objReferenceName");

How do we put an object into a session (from inside a servlet)?

// gets current session HttpSession session = request.getSession(); // saves object session.setAttribute("objReferenceName", obj);

What is a server?

A machine with server software on it.

What is the front controller design pattern?

Allows us to create a single servlet for all requests. Before responding from the servlet, we send the request and possibly response to a class we create called the RequestHelper. This class' job is to parse the URI of the request using a switch statement, then send the req and resp to a controller class. We create a series of controller classes (LoginController) to handle specific logic relevant to the requested action. The controller then returns to the RequestHelper and the RequestHelper returns to the servlet the response.

What is the difference between XML and HTML?

Extensible Markup Language describes the data while HyperText Markup Language displays the data.

How would you preinitialize/preload a servlet?

The servlet specification defines the <load-on-startup> element which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. Inside of the <servlet> block with the name of the servlet you would like to load, set <load-on-startup> to a non-negative integer to preinitialize the servlet. Or set the <load-on-startup> to a negative integer if you want the servlet to load upon being requested for the first time.

What is the HTTP 'GET' method?

The GET method sends the encoded user information appended to the page request. Encoded information is separated by the '?' symbol.

What are the two most commonly implemented abstract methods overridden by classes extending HTTPServlet?

doGet() and doPost()

How do you close a session?

// gets current session HttpSession session = request.getSession(); // closes current session session.invalidate();

How do we get an object from a session (from inside a servlet)?

// gets current session HttpSession session = request.getSession(); // gets saved object session.getAttribute("objReferenceName");

What are some important tags needed to register a servlet inside of your deployment descriptor?

<servlet>, <servlet-name>, <servlet-class>, <servlet-mapping>, <url-pattern>, <load-on-startup> Wrap the <servlet-name>, <servlet-class>, and <load-on-startup> inside of <servlet> Wrap the <servlet-name> and <url-pattern> inside of <servlet-mapping>

How do I register a single servlet with multiple paths?

<url-pattern>*.yoursuffix</url-pattern>

What is a servlet?

A Java class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Servlets act as a middle layer between a request from a client and an application on a server. They read the explicit data sent by the clients, such as the data in an HTML form, and the implicit data sent by the clients such as cookies. Process the data and generate the results by invoking a webservice or computing the response directly. Send the explicit data to the clients in a variety of formats such as text or binary, and the implicit data, such as the content type and caching policies.

What is the difference between RequestDispatcher.forward() and HttpServletResponse.sendRedirect()?

An important difference between RequestDispatcher.forward() and HttpServletResponse.sendRedirect() is that forward() is handled completely on the server side while redirect() sends a redirect message to the browser. In that sense, forward() is transparent to the browser while redirect() is not. From client perspective during a forward(), only one http request and response are handled. As a result the url will not change. The forward() cannot go to any entity outside of the server. From client perspective during a redirect(), two http requests and two http responses are handled. As a result the url WILL change. The redirect() can travel to an endpoint outside of the server. Forward is declared in the RequestDispatcher interface while sendRedirect is declared in HttpServletResponse. req.getRequestDispatcher(*path*).forward(req, resp); and resp.sendRedirect(*path*);

What is Tomcat?

An open source software implementation of the Java Servlet and JSP technologies. It acts as our web and servlet container. It can act as a standalone server. A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access-rights.

What is the web.xml, and what is another name for it?

Deployment Descriptor - A configuration file that lives in the WEB-INF folder

What is the difference between HTTP GET and HTTP POST?

GET" is basically for just getting (retrieving) data whereas "POST" may involve anything, like storing or updating data, or ordering a product, or sending E-mail. The HTML specifications technically define the difference between "GET" and "POST" so that former means that form data is to be encoded (by a browser) into a URL while the latter means that the form data is to appear within a message body. But the specifications also give the usage recommendation that the "GET" method should be used when the form processing is "idempotent" (i.e. it has no lasting observable effect on the state of the world), and in those cases only. If the processing of a form is idempotent (i.e. it has no lasting observable effect on the state of the world), then the form method should be GET. Many database searches have no visible side-effects and make ideal applications of query forms. If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST

How does the web application know where to look for the web page to load upon visiting the page of the application?

Inside the web.xml, the application checks for the path to the html file referenced within the <welcome-file> tag.

Name some important tags in ServletConfig.

Inside web.xml and inside a servlet tag: <init-param> <param-name> <param-value> </init-param>

Name some important tags inside ServletContext.

Inside web.xml and outside all servlet tags: <context-param> <param-name> <param-value> </context-param>

When a servlet container handles multiple requests for a particular servlet, does it create a new instance of the servlet?

No, the servlet container spawns multiple threads, each executing the service() method of a single instance of the servlet.

How would you write a direct message back to the browser from inside of a servlet?

PrintWriter out = response.getWriter(); Use out.println("stuff") to send content to the browser

In what ways can a servlet react to an incoming HttpRequest?

Send direct messages, forward(), or redirect()

What is the hierarchy of Servlets in Java?

Servlet (interface) => GenericServlet (AbstractClass) => HttpServlet (AbstractClass) => MyCustomServlet (Class) Servlet (interface): javax.servlet.Servlet is the central interface in the Servlet API. Every servlet class must directly or indirectly implement this interface. It has five methods: init(), service(), destroy(), getServletConfig(), and getServletInfo(). The service (ServletRequest, ServletResponse) method handles requests and creates responses. The servlet container automatically calls this method when it gets any request for this servlet. GeneriServlet: javax.servlet.GenericServlet class implements the Servlet interface. It is an abstract class that provides implementation for all methods except the service () method of the Servlet interface. We can extend this class and implement the service () method to write any kind of servlet. HTTP Servlet: javax.servlet.http.HTTPServlet represents a HTTP capable servlet and is an abstract class that extends GenericServlet. It provides the support for HTTP protocol. It adds a new service () method with the signature: service (HttpServletRequest, HttpServletResponse). For every HTTP method, there is a corresponding method in the HTTPServlet class, e.g.; doGet (), doHead (), doPost (), doDelete (), doPut (), doOptions () and doTrace (). Depending on the HTTP method, the corresponding doXXX () method is called on the servlet.

What is the difference between ServletContext and ServletConfig?

Servlet Context is an object that all servlets may see (like a variable global to all servlets on the web application). Created at the time of web application deployment. Servlet Config is an object that exists within the scope of a single servlet (localized to the specific servlet class). Created during initialization of the servlet.

What is a ServletContext in detail?

ServletContext interface is a window for a servlet to view its environment. Every web application has one and only one ServletContext and it is available to all the active resources of that application. It is also used by the servlets to share data with one another. A servlet can use this interface to get information such as initialization parameters for the web application or the servlet container's version. This interface also provides utility methods for retrieving MIME type for a file, for retrieving shared resources, for logging and so forth.

What is the HTTP 'POST' method?

The POST method packages information like a GET method, but instead of sending it in the URL, it sends it as a separate message.

What is a ServletConfig in detail?

The ServletConfig is defined in the javax.servlet package. It provides four methods: getInitParameter (String), Enumeration getInitParameterNames (), getServletContext () and getServletName (). A servlet container takes information specified about a servlet in the deployment descriptor and wraps it into a ServletConfig object. This information can then be retrieved by the servlet at the time of its initialization. It is passed as parameter to the init method: init(javax.servlet.ServletConfig).

How does the RequestDispatcher forward() method work?

The client calls Servlet A for some information. Servlet A cannot honor the request but it knows Servlet B can. Servlet A forwards the request to Servlet B which processes the request and sends the response back to Servlet A who returns it without the client knowing that a different servlet processed the request.

Tell me about yourself.

This is a simple guide on how to approach this: - Full Name - College/Degree - Position - Technologies used - Projects you worked on and implemented these technologies - Any other relevant experience

How can you pre-initialize values in a servlet?

Using the ServletConfig object or override the no-arg init() method. Nerver override the init(ServletConfig) method, as this is used by the servlet container to initialize a servlet using web.ml init-param's

What are three methods that you can use to read form data using a servlet?

getParameter() - gets the value of a form parameter getParameterValues() - if a parameter appears more than once, it will return the values of all parameters with that name getParameterNames() - returns a complete list of all parameters in the current request

What is the life cycle of a Servlet?

init(), service(), destro() init(): called exactly once in the lifecycle to instantiate the servlet. It's called when the web container starts (if load-on-startup is a non-negative integer) OR it is called when it is being requested for the first time (if load-on-startup is a negative integer) service(servletRequest, servletResponse): is called to handle the servlet's logic; among its jobs is to parse the HTTP request to determine which doXXX() method needs to be called to perform the logic contained. The service() method is called as many times as the servlet is requested during the lifecycle of a servlet. destroy(): called exactly once in the lifecycle of a servlet. It is either called when the web container is terminating or if there is a fatal error within the servlet (to force the servlet to restart) This method has the servlet close database connections and perform other cleanup activities.

What packages that come with Java EE allow you to create Servlets?

javax.servlet and javax.servlet.http packages

What are the method signatures used when overriding the HTTPServlet methods doGet() and doPost()

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {} protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {}

How do we send a JSON from a servlet?

res.setContentType("application/json"); MyClass obj = new MyClass(); res.getWriter().write(new ObjectMapper().writeValueAsString(obj)); ObjectMapper is from a dependency you put into the pom.xml (Jackson is the dependency)

What do you get when you use the HttpSession getSession() method?

the getSession() method returns the current session associated with the request, or if the request does not have a session, it creates one.


संबंधित स्टडी सेट्स

Biology Quiz 2 - Animal-like Protists

View Set

Culture Politics During the Time of Jesus

View Set

cell and molecular unit 1 practice problems

View Set

Chapter 11 - Juggling Stress, family, and work

View Set

Preguntas Examen Teórico de Conducción 1

View Set

Human Communication: The Basic Course (Chapter 13)

View Set