关键词

JavaWeb 入门:Hello Servlet

  1. 创建JavaWeb项目
  2. 打开Eclipse
  3. 点击菜单栏“File”->“New”->“Dynamic Web Project”
  4. 输入项目名称,然后点击“Next”按钮
  5. 选择“Generate web.xml deployment descriptor”,然后点击“Finish”按钮
  6. 添加Servlet
  7. 在“Package Explorer”视图中右键点击项目名称,选择“New”->“Servlet”
  8. 添加Servlet的类名和包名,然后点击“Next”按钮
  9. 选择要继承的父类,然后点击“Finish”按钮
  10. 配置Servlet
  11. 在Servlet类中重写doGet()和doPost()方法
  12. 在web.xml中添加Servlet类的映射

示例一:Hello World

@WebServlet(name = "HelloServlet", urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("<html>");
        writer.println("<head><title>Hello Servlet</title></head>");
        writer.println("<body>");
        writer.println("<h1>Hello World!</h1>");
        writer.println("</body>");
        writer.println("</html>");
        writer.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

在浏览器中输入"http://localhost:8080/<项目名>/hello",即可看到"Hello World!"字样的显示页面。

示例二:计算器

@WebServlet(name = "CalServlet", urlPatterns = "/cal")
public class CalServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("<html>");
        writer.println("<head><title>Calculator</title></head>");
        writer.println("<body>");
        int num1=Integer.parseInt(request.getParameter("num1"));
        int num2=Integer.parseInt(request.getParameter("num2"));
        int res=0;
        String op=request.getParameter("op");
        switch(op){
            case "+":res=num1+num2;break;
            case "-":res=num1-num2;break;
            case "*":res=num1*num2;break;
            case "/":res=num1/num2;break;
        }
        writer.println("<h1>"+num1+op+num2+"="+res+"</h1>");
        writer.println("</body>");
        writer.println("</html>");
        writer.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

在浏览器中输入"http://localhost:8080/<项目名>/cal?num1=2&num2=3&op=+",即可看到"2+3=5"字样的显示页面。

以上就是JavaWeb入门教程的完整攻略及示例说明。

本文链接:http://task.lmcjl.com/news/831.html

展开阅读全文