Share on Google+Share on Google+

ramyajayaraman
JSP,DB,SERVLET
2 Answer(s)      6 years and 4 months ago
Posted in : JSP-Servlet

I have a jsp page called page1.jsp with 3 text fields name,phone ,city.i populated these datas into a database table through servlet (page1servlet.java) and bean(page1bean.java).I have another jsp page(display.jsp) with 4 fields name, city ,phone.Once the user enter the name, city and phone should be automatically populated from database through servlet(SetDetailsServlet.java)..I did till connecting and populating datas in datbase bt I could not populate the datas automatically from databse in jsp on entering name ...can u help me????????

My codes**

these are my codes.....


Page1.jsp

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

<HTML> <HEAD> <TITLE>insert data using prepared statement

<BODY bgcolor="#ffffcc">
loginform!

<FORM action="page1servlet" method="post"> <TABLE style="background-color: #ECE5B6;" WIDTH="30%" >

  <TR>
      <TH width="50%">Name</TH>
      <TD width="50%"><INPUT TYPE="text" NAME="name"></TD>
  </tr>
  <TR>
     <TH width="50%">City</TH>
     <TD width="50%"><INPUT TYPE="text" NAME="city"></TD>
  </tr>
  <TR>
     <TH width="50%">Phone</TH>
     <TD width="50%"><INPUT TYPE="text" NAME="phone"></TD>
  </tr>


  <TR>
      <TH></TH>
      <TD width="50%"><INPUT TYPE="submit" VALUE="submit"></TD>
  </tr>

Page1Bean.java

public class Page1bean { private String name; private String city; private String phone; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub

}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getCity() {
    return city;
}
public void setCity(String city) {
    this.city = city;
}
public String getPhone() {
    return phone;
}
public void setPhone(String phone) {
    this.phone = phone;
}

}

Page1servlet.java

import java.io.IOException;

import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;

import newpack.DBOperation;

/** * Servlet implementation class page1servlet */ public class page1servlet extends HttpServlet { private static final long serialVersionUID = 1L;

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

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException
{
    RequestDispatcher rd = null;
    String sname,scity,sphone,check=null;

    sname = request.getParameter("name");
    scity = request.getParameter("city");
    sphone= request.getParameter("phone");


    try 
    {
        //System.out.println(firstName);
        DBOperation objDB = new DBOperation();
        check = objDB.savestuinfo(sname,scity,sphone);
        System.out.println(check);
        if(check == "")
        {
            HttpSession s=request.getSession(true);
            s.setAttribute("name", sname);
            s.setAttribute("city", scity);
            s.setAttribute("phone", sphone);

            rd = request.getRequestDispatcher("display.jsp");
        }
        else
        {

            rd = request.getRequestDispatcher("Error.jsp");
        }
    } 
    catch (Exception e) 
    {
        request.setAttribute("Error", e.getMessage());
        rd = request.getRequestDispatcher("Error1.jsp");
    }

    rd.forward(request, response);
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

}

DbConnection.java

import java.sql.DriverManager;

import com.mysql.jdbc.Connection;

public class DBConnection {

    public static Connection getDBConnection()throws ClassNotFoundException,Exception
    {
        Connection con = null;

        try 
        {
            Class.forName("com.mysql.jdbc.Driver");
            con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root");    
        }
        catch (ClassNotFoundException e) 
        {
            throw e;
        }
        catch (Exception e)
        {
            throw e;
        }

        return con;
    }
}

DbOperation.java

import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement;

import newpack.DBConnection;

import com.mysql.jdbc.CallableStatement; import com.mysql.jdbc.PreparedStatement; import com.mysql.jdbc.ResultSet;

public class DBOperation { Connection con; Statement stmt;

public String savestuinfo (String sname, String  scity, String sphone)
{
    String sMsg = "";

    try 
    {

        con = DBConnection.getDBConnection();
        PreparedStatement pstmt = (PreparedStatement) con.prepareStatement("INSERT INTO student(name,city,phone) VALUES(?,?,?)");

        pstmt.setString(1, sname);
        pstmt.setString(2, scity);
        pstmt.setString(3, sphone);


        if(pstmt.execute() == true)
        {
                sMsg = "ERROR";
        }
        pstmt.close();
    } 
    catch (SQLException e) 
    {
        sMsg = "ERROR" + e.getMessage();
        e.printStackTrace();
    }
    catch (Exception e)
    {
        sMsg = "ERROR" + e.getMessage();
        e.printStackTrace();
    }
    finally
    {
        try 
        {
            con.close();
        }
        catch (Exception e2) 
        {}
    }

    return sMsg;
}
public String getuserdetails(String sname, String scity,String sphone)throws SQLException, ClassNotFoundException, Exception
{


    String sQuery = "SELECT s.city,s.phone FROM stu_info s WHERE name = '"+sname+"'";
    Connection con = null;
    try 
    {
        con = DBConnection.getDBConnection();
        stmt = (Statement)con.createStatement();

        ResultSet rs = (ResultSet) stmt.executeQuery(sQuery);

        if(rs.next())
        {
        scity = rs.getString("city");
        sphone=rs.getString("phone");
        }
        else
        {
        scity = "";
        sphone="";
        }
    } 
    catch (Exception e)
    {
        throw e;
    }
    finally
    {
        con.close();
    }
    return sQuery;


}

}

display.jsp

Insert title here

Name Inserted <%=session.getAttribute("name")%>
Name
City
Phone

GetDetailServlet.java

import java.io.IOException;

import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;

/** * Servlet implementation class for Servlet: GetDetailServlet * */ public class GetDetailServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { static final long serialVersionUID = 1L;

/* (non-Java-doc)
 * @see javax.servlet.http.HttpServlet#HttpServlet()
 */
public GetDetailServlet() {
    super();
}       

/* (non-Java-doc)
 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
}   

/* (non-Java-doc)
 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    RequestDispatcher rd = null;
    String sname,scity,sphone,check=null;

    sname = request.getParameter("name");
    scity = request.getParameter("city");
    sphone= request.getParameter("phone");


    try 
    {
        //System.out.println(firstName);
        DBOperation objDB = new DBOperation();
        check = objDB.savestuinfo(sname,scity,sphone);
        if(check == "")
        {
            HttpSession s=request.getSession(true);
            s.setAttribute("name", sname);
            s.setAttribute("city", scity);
            s.setAttribute("phone", sphone);

            rd = request.getRequestDispatcher("Success.jsp");
        }
        else
        {

            rd = request.getRequestDispatcher("Error.jsp");
        }
    } 
    catch (Exception e) 
    {
        request.setAttribute("Error", e.getMessage());
        rd = request.getRequestDispatcher("Error.jsp");
    }

}

}

Success.jsp

Insert title here Success in Connection

Ads

View Answers

December 10, 2010 at 5:15 PM


Hi Friend,

We are sending you the simple code. Try it. 1)insert.jsp:

<html>
<form method="post" action="../InsertServlet">
<table>
<tr><td>Name:</td><td><input type="text" name="name"></td></tr>
<tr><td>Age:</td><td><input type="text" name="age"></td></tr>
<tr><td>City:</td><td><input type="text" name="city"></td></tr>
<tr><td></td><td><input type="submit" value="Submit"></td></tr>
</table>
</form>
</html>

2)InsertServlet.java:

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

public class InsertServlet extends HttpServlet { 
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException {
        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        String name=req.getParameter("name");
int age=Integer.parseInt(req.getParameter("age"));
String city=req.getParameter("city");
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
           Connection con = DriverManager.getConnection("jdbc:odbc:student");
           Statement st=con.createStatement();
           int i=st.executeUpdate("insert into data(name,age, city) values('"+name+"',"+age+",'"+city+"')");
         con.close();
         res.sendRedirect("/examples/jsp/ajax.jsp");

}
catch(Exception e){
    System.out.println(e);
}
            }
        }

3)ajax.jsp:

<%@page import="java.sql.*"%>
<html>
<head>
<script type="text/javascript">
function showData(value){ 
xmlHttp=GetXmlHttpObject()
var url="../AjaxServlet"
url=url+"?name="+value
xmlHttp.onreadystatechange=stateChanged 
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged() { 
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
    var showdata = xmlHttp.responseText; 
    var strar = showdata.split(":");
    document.getElementById("age").value= strar[1];
    document.getElementById("city").value= strar[2];

 } 
}
function GetXmlHttpObject(){
var xmlHttp=null;
try {
  xmlHttp=new XMLHttpRequest();
 }
catch (e) {
 try  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}
</script>
</head>
<body>
<form name="employee">
<br><br>
<table border="0" width="400px" align="center" bgcolor="#CDFFFF">
<div id="mydiv"></div>
   <tr><td><b>Name:</b></td><td> 
 <input  type="text" name="name" id="name" onkeyup="showData(this.value);"></td></tr>
<tr><td ><b>Age:</b></td><td>
<input  type="text" name="age" id="age" ></td></tr>
<tr><td><b>City:</b></td><td>
<input  type="text" name="city" id="city" ></td></tr>
<tr><td><b>Phone No:</b></td><td>
<input  type="text" name="phoneno" id="phoneno"></td></tr>

</table>
</form>    
<table border="0" width="100%" align="center">
<br>
<br>
</table>
</body>
</html>


December 10, 2010 at 5:16 PM


continue..

4)AjaxServlet.java:

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

public class AjaxServlet extends HttpServlet { 
    public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException {
        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        String name = req.getParameter("name").toString();
        System.out.println(name);
String data ="";
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
           Connection con = DriverManager.getConnection("jdbc:odbc:student");
           Statement st=con.createStatement();
           ResultSet rs=st.executeQuery("select * from data where name='"+name+"'");
while(rs.next())
{
data =":"+Integer.toString(rs.getInt("age")) + ":" + rs.getString("city");
}


out.println(data);
System.out.println(data);
}
catch (Exception e) {
System.out.println(e);
}
        }
        }

Thanks










Related Tutorials/Questions & Answers:
JSP,DB,SERVLET
JSP,DB,SERVLET  hi thank you for your reply.With this code i can insert the data successfully into database but In ajax.jsp once i give the name;;;age and city are not automatically fetched......instead sumthing get filled
JSP,DB,SERVLET
JSP,DB,SERVLET  I have a jsp page called page1.jsp with 3 text fields name,phone ,city.i populated these datas into a database table through servlet (page1servlet.java) and bean(page1bean.java).I have another jsp page(display.jsp
Advertisements
JSP,DB,SERVLET
JSP,DB,SERVLET  hi thank you for your reply.With this code i can insert the data successfully into database but once i give submit button... servlet Code u sent to me:: 1)insert.jsp: <%@page import="java.sql.*"%>
JSP,DB,SERVLET
JSP,DB,SERVLET  I have a jsp page with 3 text fields name,age ,city.i populated these datas into a database table.I have another jsp page with 4... be automatically populated from database throush servlet..Can u give me the code
Tutorials   
Java Spring Hibernate Struts Training fat image from db fat image from db fat image from db fat image from db unable to get value returned from javascript variable in page How to change image size before adding to mysql using jsp Design a registration.jsp page with input for user registration details Cart Quantity jsp servlet coding issue servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ? servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ? servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ? servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ? servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ? servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ? servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ? image pdf marking pdf marking Multiple image upload using JSP Read code from excel sheet and upload into database using JSP Student java about search engine Convert BLOB to PDF and save it to a location how to copy files from remote to local machine using SFTP SSL in java? Like Team viewer Socket and Servert -Jsp how to copy files from remote location to local using java? How To Store Multilple Images In MySQL database dynamically with image uploader and then retrieve them in image gallery using java how to create SOAP based web service in java? how to fetch data from mysql database table and draw a bar chart on that data using in jsp how to create users in LDAP using java? how to authenticate user using TIVOLI api in java? how to create users using IBM Tivoi API in jsp/servelet? Java/J2ee Please explain this code as many packages and classes are unknown to me .! how to download the uploaded folder files using jsp Login Query image is display from path of mysql database please reply the code to store dynamic fields in database? Reloading issue in jsp How to get Button Id ? calling one jap page from another jsp page login login Problem to get connection from DAO class to JDBC Page Loading Time Fix table's column's name row(1st row of the table) so that it does not move up when the table is scrolled up to view more rows below Sending hidden values

Ads

 
Advertisement null

Ads