微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ajax+mysql

public void doGet(HttpServletRequest request,HttpServletResponse response)
            throws servletexception,IOException {

        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        
        PrintWriter out = response.getWriter();
        request.setCharacterEncoding("utf-8");
        String id=request.getParameter("username");
        String password=request.getParameter("password");
        
        out.println("id = " +id);
        
        //Servlet操作数据库和普通java类一样
        
        Connection ct= null;
        PreparedStatement ps =null;
        ResultSet rs = null;
        try {
            //1.加载驱动
            Class.forName("com.MysqL.jdbc.Driver");
            //2.得到连接
            ct = DriverManager.getConnection("jdbc:MysqL://localhost:3306/work","root","1");
            //3.创建PreparedStatment 用于传送SQL查询语句
            ps=(PreparedStatement) ct.prepareStatement("select * from users where id =? and password=?");
            //给?赋值
            ps.setobject(1,id);
            ps.setobject(2,password);
            
            //4.执行操作
            rs= ps.executeQuery();
            //5.根据结果做处理
            if(rs.next())
            {//合法
                request.getRequestdispatcher("/MainFrame").forward(request,response);
            }else
            {
                request.setAttribute("error","用户名 或者 密码错误!");
                request.getRequestdispatcher("/LoginServlet").forward(request,response);
            }
            
            
        } catch (Exception e) {
            e.printstacktrace();
            // Todo: handle exception
        }finally
        {
            //关闭资源
            if(rs!=null)
            {
                try {
                    rs.close();
                } catch (sqlException e) {
                    // Todo Auto-generated catch block
                    e.printstacktrace();
                }
                rs=null;
            }
            if(ps!=null)
            {
                try {
                    ps.close();
                } catch (sqlException e) {
                    // Todo Auto-generated catch block
                    e.printstacktrace();
                }
                ps=null;
            }
            if(ct!=null)
            {
                try {
                    ct.close();
                } catch (sqlException e) {
                    // Todo Auto-generated catch block
                    e.printstacktrace();
                }
                ct=null;
            }
        }
        
        
        //out.println("username"+username);
        
        

    }

    public void doPost(HttpServletRequest request,IOException {

        this.doGet(request,response);

    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐