使用servlet时,比较简单,只要在web.xml里配置你的servlet,然后在页面的请求表单里加入servlet名称,就可以将表单的请求提交到servlet里去处理:
1 在web.xml里加入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>HelloWorldServlet</servlet-name> <servlet-class>HelloWorldServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorldServlet</servlet-name> <url-pattern>/helloWorldServlet</url-pattern> </servlet-mapping>
2 新建一个servlet处理类HelloWorldServlet.java:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doPost(req, resp);
}
}
3 在doGet和doPost方法里处理表单的get和post请求。
这里最好将super.doGet(req, resp);和super.doPost(req, resp);去掉,不然在跳转时会发然
java.lang.IllegalStateException:Cannot forward after response has been committed异常(可以看这类的上一篇文章有介绍).
4 一个简单的使用该servlet的表单示例:
<form method="post" action="helloWorldServlet">
JQueryAutoComplete
<input type="text" id="word" name="word"/>
<input type="submit" value="submit" />
<br>
<div id="auto"></div>
</form>