在建立一个继承了HttpServlet类并重写了该类的service()、doPost()和doGet()方法时,java会如何执行?其实若是该三个方法都在存在的情况下,java只会执行service()方法,而其他的两种方法不会被执行。若是没有service() 方法,则是根据jsp传入方式选择对应的方法。比如说,若是jsp是以Post方式传入数据,则是调用doPost()方法处理数据。但是一般上在建立一个继承HttpServlet类时都会重写doPost()和doGet()方法,而且会在其中一个方法中处理数据,另一个方法则是直接调用该方法,比如以下例子:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// 请求编码方式(设置服务器端编码方式)
request.setCharacterEncoding("utf-8");
// 响应编码方式(设置浏览器端发送编码方式)
response.setContentType("text/html; charset=utf-8");
String name = request.getParameter("name");
String psw = request.getParameter("psw");
if ("admin".equals(name) && "admin".equals(psw))
{
response.getWriter().append("欢迎" + name + "登录本页面");
}
else
{
PrintWriter out = response.getWriter();
out.print("<script>location.href=‘faild.jsp‘</script>");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request, response);
}以上仅是个人见解,如有失误,欢迎指出 !^^!
本文出自 “yinbin” 博客,请务必保留此出处http://yinbin99.blog.51cto.com/11392662/1834076
在servlet中出现service()、doGet()和doPost()方法时的执行问题
原文地址:http://yinbin99.blog.51cto.com/11392662/1834076