通过Servlet实现计算器

来源:互联网 发布:女装尺码表参照数据 编辑:程序博客网 时间:2024/05/16 09:43
package com.milk.servlet;


import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ConterServlet extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        ServletContext context = req.getSession().getServletContext();
        
        if(null == context.getAttribute("counter"))
        {
            context.setAttribute("counter", 1);
        }
        else
        {
            int num = (Integer)(context.getAttribute("counter"));
            context.setAttribute("counter", num+1);
        }
        
        req.getRequestDispatcher("counter.jsp").forward(req, resp);
    }

}





jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'counter.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">


  </head>
 
  <body>
    计数器: <%= application.getAttribute("counter") %>>
  </body>
</html>


原创粉丝点击