-1

I need your little help, I have reedited my code and posted here again, I want to edit data based on clicking the EDIT button . Can any one please help me little that how to link that EDIT feature ?

index.jsp

<html>
    <head>
        <title>Data insertion form</title>
    </head>

    <body>

    <%
    String action="/SimpleServlet/DataInsertTable";
    String method="get";

    if(request.getAttribute("EDIT")!=null)  {
        action="/SimpleServlet/DataUpdateTable";
        method="post";
    }
    %>

    <form method= "<%=method%>" action="<%=action%>">
        <h1><center>Enter the required information</center></h1>

        <table>
            <tr>
                <td>Name</td>
                <td> :- </td>
                <%if(request.getAttribute("NAME")!=null){ %>
                <td><input type="text" name="name" value="<%=request.getAttribute("NAME")%>"></input>

                <%}else{ %>
                <td><input type="text" name="name"></input>
                <%} %>
                </td>
        </tr>

        <tr>
            <td>Roll Number</td>
            <td> :- </td>
            <%if(request.getAttribute("ROLL")!=null){ %>
            <td><input type="text" name="roll" value="<%=request.getAttribute("ROLL")%>"></input>

            <%}else{ %>
            <td><input type="text" name="roll"></input>
            <%} %>
            </td>       
        </tr>

        <tr>
            <td>Class </td>
            <td> :- </td>
             <%if(request.getAttribute("CLAS")!=null){ %>
            <td><input type="text" name="clas" value="<%=request.getAttribute("CLAS")%>"></input>

            <%}else{ %>
            <td><input type="text" name="clas"></input>
            <%} %>
            </td>
        </tr>

        <tr>
            <td>Mobile Number </td>
            <td> :- </td>
            <%if(request.getAttribute("MONO")!=null){ %>
            <td><input type="text" name="mono" value="<%=request.getAttribute("MONO")%>"></input>

            <%}else{ %>
            <td><input type="text" name="mono"></input>
            <%} %>
            </td>
        </tr>

        <tr>
            <td></td>
            <td><input type="submit" value="Submit" width="100%"></input></td>
        </tr>

    </table>

    </form>

    </body>
</html>

DataInsertTable.java

import java.io.*; 
import java.sql.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 

public class DataInsertTable extends HttpServlet    {
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws IOException, ServletException    {

        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        PrintWriter pwinsert = res.getWriter();

        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Statement st = null;


        out.println("<html>");
            out.println("<head>");
                out.println("<title>User Data</title>"); 
            out.println("</head>"); 

            out.println("<body>"); 
            out.println("<center><u><h1>User Data</h1></u>"); 

            out.println("<form name='form' >"); 


            out.println("<table border="+2+ "> ");

            out.println("<tr>");
                out.println("<td> Select </td>");
                out.println("<td> Name </td>");
                out.println("<td> Roll No. </td>");
                out.println("<td> Class </td>");
                out.println("<td> Mobile Number </td>");
                out.println("<td> Edit </td>");
            out.println("</tr>");


            String nm = req.getParameter("name");
            String roll = req.getParameter("roll");
            String clas = req.getParameter("clas");
            String mono = req.getParameter("mono");


            try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
            }
            catch(ClassNotFoundException ex)    {
                System.out.println("driver not loaded");
                System.exit(0); 
            } 

            String URL = "jdbc:oracle:thin:@192.168.106.87:1521:ORA11G";
            String Username = "pratik";
            String Password = "pratik";

            try {
                con = DriverManager.getConnection(URL,Username,Password); 

//              if(req.getParameter("nm")==null && req.getParameter("roll")==null && req.getParameter("clas")==null && req.getParameter("mono")==null) {


// Insert
                if(req.getParameter("choise")==null)    {
                    ps = con.prepareStatement("INSERT INTO student (name, rollno, class, mobileno) VALUES (?, ?, ?, ? )"); 
                    ps.setString(1,nm);
                    ps.setString(2,roll); 
                    ps.setString(3,clas); 
                    ps.setString(4,mono); 

                    int i = ps.executeUpdate(); 
                    pwinsert.println(i); 

                    if(i!=0)    { 
                        pwinsert.println("Your data has been stored in the database"); 
                    } 
                    else    { 
                        pwinsert.println("Your data could not be stored in the database"); 
                    } 
                }
            } 
            catch(Exception e)  {
                pwinsert.println(e.getMessage());

            } 



// Delete           

            String idr=null;

            if(req.getParameter("choise")!=null)    {
                nm = req.getParameter("choise");
                idr = "DELETE from student WHERE name ='"+nm+"'";

                try {
                    st=con.createStatement(); 
                    rs = st.executeQuery(idr); 
                } 
                catch (Exception e) { 
                    e.getMessage(); 
                    System.out.println("Error " +e); 
                } 

                System.out.println("Data deleted..."); 
            }


//          res.sendRedirect("DataInsertTable.java"); 


            idr = "SELECT * FROM student WHERE name IS NOT NULL ORDER BY name"; 

            try {
                st=con.createStatement();
                rs = st.executeQuery(idr);
            }
            catch (Exception e) {
                e.getMessage();
                System.out.println("Error " +e);
            }


            try {
                while (rs.next())   {
                    out.println("<tr>");
                        out.println("<td>" + "<input type=\"radio\" name=\"choise\" value=\"" + rs.getString(1) + "\" /> </br>" + "</td>");
                        out.println("<td>" + rs.getString(1) + "</td>" + "\t <td>" + rs.getInt(2) + "</td>" + "\t <td>" + rs.getString(3) + "</td>" + "\t <td>" + rs.getString(4)); 
                        out.println("<td>" + "<a href='"+req.getContextPath()+"/DataUpdate?mode=EDIT&name="+rs.getString(1)+"&roll="+rs.getInt(2)+"&clas="+rs.getString(3) +"&mono="+rs.getString(4)+"'>Edit</a> </br>" + "</td>"); 
                    out.println("</tr>"); 
                } 

            } 
            catch (Exception e) { 
                e.getMessage(); 
                System.out.println("Error" +e); 
            } 



            out.println("");
            out.println("<tr>"); 
            out.println("<td> </td>"); 

            out.println("<td>" + "<form>" + "<input type=\"button\" name = \"nw\" value=\"Add More Users\" onClick=\"window.location.href='"+ req.getContextPath()+"/index.jsp'\">" + "<form>" + "<td>");


            out.println("<td>" + "<form>" + "<input type=\"button\" name = \"edit\" value=\"Edit userdata\" onClick=\"window.location.href='"+ req.getContextPath()+"/DataUpdateTable'\">" + "<form>" + "<td>");


//          out.println("<td>" + "<input type=\"submit\" value = \"Edit\">" + "<a href='/SimpleServlet/'></a> </br>" + "</input>" + "</td>");


            out.println("<td>" + "<input type=\"submit\" name=\"del\" value=\"Delete\" />" + "</td>");

            out.println("<td>" + "<input type=\"submit\" value=\"Update\" />" + "</td>");

            out.println("</tr>"); 





            try {
                rs.close(); 
            }
            catch (Exception e) { 
                e.getMessage(); 
                System.out.println("Error" +e); 
            } 

            try { 
                st.close(); 
            } 
            catch (Exception e) { 
                e.getMessage(); 
                System.out.println("Error" +e); 
            } 


            out.println("</table>"); 

            out.println("</form>"); 

            out.println("</center>"); 

            out.println("</body>"); 
        out.println("</html>"); 

    out.close(); 

    } 
}

DataUpdateTable.java

import java.io.*; 
import java.sql.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 

public class DataUpdateTable extends HttpServlet    {
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws IOException, ServletException    {

        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        PrintWriter pwinsert = res.getWriter();

        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Statement st = null;


        out.println("<html>"); 
            out.println("<head>"); 
                out.println("<title>User Data</title>"); 
            out.println("</head>");

            out.println("<body>"); 
            out.println("<center><u><h1>User Data</h1></u>"); 

            out.println("<form name='form' >"); 

//          int a = 2; 
            out.println("<table border="+2+ "> "); 
            out.println("<tr>");
                out.println("<td> Name </td>");
                out.println("<td> Roll No. </td>");
                out.println("<td> Class </td>"); 
                out.println("<td> Mobile Number </td>"); 
            out.println("</tr>"); 


            String nm = req.getParameter("name");
            String roll = req.getParameter("roll");
            String clas = req.getParameter("clas");
            String mono = req.getParameter("mono");

            req.setAttribute("NAME", nm);
            req.setAttribute("ROLL", roll);
            req.setAttribute("CLAS", clas);
            req.setAttribute("MONO", mono);
            req.setAttribute("EDIT", "Y");

            req.getRequestDispatcher("/index.jsp").forward(req, res);

    }


    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws IOException, ServletException    {

        res.setContentType("text/html"); 
        PrintWriter out = res.getWriter();
        PrintWriter pwinsert = res.getWriter();
//      PrintWriter pwdelete = res.getWriter();

        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null; 
        Statement st = null; 


        try { 
            Class.forName("oracle.jdbc.driver.OracleDriver"); 
        } 
        catch(ClassNotFoundException ex)    { 
            System.out.println("driver not loaded"); 
            System.exit(0); 
        } 

        String URL = "jdbc:oracle:thin:@192.168.106.87:1521:ORA11G";
        String Username = "pratik";
        String Password = "pratik";

        try { 
            con = DriverManager.getConnection(URL,Username,Password); 

            String nm = req.getParameter("name"); 
            String roll = req.getParameter("roll"); 
            String clas = req.getParameter("clas"); 
            String mono = req.getParameter("mono"); 


            if(req.getParameter("choise")==null)    {
                ps = con.prepareStatement("update student set name=?, rollno=?, class=?, mobileno=? where rollno=?"); 
                ps.setString(1,nm); 
                ps.setString(2,roll); 
                ps.setString(3,clas); 
                ps.setString(4,mono); 
                ps.setString(5,roll); 

                int i = ps.executeUpdate(); 
                pwinsert.println(i); 


                if(i!=0)    {
                    pwinsert.println("Your data has been stored in the database"); 
                } 
                else    { 
                    pwinsert.println("Your data could not be stored in the database"); 
                } 

                res.sendRedirect( req.getContextPath()+ "/DataInsertTable");
//              res.sendRedirect("https://www.google.co.in/");

            }
        } 
        catch(Exception e)  { 
            pwinsert.println(e.getMessage()); 
        } 
    }
}
Pratik
  • 37
  • 1
  • 1
  • 5
  • I'd recommend taking that database code out of the servlet. Put it in an interface-based POJO that you can develop and test outside the servlet. Get that working and put it aside. You're mingling database and HTML generation code together in a way that'll be hard to debug and maintain. Learn JSPs and take the HTML generation out of the servlet, too. – duffymo May 29 '13 at 14:12
  • 1
    Just a tip: I would not recommend putting `System.exit(0);` in your servlet code. This shuts down the entire VM, including whatever is hosting the servlet, so all your other web apps will stop as well. – austin May 29 '13 at 14:13
  • Good tip, austin. You read it more carefully than I did. – duffymo May 29 '13 at 14:19
  • Just create the radio button this way _out.println("" + " " + "");_ – fGo May 29 '13 at 14:23
  • @Pratik i didn't check at that nivel of detail your html code, i assume it is correct. You already have a submit button – fGo May 29 '13 at 14:52
  • @Pratik I suggest you to modify completely your code and at least do each thing into a different method – fGo May 29 '13 at 14:58
  • @fGo Sir, I have updated my code. Waiting for youer reply. – Pratik Jun 08 '13 at 06:20
  • @fGo I have similar problem, see this. [http://stackoverflow.com/questions/16998126/update-edit-entered-data-from-database-servlet][1] [1]: http://stackoverflow.com/questions/16998126/update-edit-entered-data-from-database-servlet – Raman Jun 08 '13 at 10:35
  • @Pratik If you do a `toString()` in a parameter like this `String nm = req.getParameter("nm").toString();` and you didn't send anything then your code is going to break with a `NullPointerException`. You know that this is false? `System.out.println("Disconnected from database");` because you never did a `conn.close();` Instead of doing `res.sendRedirect("servletRecord");` you could do `res.sendRedirect("another.jsp");`, then inside than that jsp you point your form to an update servlet `
    ` and add the same fields that your `adduser.jsp`.
    – fGo Jun 10 '13 at 15:48
  • @fGo Query is edited, would you please check now ?? Thank you. – Pratik Jun 13 '13 at 09:16

2 Answers2

0

The first time you get into the jsp you print your form and show your fields with no much trouble (apart from the structural problems). However, in the servlet you print directly your html and as i told you in a previous comment in that case you don't include any name field. So, instead of doing this:

out.println("<td>" + "<input type=\"radio\" name=\"choise\" value=\"choise\" /> </br>" + "</td>");

You could do this:

out.println("<td>" + "<input type=\"radio\" name=\"name\" value=\"choise\" /> </br>" + "</td>");

And also, there is no form tag and there is no submit button, so, how do you pretend to send the selected student if you don't send the data? I think you have not thinked about this because you really don't understand ho the application is flowing. So the short answer is this do this:

out.println("<form method=\"get\" action=\"/datainsert/DataInsertTable\">"); //added line
out.println("<tr>");
while (rs.next())   {
  ...//you get the idea
}
out.println("</form>"); //added line

BUT in order to fix this kind of problems you'll have to read tutorials on good practices on java web programming!

fGo
  • 1,146
  • 5
  • 11
  • @Pratik doing these recommendations you won't get _null_ in the _name_ param and you'd be able to delete the data – fGo Jun 03 '13 at 12:04
  • Hello sir, I have done the connectivity about radio and database, now, I want to update the data which is already inserted by me. Would you please help me regarding to it ?? – Pratik Jun 07 '13 at 11:44
0

Inside your DataInsertTable just after this line

out.println("</html>");

you must add

response.setAttribute("EDIT", "yes");

Because you are changing the destination based on the EDIT parameter but you are never really setting it. Also instead of doing this:

out.println("<td>" + "<input type=\"submit\" value = \"Edit\">" + "<a href='"+req.getContextPath()+"/DataUpdate'></a> " + "</input>");

you should do

out.println("<td>" + "<input type=\"submit\" value = \"Edit\">" + "<a href='"+req.getContextPath()+"/DataUpdateTable'></a> " + "</input>");

NOTE: I'm assuming that you mapped your DataUpdateTable servlet to DataUpdateTable as you did in action="/SimpleServlet/DataUpdateTable";. But i can only be sure if you provide your config.

Also, i have no idea what you pretended here, but it makes no sense because you are already in a form:

out.println("<td>" + "<FORM>" + "<INPUT Type=\"BUTTON\" VALUE=\"Add More Users\" ONCLICK=\"window.location.href='"+ req.getContextPath()+"/index.jsp'\">" + "<FORM>" + "<td>");
fGo
  • 1,146
  • 5
  • 11
  • Hello sir, I need your little help, I have reedited my code and posted here again, I want to edit data based on clicking the EDIT button . Can you please help me little that how to link that EDIT feature ? Thank you. – Pratik Jun 13 '13 at 14:21
  • @Pratik why do you keep adding this
    tag to your buttons!!?? `out.println("" + "" + ...`. I told you it makes no sense since you are already in a
    !! and i told you to add the 'EDIT' attribute in the _insert_ and you did it in the _Update_! If you don't follow my recomendations than i cannot do anything for you, sorry
    – fGo Jun 14 '13 at 08:42
  • Sir I am really sorry for what I did by mistake but I am not getting as I am a beginner. If would be better if you explain and help me. Being beginner in servlet and jsp I am finding it too difficult. I request you to help me sir. Please tell me how can I add the feature of editing. There are too many hopes from you, Waiting for your kind reply. Thank you. – Pratik Jun 14 '13 at 09:56
  • @Pratik Ask a new question with your updated code, follow their recommendations and let other people help you – fGo Jun 14 '13 at 09:59
  • Sir, I have removed all unnecessary forms. can we please proceed further ? – Pratik Jun 14 '13 at 10:32