servlet创建
1.创建一个Servlet,要继承一个import javax.servlet.http.HttpServlet类.
2.重写service方法,里面有两个参数(HttpServletRequest,HttpServletResponse).
3.在web.xml中设置请求返回的映射
例子
创建一个Servlet
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 TestServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 要调用父类的service方法,就必须重写doGet和doPost方法
// super.service(req, resp);
System.out.println("进入ServletTest");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.getWriter().print("<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'><title>servlet返回的页面</title></head><body><center><h1>这是一个返回的页面</h1></center></body></html>");
System.out.println("servlet返回结束");
}
}
在WEB-INF目录下创建一个web.xml文件,内容如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<!--上面是使用xml的标准格式-->
<!--servlet-name这个名字随便起
servlet-class里面写servlet的全类名,内部使用反射机制-->
<servlet>
<servlet-name>tt</servlet-name>
<servlet-class>test.ServletTest</servlet-class>
</servlet>
<!--servlet-name跟上面的servlet-name的名字一样
url-pattern是请求的地址,也就是浏览器中处理hosts地址,端口号,项目名称之后的地址,这就形成了servlet-class跟url-pattern的一个映射-->
<servlet-mapping>
<servlet-name>tt</servlet-name>
<url-pattern>/abc</url-pattern>
</servlet-mapping>
</web-app>
测试
<!--在url中输入地址 http://127.0.0.1/test/abc 输出结果-->
以上一个原始的servlet的就写出来了,但是在web.xml配置映射关系太麻烦,所以Java1.5之后使用了注解方法来代替web.xml配置.方法如下:
//下面就是使用了注解,跟web.xml的<url-pattern>/abc</url-pattern>映射地址时一样的,效果跟上面配置web.xml是一样的
@WebServlet("/abc")
public class TestServlet extends HttpServlet{}
现在再谈谈重写的service(…)方法中为什么不让调用父类的service(…)方法.
因为,父类,也就是HttpServlet类中,service方法会根据请求方式(get,post)来选择调用doGet(…) 还是doPost(…) 方法,所以service总结如下:
如果Servlet不重写service(…)方法,那么会调用HttpServlet(父类)的service(…)方法,父类的service方法判断请求是get方式还是post方式,如果是get请求,则调用doGet(…)方法,如果是post请求,则调用doPost(…)方法.如果不重写service方法,那么就必须重写doGet方法和doPost方法.当一个项目请求方式都为同一种方式的时候,就没有必要重写doGet和doPost方法了,直接重写service方法;当请求方式或为get,或为post方式,那就重写doGet(…)和doPost(…)