`

Servlet 3.0 Demo

 
阅读更多

A servlet is a Java class that is used to extend the capabilities of servers that host applications. Servlets can respond to requests and generate responses. The base class for all servlets is javax.servlet.GenericServlet. This class defines a generic, protocol-independent servlet.

1.Maven Dependency

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.fool.servlet</groupId>
	<artifactId>servlet</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<dependencies>
        <dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.2.1</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>

	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.0</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

 

2.Project Directory


  

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>servlet</display-name>
	<servlet>
		<servlet-name>SimpleServlet</servlet-name>
		<servlet-class>org.fool.simpleservlet.servlet.SimpleServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>SimpleServlet</servlet-name>
		<url-pattern>/simpleservlet</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>dataentry.html</welcome-file>
	</welcome-file-list>
</web-app>

 

3.Demo

Demo01 - Configuring the servlet via XML

SimpleServlet.java

package org.fool.simpleservlet.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SimpleServlet extends HttpServlet
{
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<h2>");
		out.println("Hello World");
		out.println("</h2>");
	}
}

web.xml

...
<servlet>
    <servlet-name>SimpleServlet</servlet-name>
    <servlet-class>org.fool.simpleservlet.servlet.SimpleServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>SimpleServlet</servlet-name>
    <url-pattern>/simpleservlet</url-pattern>
  </servlet-mapping>
...

result

http://localhost:8080/servlet/simpleservlet


 

Demo02 - @WebServlet annotation

SimpleAnnotationServlet.java

package org.fool.simpleservlet.annotation;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "SimpleAnnotationServlet", urlPatterns = {
		"/simpleannotationservlet", "*.foo" })
public class SimpleAnnotationServlet extends HttpServlet
{

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<h2>");
		out.println("Hello Servlet 3.0 WebServlet Annotation");
		out.println("</h2>");
	}

}

result

http://localhost:8080/servlet/simpleannotationservlet

http://localhost:8080/servlet/test.foo

 

Demo03 - request.getParameter()
FormHandlerServlet.java

package org.fool.simpleservlet.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/formhandlerservlet")
public class FormHandlerServlet extends HttpServlet
{
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		String enteredValue = request.getParameter("enteredValue");

		response.setContentType("text/html");

		PrintWriter out = response.getWriter();
		out.println("<p>");
		out.println("You entered: ");
		out.println(enteredValue);
		out.println("</p>");

	}
}

web.xml

...
  <welcome-file-list>
    <welcome-file>dataentry.html</welcome-file>
  </welcome-file-list>
...

dataentry.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Data Entry Page</title>
</head>
<body>
	<form action="formhandlerservlet" method="get">
		<table>
			<tr>
				<td>Please enter some text:</td>
				<td><input type="text" name="enteredValue" /></td>
			</tr>
			<tr>
				<td></td>
				<td><input type="submit" value="Submit" /></td>
			</tr>
		</table>
	</form>
</body>
</html>

result

http://localhost:8080/servlet/


 

Demo04 - request.getParameterValues()

MultipleValueFieldHandlerServlet.java

package org.fool.simpleservlet.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/multiplevaluefieldhandlerservlet")
public class MultipleValueFieldHandlerServlet extends HttpServlet
{

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		String[] selectedOptions = request.getParameterValues("options");

		response.setContentType("text/html");

		PrintWriter out = response.getWriter();

		out.println("<p>");
		out.print("The following options were selected:");
		out.println("<br>");

		if (selectedOptions != null)
		{
			for (String option : selectedOptions)
			{
				out.print(option);
				out.print("<br>");
			}
		}
		else
		{
			out.println("None");
		}

		out.println("</p>");
	}

}

multiplevaluedataentry.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Multiple Value Submission Demo</title>
</head>
<body>
<form action="multiplevaluefieldhandlerservlet" method="post">
	<table>
   		<tr>
   			<td><input name="options" type="checkbox" value="option1" />Option 1</td>
  		</tr>
  		<tr>
    		<td><input name="options" type="checkbox" value="option2" />Option 2</td>
  		</tr>
  		<tr>
    		<td><input name="options" type="checkbox" value="option3" />Option 3</td>
  		</tr>
  		<tr>
    		<td><input type="submit" value="Submit" /></td>
    		<td></td>
  		</tr>
    </table>
	</form>
</body>
</html>

result

http://localhost:8080/servlet/multiplevaluedataentry.html

 
 

Demo05 - Request forwarding

MultipleValueFieldHandlerServlet2.java

package org.fool.simpleservlet.requestforward;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/multiplevaluefieldhandlerservlet2")
public class MultipleValueFieldHandlerServlet2 extends HttpServlet
{

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		String[] selectedOptions = request.getParameterValues("options");

		List<String> selectedOptionLabels = null;

		if (selectedOptions != null)
		{
			selectedOptionLabels = new ArrayList<>(selectedOptions.length);

			for (String selectedOption : selectedOptions)
			{
				if (selectedOption.equals("option1"))
				{
					selectedOptionLabels.add("Option 1");
				}
				else if (selectedOption.equals("option2"))
				{
					selectedOptionLabels.add("Option 2");
				}
				else if (selectedOption.equals("option3"))
				{
					selectedOptionLabels.add("Option 3");
				}
			}
		}

		request.setAttribute("checkedLabels", selectedOptionLabels);

		request.getRequestDispatcher("confirmationservlet").forward(request,
				response);
	}

}

 ConfirmationServlet.java

package org.fool.simpleservlet.requestforward;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/confirmationservlet")
public class ConfirmationServlet extends HttpServlet
{

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		@SuppressWarnings("unchecked")
		List<String> checkedLabels = (List<String>) request
				.getAttribute("checkedLabels");

		response.setContentType("text/html");

		PrintWriter out = response.getWriter();
		out.println("<p>");
		out.print("The following options were selected: ");
		out.println("<br>");

		if (checkedLabels != null)
		{
			for (String optionLabel : checkedLabels)
			{
				out.print(optionLabel);
				out.println("<br>");
			}
		}
		else
		{
			out.println("None");
		}

		out.println("</p>");
	}

}

 multiplevaluedataentry2.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Multiple Value Submission Demo2</title>
</head>
<body>
<form action="multiplevaluefieldhandlerservlet2" method="post">
	<table>
   		<tr>
   			<td><input name="options" type="checkbox" value="option1" />Option 1</td>
  		</tr>
  		<tr>
    		<td><input name="options" type="checkbox" value="option2" />Option 2</td>
  		</tr>
  		<tr>
    		<td><input name="options" type="checkbox" value="option3" />Option 3</td>
  		</tr>
  		<tr>
    		<td><input type="submit" value="Submit" /></td>
    		<td></td>
  		</tr>
    </table>
	</form>
</body>
</html>

 result

http://localhost:8080/servlet/multiplevaluedataentry2.html

 

Demo06 - Response redirection
ResponseRedirectionServlet.java

package org.fool.simpleservlet.responseredirection;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/responseredirectionservlet")
public class ResponseRedirectionServlet extends HttpServlet
{

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		String url = request.getParameter("searchEngine");

		if (url != null)
		{
			response.sendRedirect(url);
		}
		else
		{
			PrintWriter out = response.getWriter();
			out.println("No search engine was selected.");
		}
	}

}

 index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Response Redirection Demo</title>
</head>
<body>
	<form method="post" action="responseredirectionservlet">
		Please indicate your favorite search engine.
		<table>
			<tr>
				<td><input type="radio" name="searchEngine"
					value="http://www.google.com" checked="checked">Google</td>
			</tr>
			<tr>
				<td><input type="radio" name="searchEngine"
					value="http://www.msn.com">MSN</td>
			</tr>
			<tr>
				<td><input type="radio" name="searchEngine"
					value="http://www.yahoo.com">Yahoo!</td>
			</tr>
			<tr>
				<td colspan="2"><input type="submit" value="Submit" /></td>
			</tr>
		</table>
	</form>
</body>
</html>

 result

http://localhost:8080/servlet/index.html


 

 Demo07 - Passing initialization parameters to a servlet via annotations

 InitParamsServlet.java

package org.fool.simpleservlet.initparam;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/initparamsservlet", initParams = {
		@WebInitParam(name = "param1", value = "value1"),
		@WebInitParam(name = "param2", value = "value2") })
public class InitParamsServlet extends HttpServlet
{
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		ServletConfig servletConfig = this.getServletConfig();

		String param1Val = servletConfig.getInitParameter("param1");
		String param2Val = servletConfig.getInitParameter("param2");

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<p>");
		out.println("Value of param1 is " + param1Val);
		out.println("</p>");
		out.println("<p>");
		out.println("Value of param2 is " + param2Val);
		out.println("</p>");
	}

}

 result

http://localhost:8080/servlet/initparamsservlet


 

Demo08 - @WebFilter annotation

SimpleFilter.java

package org.fool.simpleservlet.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

@WebFilter(urlPatterns = { "/initparamsservlet" }, initParams = { @WebInitParam(name = "filterparam1", value = "filtervalue1") })
public class SimpleFilter implements Filter
{

	private FilterConfig filterConfig;

	public void destroy()
	{
		filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException
	{
		ServletContext servletContext = filterConfig.getServletContext();
		servletContext.log("Entering doFilter()");
		servletContext.log("initialization parameters: ");

		Enumeration<String> initParameterNames = filterConfig
				.getInitParameterNames();

		String parameterName;
		String parameterValue;

		while (initParameterNames.hasMoreElements())
		{
			parameterName = initParameterNames.nextElement();
			parameterValue = filterConfig.getInitParameter(parameterName);

			servletContext.log(parameterName + " = " + parameterValue);
		}

		servletContext.log("Invoking servlet...");

		chain.doFilter(request, response);

		servletContext.log("Back from servlet invocation");
	}

	public void init(FilterConfig fConfig) throws ServletException
	{
		this.filterConfig = fConfig;
	}

}

Our filter is fairly simple. It simply sends some output to the server log before and after the servlet is invoked. Inspecting the server log after deploying our application and pointing the browser to the servlet's URL should reveal our filter's output. 


 

Demo09 - @WebListener annotation

During the lifetime of a typical web application, a number of events take place, such as HTTP requests are created or destroyed, request or session attributes are added, removed, or modified, and so on and so forth.

The Servlet API provides a number of listener interfaces we can implement in order to react to these events. All of these interfaces are in the javax.servlet package. The following table summarizes them:


 HttpRequestListener.java 

package org.fool.simpleservlet.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class HttpRequestListener implements ServletRequestListener {

	public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
		ServletContext servletContext = servletRequestEvent.getServletContext();

		servletContext.log("Request destroyed");
	}

	public void requestInitialized(ServletRequestEvent servletRequestEvent) {
		ServletContext servletContext = servletRequestEvent.getServletContext();

		servletContext.log("New request initialized");
	}

}

Deploying our previous listener along with the simple servlet we developed earlier, we can see the following output :


 

Demo10 -  Configuring web applications programmatically

ProgrammaticallyConfiguredServlet.java

package org.fool.simpleservlet.programmaticservlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ProgrammaticallyConfiguredServlet extends HttpServlet
{

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		ServletOutputStream out = response.getOutputStream();

		out.println("This message was generated from a servlet that was configured programmatically.");
	}
}

 ServletContextListenerImpl.java

package org.fool.simpleservlet.programmaticservlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebListener;

@WebListener
public class ServletContextListenerImpl implements ServletContextListener
{
	public void contextInitialized(ServletContextEvent sce)
	{
		ServletContext servletContext = sce.getServletContext();

		try
		{
			ProgrammaticallyConfiguredServlet servlet = servletContext
					.createServlet(ProgrammaticallyConfiguredServlet.class);

			servletContext.addServlet("ProgrammaticallyConfiguredServlet",
					servlet);

			ServletRegistration servletRegistration = servletContext
					.getServletRegistration("ProgrammaticallyConfiguredServlet");

			servletRegistration
					.addMapping("/ProgrammaticallyConfiguredServlet");
		}
		catch (ServletException e)
		{
			e.printStackTrace();
		}
	}

	public void contextDestroyed(ServletContextEvent sce)
	{
	}

}

result

http://localhost:8080/servlet/ProgrammaticallyConfiguredServlet

 

Demo11 - Asynchronous processing

Traditionally, servlets have created a single thread per request in Java web applications. After a request is processed, the thread is made available for other requests to use. This model works fairly well for traditional web applications in which HTTP requests are relatively few and far in between. However, most modern web applications take advantage of Ajax (Asynchronous JavaScript and XML), a technique that makes web applications behave much more responsively than traditional web applications. Ajax has the side effect of generating a lot more HTTP requests than traditional web applications. If some of these threads block for a long time waiting for a resource to be ready or are doing anything that takes a long time to process, it is possible our application may suffer from thread starvation. 

To alleviate the situation described in the previous paragraph, the Servlet 3.0 specification introduced asynchronous processing. Using this new capability, we are no longer limited to a single thread per request. We can now spawn a separate thread and return the original thread back to the pool to be reused by other clients. 

AsynchronousServlet.java

package org.fool.simpleservlet.asynchronousservlet;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = { "/AsynchronousServlet" }, asyncSupported = true)
public class AsynchronousServlet extends HttpServlet
{
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		final Logger logger = Logger.getLogger(AsynchronousServlet.class
				.getName());
		logger.log(Level.INFO, "--- Entering doGet()");

		final AsyncContext ac = request.startAsync();

		logger.log(Level.INFO, "---- invoking ac.start()");

		ac.start(new Runnable()
		{

			@Override
			public void run()
			{
				logger.log(Level.INFO, "inside thread");

				try
				{
					// simulate a long running process.
					Thread.sleep(10000);
				}
				catch (InterruptedException e)
				{
					Logger.getLogger(AsynchronousServlet.class.getName()).log(
							Level.SEVERE, null, e);
				}

				try
				{
					ac.getResponse().getWriter()
							.println("You should see this after a brief wait");
					ac.complete();
				}
				catch (IOException e)
				{
					Logger.getLogger(AsynchronousServlet.class.getName()).log(
							Level.SEVERE, null, e);
				}

			}
		});

		logger.log(Level.INFO, "Leaving doGet()");
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		doGet(request, response);
	}

}

result

http://localhost:8080/servlet/AsynchronousServlet


 

 

 

 

 

 

  • 大小: 35.2 KB
  • 大小: 51.5 KB
  • 大小: 52.3 KB
  • 大小: 33.8 KB
  • 大小: 48.5 KB
  • 大小: 41.9 KB
  • 大小: 41.5 KB
  • 大小: 60.1 KB
  • 大小: 50 KB
  • 大小: 45.3 KB
  • 大小: 36.6 KB
  • 大小: 26 KB
  • 大小: 56.8 KB
  • 大小: 21.7 KB
  • 大小: 60.9 KB
  • 大小: 38.1 KB
  • 大小: 33.6 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics