如何在jsp中使用bean类在数据库中插入值?

时间:2014-03-06 13:22:48

标签: java jsp jdbc javabeans

嗨我想在jsp表单中使用bean类在数据库中插入值,我能够做到这一点,但是每当我在表中插入值时,我都会得到一点点问题值也插入它们我尝试了不是我不能得到我错在哪里请解决我的问题

我的bean.java

package com.javabean;


import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;

public class bean 
{

    private String msgid;
    private String message;
    private Connection connection=null;
    private ResultSet rs = null;
    private Statement st = null;
    String connectionURL = "jdbc:mysql://localhost:3306/JspBean";


    public bean() 
    {
         try {
             // Load the database driver
            Class.forName("com.mysql.jdbc.Driver");
            // Get a Connection to the database
            connection = DriverManager.getConnection(connectionURL, "root", ""); 
            }catch(Exception e){
            System.out.println("Exception is ;"+e);
            }

    }  
    public void setmsgid(String msgid)
    {
        this.msgid = msgid;
    }

    public String getmsgid()
    {
        return (this.msgid);
    }

    public void setmessage(String message)
    {
        this.message = message;
    }

    public String getmessage()
    {
        return (this.message);
    }

    public void insert()
    {

       try
       {
            String sql = "insert into login(messageid,message) values('"+msgid+"','"+message+"')";
            Statement s = connection.createStatement();
            s.executeUpdate (sql);
            s.close ();
        }catch(Exception e){
            System.out.println("Exception is ;"+e);
        }
    }

}

这是我的jspbean.jsp文件

<%@ page language="Java" import="java.sql.*" %>

<html>
    <head><title>JSP with Javabeans</title></head>
<body bgcolor="#ffccff">
<h1>JSP using JavaBeans example</h1>
    <form name="form1" method="POST">

         ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
         <input type="text" name ="msgid"> <br>
         Message<input type="text" name ="message"> <br>
         <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
         <input type = "submit" value="Submit">
         <jsp:useBean id="sample" class="com.javabean.bean" scope="page">
            <jsp:setProperty name="sample" property="*"/>
        </jsp:useBean>
    </form>
    <% sample.insert();%>
</body>
</html>

我怎样才能实现这一点请解决我的问题 提前做好准备 Ť

1 个答案:

答案 0 :(得分:1)

你犯了一些错误:

public void setmsgid(String msgid)
    {
        this.msgid = msgid;
    }
    public String getmsgid()
    {
        return (this.msgid);
    }

你应该改为:

public String getmsgid()
    {
        return msgid;
    }
public void setmsgid(String msgid)
    {
        this.msgid = msgid;
    }

并添加此内容:

public String toString()
{
    return "User[msgid="+msgid+",message="+message+"];

}

你应该改变这个:

insert into login(username,password) values('"+msgid+"','"+message+"')";

insert into login(username,password) values(?,?)";

<强>更新

insert into login(messageid,message) values(?,?)";