一:对web.xml文件修改的说明
Web.xml文件的第一行是对xml文件的声明,接着就是xml的根元素,其属性中声明了版本信息,这是固定的头文件,大家可以粘贴。接着才是需要配置的文件。与之间配置的是和,其中的值是”helloWorld”是为Servlet起的一个名字,这个可以随便起名,只要符合Java的命名规则就行;而的值则是自己写的Servlet类的类名,这个必须配置正确,如果有包,还要在前面加上包名。
与之间配置的是与,其中的值就是上面刚刚配置的的值;的值也可以随便起名,但其前面必须加”/”
二: Servlet生命周期
当Servlet被装载到容器后,生命周期开始。首先调用init()方法进行初始化,初始化后,调用service()方法,根据请求的不同调用不同的doXxx()方法处理客户请求,并将处理结果封装到HttpServletResponse中返回给客户端。当Servlet实例从容器中移除时调用其destroy()方法,这就是Servlet运行的整个过程。
三: Servlet实际应用举例
个实例要达到这样的目的,首先在一个HTML文件中建立一个表单,里面有一个输入框,当客户输入内容后,提交到一个Servlet类,而这个Servlet类取出客户输入的信息,并在一个HTML页面上显示该内容。其效果如图所示。
程序实现:
1.InputServlet类编写
package servletexample;
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 InputServlet extends HttpServlet{
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setCharacterEncoding("gb2312");
//响应转换为中文编码
req.setCharacterEncoding("gb2312");
//请求也转换为中文编码
String input=req.getParameter("input");
//得到表单提交的内容
PrintWriter pw = resp.getWriter();
pw.println("<html><head><title>");
pw.println("显示的内容");
pw.println("</title><body>");
pw.println(input);
pw.println("</body>");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req,resp); #引用doGet
}
}
2.修改过后的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">
#web-app部分是固定的头文件,可以粘贴。
<servlet>
<servlet-name>InputServlet</servlet-name>
<servlet-class>servletexample.InputServlet</servlet-class> #servlet-class内容为自己新建的包名引入的类
</servlet>
<servlet-mapping>
<servlet-name>InputServlet</servlet-name> #与上面的servlet-name必须相同
<url-pattern>/inputServlet</url-pattern> #此处url-pattern必须与input.html中form action的值相同
</servlet-mapping>
<display-name></display-name>
<welcome-file-list>
<welcome-file>imput.html</welcome-file>
</welcome-file-list>
</web-app>
3.input.html
<!DOCTYPE html>
<html>
<head>
<title>Servlet实例</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<form action="inputServlet" method="post">
请输入你想显示的内容:<input type="text" name="input"/><br>
<input type="submit" value="提交"/>
<input type="reset" value="重置"/>
</form>
</body>
</html>