一个简单的例子
1、建立一个dynamic web project
2、在src中创建一个servlet类(可以借助eclipse创建)
注意要点:
1、它会继承HttpServlet 类,
2、带有一个WebServlet的注解,让我们不用再去web.xml中配置servlet
3、HttpServlet 实现了java.io.Serializable接口,所以需要提供serialVersionUID,它的值默认生成。
@WebServlet("/ServletDemo")
public class ServletDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletDemo() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setHeader("Content-type", "text/html charset = utf-8");
PrintWriter out = response.getWriter();
Date today = new Date();
out.println("<html><body>"
+"now:"+today+
"</body></html>");
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
run on server ,启动tomcat
在网页上输入 http://localhost:8080/project名称/@WebServlet注解括号里的内容
例如 http://localhost:8080/FirstServlet/ServletDemo
网页上输出结果:
now:Sun May 28 20:18:59 CST 2017
注意:在eclipse中可能结果不一致。
网友评论