servlet接受请求,进行处理后,返回结果给用户。
1。servlet
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet{ public void init(ServletConfig config) throws ServletException{ super.init(config); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub //super.doGet(req, resp); PrintWriter out=resp.getWriter(); resp.setContentType("text/html;charset=gb2312"); out.println("<html><body>"); out.println("hello!"); out.println("</body></html>"); } /* public void service(HttpServletRequest request,HttpServletResponse response) throws IOException{ PrintWriter out=response.getWriter(); response.setContentType("text/html;charset=gb2312"); out.println("<html><body>"); out.println("hello!"); out.println("</body></html>"); } */ }
常继承的有4种方法:doGet(),doPost(),init(),destroy()
service()方法调用doGet(),doPost();所以也可以只写service()方法而不写doPost(),doGet()方法。
2。web.xml的配置
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>com.servlet.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/servlet/hello</url-pattern>
</servlet-mapping>
(http://........./工程名/servlet/hello,只要在浏览器中写入该地址,并敲回车,就会提交一个默认的get请求,容器会将该请求交给MyServlet处理。)
get的请求,可以被搜索引擎引用,所以很多的门户网站会用这种方式。但是在参数太多超过限制的时候会有问题。