示例一: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