美文网首页Servlet实例专题
避免客户端访问的并发问题

避免客户端访问的并发问题

作者: 神坛下的我 | 来源:发表于2018-08-21 18:46 被阅读0次

    UseServlet.java

    @WebServlet("/user.do")
    public class UseServlet extends HttpServlet{
    
        private int sum=100;
        private static final long serialVersionUID = 1L;
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            //设置字符集格式为utf-8
            req.setCharacterEncoding("UTF-8");
            String num2=req.getParameter("num2");
            int n2=Integer.parseInt(num2);
            resp.setContentType("text/html");
            resp.setCharacterEncoding("utf-8");
            PrintWriter out = resp.getWriter();
            out.println("<!DOCTYPE>");
            out.println("<html>");
            out.println("<head><title>A servlet</title></head>");
            out.println("<body>");
            synchronized (this) {
                out.println(sum+"+"+n2+"=");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sum+=n2;
                out.println(sum);
            }
            out.println("</body>");
            out.println("</html>");
            out.flush();
            out.close();
            
        }
        
    

    index.jsp

    <form action="user.do" method="post">
            <table>
                <tr>
                    <td>100+</td>
                    <td><input type="text" name="num2"/>=</td>
                    <td><input type="submit" value="计算"/></td>
                </tr>
            </table>
        </form>
    
    36.PNG 37.PNG

    相关文章

      网友评论

        本文标题:避免客户端访问的并发问题

        本文链接:https://www.haomeiwen.com/subject/vxajiftx.html