---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ----------------------详细请查看:http://edu.csdn.net
下面是第一个Servlet程序:
package 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 Servlet1 extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<html><head><title>This is my First page! </title></head><body>" +
"<h1 font-color = 'red'>HelloWorld!!!</h1></body></html>");
out.flush();
}
}
下面是Web . XML中的配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
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_3_0.xsd">
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>servlet.Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/helloworld</url-pattern>
</servlet-mapping>
</web-app>
其中,url-pattern 是资源的路径名,与servlet名称无关,servlet-mapping 中的servlet-name 是与上面的 servlet中的servlet-name是一一对应的,也就是说先访问这个路径,然后再去找这个路径所对应的servlet-mapping中的servlet-name的名称,然后再从上面的servlet中找到servlet-class 从中找到相应的java类去生成相应的对象,生成完对象之后自动去调用doGet方法。
下面是一个简单的打印用户名的servlet程序:
<body>
<form action = "denglu" >
<input type = "text" name = "username">
<input type = "password" name = "password">
<input type = "submit" value = "dengLu">
</form>
</body>
public class Servlet2 extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String username = req.getParameter("username");
String password = req.getParameter("password");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<html><body>username: "+username + "<br>password:" + password+"</body></html>");
out.flush();
}
}
下面是XML的配置文件:
<servlet>
<servlet-name>Denglu</servlet-name>
<servlet-class>servlet.Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Denglu</servlet-name>
<url-pattern>/denglu</url-pattern>
</servlet-mapping>
<form action = "denglu" >
注意在jsp中的表单中填入的action的值 应该为url-pattern的值。