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
相关推荐
基于java的贝儿米幼儿教育管理系统答辩PPT.pptx
本压缩包资源说明,你现在往下拉可以看到压缩包内容目录 我是批量上传的基于SpringBoot+Vue的项目,所以描述都一样;有源码有数据库脚本,系统都是测试过可运行的,看文件名即可区分项目~ |Java|SpringBoot|Vue|前后端分离| 开发语言:Java 框架:SpringBoot,Vue JDK版本:JDK1.8 数据库:MySQL 5.7+(推荐5.7,8.0也可以) 数据库工具:Navicat 开发软件: idea/eclipse(推荐idea) Maven包:Maven3.3.9+ 系统环境:Windows/Mac
基于java的消防物资存储系统答辩PPT.pptx
项目经过测试均可完美运行! 环境说明: 开发语言:java jdk:jdk1.8 数据库:mysql 5.7+ 数据库工具:Navicat11+ 管理工具:maven 开发工具:idea/eclipse
项目经过测试均可完美运行! 环境说明: 开发语言:java jdk:jdk1.8 数据库:mysql 5.7+ 数据库工具:Navicat11+ 管理工具:maven 开发工具:idea/eclipse
TA_lib库(whl轮子),直接pip install安装即可,下载即用,非常方便,各个python版本对应的都有。 使用方法: 1、下载下来解压; 2、确保有python环境,命令行进入终端,cd到whl存放的目录,直接输入pip install TA_lib-xxxx.whl就可以安装,等待安装成功,即可使用! 优点:无需C++环境编译,下载即用,方便
使用软件自带的basic脚本编辑制作的脚本 低版本软件无法输出Excel报告,可以通过脚本方式实现这一功能
基于java的就业信息管理系统答辩PPT.pptx
25法理学背诵逻辑.apk.1g
基于java的大学生校园兼职系统答辩PPT.pptx
做到代码,和分析的源数据
本压缩包资源说明,你现在往下拉可以看到压缩包内容目录 我是批量上传的基于SpringBoot+Vue的项目,所以描述都一样;有源码有数据库脚本,系统都是测试过可运行的,看文件名即可区分项目~ |Java|SpringBoot|Vue|前后端分离| 开发语言:Java 框架:SpringBoot,Vue JDK版本:JDK1.8 数据库:MySQL 5.7+(推荐5.7,8.0也可以) 数据库工具:Navicat 开发软件: idea/eclipse(推荐idea) Maven包:Maven3.3.9+ 系统环境:Windows/Mac
项目经过测试均可完美运行! 环境说明: 开发语言:java jdk:jdk1.8 数据库:mysql 5.7+ 数据库工具:Navicat11+ 管理工具:maven 开发工具:idea/eclipse
适用于ensp已经入门人群的学习,有一定难度
基于java的数码论坛系统设计与实现答辩PPT.pptx
tornado-6.4.1-cp38-abi3-macosx_10_9_universal2.whl
基于java的医院信管系统答辩PPT.pptx
项目经过测试均可完美运行! 环境说明: 开发语言:java jdk:jdk1.8 数据库:mysql 5.7+ 数据库工具:Navicat11+ 管理工具:maven 开发工具:idea/eclipse
tornado-4.2.tar.gz
链表 合并两个链表,链表基础操作