星期四, 十二月 17, 2015 20:53:26
一、servlet生命周期
1.生命全过程
加载 ClassLoader
实例化 new
初始化 init(ServletConfig)
处理请求 service doGet doPost
退出服务 destroy()
2.只有一个对象
3.API中的过程
init()//只执行一次,第一次初始化的时候
service()
destroy()//webapp退出的时候
二、代码案例
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 ServletLifeCycle extends HttpServlet { /** * Constructor of the object. */ public ServletLifeCycle() { System.out.println("construct"); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { System.out.println("init"); } /** * Destruction of the servlet. <br> */ public void destroy() { System.out.print("destroy"); } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doGet"); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>ServletLifeCycle</servlet-name>
<servlet-class>ServletLifeCycle</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/httpServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ServletLifeCycle</servlet-name>
<url-pattern>/ServletLifeCycle</url-pattern>
</servlet-mapping>
</web-app>
访问url
http://localhost:8080/TestServlet01/ServletLifeCycle
运行结果:
信息: Server startup in 866 ms
construct
init
doGet
doGet
2015-12-17 21:26:10 org.apache.coyote.http11.Http11Protocol pause
信息: Pausing Coyote HTTP/1.1 on http-8080
2015-12-17 21:26:11 org.apache.catalina.core.StandardService stop
信息: Stopping service Catalina
destroy2015-12-17 21:26:11 org.apache.catalina.core.ApplicationContext log
信息: SessionListener: contextDestroyed()
2015-12-17 21:26:11 org.apache.catalina.core.ApplicationContext log
信息: ContextListener: contextDestroyed()
从结果可以看出,先调用construct,然后init且只初始化一次
doGet..doGet可多次调用,最后在tomcat退出的时候,才执行destroy
二_servlet编程接口
1.GenericServlet是所有Servlet的鼻祖
2.用户HTTP的Servlet编程都通过继承。
javax.servlet.http.HttpServlet 实现
3.请求处理方法:
分别对应http协议的7种请求
3.1 doGet 响应Get请求,常用
3.2 doPost 响应Post请求,常用
3.3 doPut 用户http1.1协议
3.4 doDelete 用户http1.1协议
3.5 doHead 仅响应Get请求头部
3.6 doOptions 用户http1.1协议
3.7 doTrace 用于http1.1协议
4.实例个数
在非分布式的情况下,通常一个Servlet在服务器中一个实例
实现3个参数通过doGet()和doPost()传递
代码案例:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>MyHtml.html</title>
</head>
<body>
<form method="post" action = "servlet/ThreeParams">
<table>
<tr>
<tb width="93">param1</tb>
<tb width="94">
<input name="param1" type="text" id="param1"/>
</tb>
</tr>
<tr>
<tb width="93">param2</tb>
<tb width="94">
<input name="param2" type="text" id="param2"/>
</tb>
</tr>
<tr>
<tb width="93">param3</tb>
<tb width="94">
<input name="param3" type="text" id="param3"/>
</tb>
</tr>
<br/>
<tr>
<tb width="94">
<input type="submit"/>
</tb>
</tr>
</table>
</form>
</body>
</html>
/TestServlet01/src/ThreeParams.java
servlet类
ThreeParams.java
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 ThreeParams extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(request.getParameter("param1"));
out.println("<br/>");
out.println(request.getParameter("param2"));
out.println("<br/>");
out.println(request.getParameter("param3"));
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.print("doPost");
doGet(request,response);
}
}
运行结果:
http://localhost:8080/TestServlet01/MyHtml.html
提交后post
http://localhost:8080/TestServlet01/servlet/ThreeParams
console展示
doPost
星期四, 十二月 17, 2015 22:36:55
今天了解了servlet的生命周期
和 使用页面进行传参给servlet
星期日, 十二月 20, 2015 19:57:11
07_通过request读取所有参数
7.1代码案例:
http://localhost:8080/TestServlet01/MyHtml.html
MyHtml.html
<html>
<head>
<title>A sample show parameters</title>
</head>
<body>A sample show parameters
<form method="post" action="servlet/ShowParameters">
Item Number:<input type="text" name="itemNum"><br>
Quantity:<input type="text" name="quantity"><br>
Price each:<input type="text" name="price" value="$"><br>
First Name:<input type="text" name="firstName"><br>
Last Name:<input type="text" name="lastName"><br>
Middle Initial:<input type="text" name="initial"><br>
Shipping Address:<textarea name="address" row="3" cols="40"></textarea><br>
Credit Card:<br>
<!--单框示例-->
<input type="radio" name="cardType" value="Visa">Visa<br>
<input type="radio" name="cardType" value="Master Card">Master Card<br>
<input type="radio" name="cardType" value="Amex">Amex<br>
<input type="radio" name="cardType" value="Discover">Discover<br>
<input type="radio" name="cardType" value="Java SmartCard">Java SmartCard<br>
<!--密码输入框-->
Credit Card password:<input type="password" name="cardNum"><br>
Repeat Credit Card password:<input type="password" name="cardNum"><br><br>
<center><input type="submit" value="Submit Order"></center>
</form>
</body>
</html>
ShowParameters.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ShowParameters extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
String title = "Reading All Request Parameters";
out.println("init");
out.println("<html><head><title>读取所有参数</title></head>"
+ title
+ "\n" + "<table border=1 align=center>\n"
+ "<TH>Parameter Name<TH>Parameter Value(s)");
// Returns an Enumeration of String objects containing the names of the parameters contained in this request.
Enumeration paramNames = request.getParameterNames();
// Tests if this enumeration contains more elements.
while(paramNames.hasMoreElements()) {
// Returns the next element of this enumeration if this enumeration object has at least one more element to provide.
String paraName = (String)paramNames.nextElement();
out.println("<tr><td>" + paraName + "\n<td>");
// Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.
// 注意参数paraName(变量)不能加双引号,否则就是找参数名叫paraName的对应值了。
String[] paramValues = request.getParameterValues(paraName);
// 这个参数只有一个值
if(paramValues.length == 1) {
String paramValue = paramValues[0];
if(paramValue.length() == 0) {
out.println("<I>no value</I>");
} else {
out.println(paramValue);
}
}else {
// 这个参数有好几条值
out.println("<UL>");
for(int i = 0; i < paramValues.length; i++) {
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}
out.println("</table>\n<body></html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost");
doGet(request,response);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>HelloServlet</servlet-class> </servlet> <servlet> <servlet-name>ServletLifeCycle</servlet-name> <servlet-class>ServletLifeCycle</servlet-class> </servlet> <servlet> <servlet-name>ThreeParams</servlet-name> <servlet-class>ThreeParams</servlet-class> </servlet> <servlet> <servlet-name>ShowParameters</servlet-name> <servlet-class>ShowParameters</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/httpServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ServletLifeCycle</servlet-name> <url-pattern>/ServletLifeCycle</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ThreeParams</servlet-name> <url-pattern>/ThreeParams</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ShowParameters</servlet-name> <url-pattern>/servlet/ShowParameters</url-pattern> </servlet-mapping> </web-app>
十二月 20, 2015 19:59:17