08-11 数据库、方法封装 Serverlet、doGet方法

数据库、方法封装

//**数据库连接**
public class SQLManger {
    private Statement state;
    private Connection connection;
    public Connection getConnection() {
        return connection;
    }
    public void setConnection(Connection connection) {
        this.connection = connection;
    }
    public Statement getState() {
        return state;
    }
    public void setState(Statement state) {
        this.state = state;
    }
    public static SQLManger manger;
    //创建外部调用的方法
    public static synchronized SQLManger newInstance(){
        if(manger==null){
            manger=new SQLManger();
        }
        return manger;
    }
    //私有化SQLManger
    private SQLManger(){
                //连接数据库驱动
                String driver="com.mysql.jdbc.Driver";
                //URL指向要访问的数据库名
                String url="jdbc:mysql://localhost:3306/clazz";
                //MySQL配置时的用户名
                String user="root";
                //Java连接MySQL配置时的密码
                String  password="123456";

                try {
                    Class.forName(driver);//加载驱动
                    //与数据库建立连接
                    connection=DriverManager.getConnection(url, user, password);
                    if(!connection.isClosed()){  //如果数据库打开着
                        //创建一个 Statement 对象来将 SQL 语句发送到数据库
                        state=connection.createStatement();                     
                        //创建user表
                        String create="create table if not exists user(id int not null primary key auto_increment ,name varchar(30) not null,password varchar(30) not null)";
                        state.execute(create);
                        System.out.println("user表创建成功");
                        //插入数据
//                      String insert="insert into Student (name,sex,age)values('王武','男',20)";
//                      state.execute(insert);
//                      System.out.println("执行成功");
//                      //删除数据
//                      String delete="delete from Student where name='王武'";
//                      state.execute(delete);
//                      System.out.println("执行成功");
//                      //更新数据
//                      String update="update Student set age=25 where id=3";
//                      state.execute(update);
//                      System.out.println("执行成功");
//                      //查询数据
//                      String select="select * from Student";              
//                      ResultSet set=state.executeQuery(select);
//                      set.first();
//                      while(!set.isAfterLast()){
//                          String name=set.getString("name");
//                          String age=set.getString("age");
//                          System.out.print(name+" "+age);
//                          System.out.println();
//                          set.next();
//                      }
//                      System.out.println("执行成功");
                    }else{
                        System.out.println("请打开数据库");
                    }                       

                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    }
}

//**方法封装,登录、注册方法**
public class SQLOperate {
    private Connection connection;
    public static SQLOperate operate;
    public Connection getConnection() {
        return connection;
    }


    public void setConnection(Connection connection) {
        this.connection = connection;
    }
    public static synchronized SQLOperate newInstance(){
        if(operate==null){
            operate=new SQLOperate();
        }
        return operate;
    }

    //登录操作
    public boolean Login(String name,String password){
        connection=SQLManger.newInstance().getConnection();
        try {
            if(!connection.isClosed()){
                PreparedStatement state=connection.prepareStatement("select * from user where name=? and password=?");
                state.setString(1, name);
                state.setString(2, password);
                ResultSet set=state.executeQuery();
                set.last();
                int num=set.getRow();
                System.out.println("查询结果"+num);
                return num==1;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }


    //注册操作
    public boolean Register(String name,String password){
        Statement state=SQLManger.newInstance().getState();
        String sql="select * from user where name='"+name+"'";

        try {
            ResultSet set = state.executeQuery(sql);
            set.last();//设置游标,放到最后一行
            int num=set.getRow();//得到最后一行在第几行
            System.out.println(num);
            if(num>0){
                System.out.println("该用户已存在");
            }else{
                String register="insert into user(name,password)values('"
            +name+"','"
            +password
            +"')";
            state.execute(register);            
            }
            return true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

}


//**登陆界面**
public class Login extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    private JTextField textField_1;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Login frame = new Login();
                    frame.setTitle("登录");
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Login() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textField = new JTextField();
        textField.setBounds(151, 43, 147, 30);
        contentPane.add(textField);
        textField.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setBounds(151, 100, 147, 30);
        contentPane.add(textField_1);
        textField_1.setColumns(10);

        JButton btnLogin = new JButton("login");
        btnLogin.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String name=textField.getText();  //得到用户名
                String password=textField_1.getText();  //得到密码
                boolean isLogin=SQLOperate.newInstance().Login(name, password);
                if(isLogin){
                    System.out.println("登录成功");
                }else{
                    System.out.println("登录失败");
                }                       
            }
        });
        btnLogin.setBounds(178, 162, 93, 23);
        contentPane.add(btnLogin);

        JLabel lblUsername = new JLabel("username");
        lblUsername.setBounds(56, 50, 85, 15);
        contentPane.add(lblUsername);

        JLabel lblPassword = new JLabel("password");
        lblPassword.setBounds(56, 107, 85, 15);
        contentPane.add(lblPassword);
    }
}

//**注册界面**
public class Register extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    private JTextField textField_1;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Register frame = new Register();
                    frame.setTitle("注册");
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Register() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textField = new JTextField();
        textField.setBounds(131, 30, 148, 34);
        contentPane.add(textField);
        textField.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setBounds(131, 93, 148, 34);
        contentPane.add(textField_1);
        textField_1.setColumns(10);

        JButton btnNewButton = new JButton("register");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {             
                String name=textField.getText();  //得到用户名           
                String password=textField_1.getText();  //得到密码
                //创建一个 Statement 对象来将 SQL 语句发送到数据库
                boolean isRegister=SQLOperate.newInstance().Register(name, password);
                if(isRegister){
                    System.out.println("注册成功");
                }else{
                    System.out.println("注册失败");
                }


            }
        });
        btnNewButton.setBounds(155, 169, 93, 23);
        contentPane.add(btnNewButton);

        JLabel lblUsername = new JLabel("username");
        lblUsername.setBounds(39, 39, 82, 15);
        contentPane.add(lblUsername);

        JLabel lblPasword = new JLabel("pasword");
        lblPasword.setBounds(39, 102, 82, 15);
        contentPane.add(lblPasword);
    }
}

//**事务**   几条语句中只要有一条false,全部回滚
public class Action extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Action frame = new Action();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Action() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton btnNewButton = new JButton("New button");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String sql1="insert into user (name,password) values ('qwe','123')";
                String sql2="insert into user (name,passwords) values ('we','123')";
                String sql3="insert into user (name,password) values ('qw','123')";
                Connection conn=SQLManger.newInstance().getConnection();
                try {
                    Statement state=conn.createStatement();
                    conn.setAutoCommit(false);
                    //addBatch 将给定的 SQL 命令添加到此 Statement 对象的当前命令列表中。
                    state.addBatch(sql1);
                    state.addBatch(sql2);
                    state.addBatch(sql3);
                    //executeBatch 将一批命令提交给数据库来执行
                    state.executeBatch();
                    conn.commit();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });
        btnNewButton.setBounds(130, 112, 93, 23);
        contentPane.add(btnNewButton);
    }
}

Serverlet

//**前段与后台数据格式转换,避免乱码**

public class Encoding {
    public static String doEncoding(String string){
        try {
            byte[] array=string.getBytes("ISO-8859-1");
            string=new String(array, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return string;
    }
}

//**Serverlet**  前台数据传往后台,doGet方法

/**
 * Servlet implementation class MyServerlet
 */
@WebServlet("/MyServerlet")
public class MyServerlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyServerlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //显示在控制台
        String userName=request.getParameter("name");
        String passWord=request.getParameter("password");
        userName=Encoding.doEncoding(userName);
        passWord=Encoding.doEncoding(passWord);     
        System.out.println("用户名:"+userName+"  密码:"+passWord);

        //显示在界面
        String s="用户名:"+userName+"  密码:"+passWord;
        response.setHeader("Content-type","text/html;charset=UTF-8");
        response.getWriter().append(s);
//      response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值