X

由于无法提供服务器的高昂费用,博客即将迁移到github pages...

点击右上的X可以临时关闭此框并阻止跳转^_^

现在带您过去 秒后跳转...

[作业练习]带数据库的简易购物车

    在前一次作业的基础上([作业]JavaBean+Jsp简易购物车实现),加上数据库来管理商品和购买记录。
    最后结果展示:http://demo.dshui.wang/tomcat/ShopCartDemo/
    首先,建立数据表:

    #用户表
    CREATE TABLE `cart_users` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `username` varchar(80) NOT NULL DEFAULT '',
      `password` varchar(220) NOT NULL DEFAULT '',
      PRIMARY KEY (`id`),
      UNIQUE KEY `username` (`username`)
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
     (...继续阅读这篇文章...)

[作业]JavaBean+Jsp简易购物车实现

    本次作业要求使用到JavaBean+纯Jsp,带有登陆功能的购物车系统。
    登陆功能这里就不多讲了,前面的聊天室已经做过,这边直接拷贝就能使用了。
    另外,本次作业中我加入了BootStrap来做一个小小风格美化。
    不多说,直接上代码!
    index.jsp 首页,也是登陆界面

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%
        Cookie[] cookies = request.getCookies();
        String uname = "";
        String upwd = "";
        if(cookies!=null){
            for(int i=0;i
    
    
        
            
            
            
            请登录ShopCartDemo
            
        
        
            

    dologin.jsp 登陆信息处理页面

    <%-- 
        Document   : dologin
        Created on : 2015-10-9, 11:28:29
        Author     : Anthony
    --%>
    
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%@page import="java.util.*"%>
    
    
        
            
            正在登录...
        
        
            <%
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String remember = (String) request.getParameter("remember");
            if(username == null)
                username="";
            if(password == null)
                password="";
            if(remember == null)
                remember = "false";
            if(username.equals("201321092028")&&password.equals("123456") || username.equals("201321092027")&&password.equals("123456"))
            {
                if(remember != null && remember.equals("true"))
                {
                    Cookie cookie1 = new Cookie("remname",username);
                    Cookie cookie2 = new Cookie("rempwd",password);
                    cookie1.setMaxAge(60*60*24*5);
                    cookie2.setMaxAge(60*60*24*5);
                    response.addCookie(cookie1);
                    response.addCookie(cookie2);
                }
                session.setAttribute("UserName",username);
                session.setAttribute("IsLogin","true");
                response.sendRedirect("goods.jsp");
            }else{
                response.sendRedirect("index.jsp");
            }
            %>
        
    
    

    goods.jsp 商品列表页面

    <%-- 
        Document   : goods
        Created on : 2015-10-15, 17:11:28
        Author     : anthony
    --%>
    
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    
    
        
            
            
            
            商品列表
            
        
        
            
    编号商品名单价(元/斤)购买数量
    1苹果13
    2橘子8
    3西瓜2
    4火龙果15

    order.jsp 订单信息页面

    <%-- 
        Document   : order
        Created on : 2015-10-15, 18:28:05
        Author     : anthony
    --%>
    
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    
    
        
            
            
            
            订单信息
            
        
        
            
                
                
                
                
            
    编号商品名单价(元/斤)数量价格
    1苹果13
    2橘子8
    3西瓜2
    4火龙果15

    另外,还需要一个JavaBean CountPrice.java

    package Cart;
    
    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    
    /**
     *
     * @author anthony
     */
    public class CountPrice {
        private double n_apple;
        private double n_orange;
        private double n_watermalon;
        private double n_fires;
        private double p_apple;
        private double p_orange;
        private double p_watermalon;
        private double p_fires;
        private double totalprice;
    
        /**
         * @return the n_apple
         */
        public double getN_apple() {
            return n_apple;
        }
    
        /**
         * @param n_apple the n_apple to set
         */
        public void setN_apple(double n_apple) {
            this.n_apple = n_apple;
            this.setP_apple(n_apple*13);
        }
    
        /**
         * @return the n_orange
         */
        public double getN_orange() {
            return n_orange;
        }
    
        /**
         * @param n_orange the n_orange to set
         */
        public void setN_orange(double n_orange) {
            this.n_orange = n_orange;
            this.setP_orange(n_orange*8);
        }
    
        /**
         * @return the n_watermalon
         */
        public double getN_watermalon() {
            return n_watermalon;
        }
    
        /**
         * @param n_watermalon the n_watermalon to set
         */
        public void setN_watermalon(double n_watermalon) {
            this.n_watermalon = n_watermalon;
            this.setP_watermalon(n_watermalon*2);
        }
    
        /**
         * @return the n_fires
         */
        public double getN_fires() {
            return n_fires;
        }
    
        /**
         * @param n_fires the n_fires to set
         */
        public void setN_fires(double n_fires) {
            this.n_fires = n_fires;
            this.setP_fires(n_fires*15);
        }
    
        /**
         * @return the totalprice
         */
        public double getTotalprice() {
            this.totalprice = this.getP_apple()+this.getP_fires()+this.getP_orange()+this.getP_watermalon();
            return totalprice;
        }
    
        /**
         * @return the p_apple
         */
        public double getP_apple() {
            return p_apple;
        }
    
        /**
         * @return the p_orange
         */
        public double getP_orange() {
            return p_orange;
        }
    
        /**
         * @return the p_watermalon
         */
        public double getP_watermalon() {
            return p_watermalon;
        }
    
        /**
         * @return the p_fires
         */
        public double getP_fires() {
            return p_fires;
        }
    
        /**
         * @param p_apple the p_apple to set
         */
        public void setP_apple(double p_apple) {
            this.p_apple = p_apple;
        }
    
        /**
         * @param p_orange the p_orange to set
         */
        public void setP_orange(double p_orange) {
            this.p_orange = p_orange;
        }
    
        /**
         * @param p_watermalon the p_watermalon to set
         */
        public void setP_watermalon(double p_watermalon) {
            this.p_watermalon = p_watermalon;
        }
    
        /**
         * @param p_fires the p_fires to set
         */
        public void setP_fires(double p_fires) {
            this.p_fires = p_fires;
        }
        
    }

    附上NetBean项目工程:
    链接: http://pan.baidu.com/s/1o66DrjO 密码: yksy

[作业]Servlet简易聊天室

    简单例子-Servlet聊天室,所用工具:NetBeans IDE(配备GlassFish)
    本次例子重在思路,页面未做任何美化。
    最后结果展示:http://demo.dshui.wang/tomcat/First_chat_room/
    首先,需要一个登陆页面。
    Login.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%
        Cookie[] cookies = request.getCookies();
        String uname = "";
        String upwd = "";
        if(cookies!=null){
            for(int i=0;i
    
    
        
            牛逼的登陆界面
            
        
        
            
    用户名:
    密码:
    记住信息

    新建一个用来处理登录信息的Servlet: Main.java 所有的处理都在DoPost()完成

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package User;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    /**
     *
     * @author Administrator
     */
    public class Main extends HttpServlet {
    
        /**
         * Processes requests for both HTTP
         * GET and
         * POST methods.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            try {
                /* TODO output your page here. You may use following sample code. */
            } finally {            
                out.close();
            }
        }
    
        // 
        /**
         * Handles the HTTP
         * GET method.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
        }
    
        /**
         * Handles the HTTP
         * POST method.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            //processRequest(request, response);
            String username,password,remember;
            HttpSession session = request.getSession(true);
            username = (String) request.getParameter("username");
            password = (String) request.getParameter("password");
            remember = (String) request.getParameter("remember");
            System.out.println("remember:"+remember);
            System.out.println(username);
            System.out.println(password);
            if(username != null && username.equals("201321092028") && password.equals("123456"))
            {
                if(remember != null && remember.equals("true"))
                {
                    Cookie cookie1 = new Cookie("remname",username);
                    Cookie cookie2 = new Cookie("rempwd",password);
                    cookie1.setMaxAge(60*60*24*5);
                    cookie2.setMaxAge(60*60*24*5);
                    response.addCookie(cookie1);
                    response.addCookie(cookie2);
                }
                session.setAttribute("UserName",username);
                session.setAttribute("IsLogin","true");
                response.sendRedirect("LoginSuccess.jsp");
            }else if(username != null && username.equals("201321092027") && password.equals("123456"))
            {
                if(remember.equals("true"))
                {
                    Cookie cookie1 = new Cookie("remname",username);
                    Cookie cookie2 = new Cookie("rempwd",password);
                    cookie1.setMaxAge(60*60*24*5);
                    cookie2.setMaxAge(60*60*24*5);
                    response.addCookie(cookie1);
                    response.addCookie(cookie2);
                }
                session.setAttribute("UserName",username);
                session.setAttribute("IsLogin","true");
                response.sendRedirect("LoginSuccess.jsp");
            }
            else
            {
                session.setAttribute("IsLogin","false");
                response.sendRedirect("LoginFail.jsp");
            }
        }
    
        /**
         * Returns a short description of the servlet.
         *
         * @return a String containing servlet description
         */
        @Override
        public String getServletInfo() {
            return "Short description";
        }// 
    }
    
    

    如果登录失败,跳转到LoginFail.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    
    
        
            
            
            请告诉他,登录失败了
        
        
            嗨,登陆失败了哟,3秒后跳转到登录页重新登陆哟! 点击此处直接跳转
        
    
    

    登录成功,则跳转到FrameSet窗口框架 LoginSuccess.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%
      session = request.getSession(true);
      String username = "";
      if(session.getAttribute("UserName") != null)
      {
          username = session.getAttribute("UserName").toString();
      }
      if(username != null && !username.equals(""))
      {
          if(!session.getAttribute("IsLogin").equals("true"))
          {System.out.println(session.getAttribute("IsLogin").toString());
              response.sendRedirect("Login.jsp");
          }
      }else{
          response.sendRedirect("Login.jsp");
      }
     %>
    
    
        
            
            
        
    
    

    上面的Frame加载了两个页面,一个是用来展示Messagebox聊天记录的,一个是用户的输入框
    Messagebox.Java

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package User;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    /**
     *
     * @author Administrator
     */
    public class messagebox extends HttpServlet {
    
        /**
         * Processes requests for both HTTP GET and POST
         * methods.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            request.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            try {
                /* TODO output your page here. You may use following sample code. */
                HttpSession session = request.getSession(true);
                String username = "";
                if(session.getAttribute("UserName") != null)
                {
                    username = session.getAttribute("UserName").toString();
                }
                if(username != null && !username.equals(""))
                {
                    if(!session.getAttribute("IsLogin").equals("true"))
                    {System.out.println(session.getAttribute("IsLogin").toString());
                        response.sendRedirect("Login.jsp");
                        //request.getRequestDispatcher("/Login.html").forward(request, response);
                    }
                }else{
                    response.sendRedirect("Login.jsp");
                }
                String words = (String) getServletConfig().getServletContext().getAttribute("Words");
                String messages = "";
                if(request.getParameter("usermessages") != null)
                {
                    messages = request.getParameter("usermessages");
                }
                if (words == null) {
                    words = "系统提示:可以聊天\n";
                } else if(!messages.equals("")){
                    words = (String) getServletConfig().getServletContext().getAttribute("Words") + username + " 说:"+messages + "\n";
                }
                getServletConfig().getServletContext().setAttribute("Words", words);
                String temp = (String) getServletConfig().getServletContext().getAttribute("online");
                if(temp==null)temp="0";
                out.println("");
                out.println("");
                out.println("Servlet messagebox");
                out.println("");
                out.println("");
                out.println("");
                out.println("

    当前在线:"); out.println(temp); out.println("人

    "); out.println(""); out.println(""); out.println(""); } finally { out.close(); } } // /** * Handles the HTTP GET method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP POST method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// }

    用户填写框:userinput.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <% session = request.getSession(true);%>
    
    
        
            
            输入框
        
        
            
    退出登陆

    我们还需要一个退出登录的功能:Loginout.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <% 
        session = request.getSession(true);
        session.removeAttribute("UserName");
        session.removeAttribute("IsLogin");
    %>
    
    
        
            
            
            Logout
        
        
            

    成功退出!

    注意了,既然是聊天室的话,也要知道当前有多少人在线吧,这个用监听来实现:SessionListrner.java

    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package Listener;
    
    import javax.servlet.annotation.WebListener;
    import javax.servlet.http.HttpSessionAttributeListener;
    import javax.servlet.http.HttpSessionBindingEvent;
    import javax.servlet.http.HttpSessionEvent;
    import javax.servlet.http.HttpSessionListener;
    
    /**
     * Web application lifecycle listener.
     *
     * @author Anthony
     */
    @WebListener()
    public class SessionListenr implements HttpSessionListener, HttpSessionAttributeListener {
    
        @Override
        public void sessionCreated(HttpSessionEvent se) {
            
        }
    
        @Override
        public void sessionDestroyed(HttpSessionEvent se) {
            
        }
    
        @Override
        public void attributeAdded(HttpSessionBindingEvent event) {
            if(event.getName().equals("UserName"))
            {
                String current = (String) event.getSession().getServletContext().getAttribute("online");
                String info = (String) event.getSession().getServletContext().getAttribute("Words");
                if(info==null)info ="";
                if(current == null) current="0";
                int c=Integer.parseInt(current);
                c++;
                current = String.valueOf(c);
                event.getSession().getServletContext().setAttribute("online", current);
                event.getSession().getServletContext().setAttribute("Words", info+event.getValue()+" 加入聊天室\n");
            }
        }
    
        @Override
        public void attributeRemoved(HttpSessionBindingEvent event) {
            if(event.getName().equals("UserName"))
            {
                String current = (String) event.getSession().getServletContext().getAttribute("online");
                String info = (String) event.getSession().getServletContext().getAttribute("Words");
                if(info==null)info ="";
                if(current==null)current = "0";
                int c = Integer.parseInt(current);
                c--;
                current = String.valueOf(c);
                event.getSession().getServletContext().setAttribute("online", current);
                event.getSession().getServletContext().setAttribute("Words", info+event.getValue()+" 离开了聊天室\n");
            }
        }
    
        @Override
        public void attributeReplaced(HttpSessionBindingEvent event) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    }
    

    附上NetBean项目工程:
    链接: http://pan.baidu.com/s/1qWL2xRm 密码: 22wa