广州疯狂软件教育Java培训,iOS培训分享
Servlet三种实现方式:实现Servlet接口,继承GenericServlet ,继承HttpServlet。
1、实现Servlet接口:
import javax.servlet.*;
import java.io.*;
public class Hello implements Servlet{
//执行条件:reload,关闭tomcat,关机
public void destroy() {
// TODO Auto-generated method stub
System.out.println("destroy it");
}
@Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}
//初始化,用户第一次访问时调用
public void init(ServletConfig arg0) throws ServletException {
// TODO Auto-generated method stub
System.out.println("init it");
}
//业务处理
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("service it");
res.getWriter().println("hell,world");
}
}
2、继承GenericServlet :
import javax.servlet.*;
import java.io.*;
public class HelloGen extends GenericServlet{
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// TODO Auto-generated method stub
res.getWriter().println("Hello,gen");
}
}
3、继承HttpServlet:
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class HellHttp extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try {
res.setContentType("text/html;charset=gbk");
res.getWriter().println("hello,HttpServlet");;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doPost(HttpServletRequest req,HttpServletResponse res)
{
this.doGet(req, res);
}
}
使用Servlet需要对其在web.xml中进行配置,对于上面的三种方式要在web.xml中添加如下信息:
<!-- JSPC servlet mappings start-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>Hello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<!-- JSPC hellogen-->
<servlet>
<servlet-name>hellogen</servlet-name>
<servlet-class>HelloGen</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hellogen</servlet-name>
<url-pattern>/hellogen</url-pattern>
</servlet-mapping>
<!-- JSPC hellohttp-->
<servlet>
<servlet-name>hellohttp</servlet-name>
<servlet-class>HellHttp</servlet-class>
</servlet>
<servlet-mapping>
<!-- JSPC servlet mappings end-->
启动tomcat,输入正确地址,即可在浏览器中访问了。
疯狂Java培训专注软件开发培训,提升学员就业能力,重点提升实践动手能力。高薪从IT名企请来项目经理为学员亲自授课,对学员进行实战教学,在没有工作经验的学员,在疯狂java,通过大量全真经典企业级项目进行集中培训,学员通过数月培训都可获得1-2年的工作经验,进而在同类的求职者中脱颖而出。疯狂Java培训让你体会java编程的快乐,项目开发的兴奋,成就感,通过短短几个月的时间,让你在半年的时间内掌握8-10万的代码量,掌握Java核心技术,迅速成为技能型的现代化高端人才,迅速获得高薪就业!