How to show data from database in textbox in jsp
Here is an example that retrieve the particular record from the database and display it in textbox using JSP.
<%@page language="java"%> <%@page import="java.sql.*"%> <table border="1"> <% try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); String query = "select * from employee where id='1'"; Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(query); if(rs.next()){ %> <tr> <tr><td>Name</td><td><input type="text" name="name" value="<%=rs.getString("name")%>"></td></tr> <tr><td>Address</td><td><input type="text" name="address" value="<%=rs.getString("address")%>"></td></tr> <tr><td>Contact No</td><td><input type="text" name="contact" value="<%=rs.getInt("contactNo")%>"></td></tr> <tr><td>Email</td><td><input type="text" name="email" value="<%=rs.getString("email")%>"></td></tr> <% } } catch(Exception e){} %> </table>
Here is an example of autocompletebox in JSP. As the user tpe any letter in the textbox, corresponding values will get displayed.
1)auto.jsp:
<%@page import="java.sql.*"%> <html> <head> <script language="javascript" type="text/javascript"> var xmlHttp var xmlHttp function showState(str){ if (typeof XMLHttpRequest != "undefined"){ xmlHttp= new XMLHttpRequest(); } else if (window.ActiveXObject){ xmlHttp= new ActiveXObject("Microsoft.XMLHTTP"); } if (xmlHttp==null){ alert ("Browser does not support XMLHTTP Request") return } var url="get.jsp"; url += "?count=" +str; xmlHttp.onreadystatechange = stateChange; xmlHttp.open("GET", url, true); xmlHttp.send(null); } function stateChange(){ if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ document.getElementById("country").innerHTML=xmlHttp.responseText; } } </script> </head> <body> <input id="name" type="text" name="name" onkeyup="showState(this.value)"> <br> <div id='country'> </div> </body> </html>
2)get.jsp:
<%@page language="java" import ="java.sql.*" %> <% String name=request.getParameter("count"); String buffer="<div>"; Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("Select * from country where countryname LIKE '"+name+"%'"); while(rs.next()){ buffer=buffer+rs.getString(2)+"<br>"; } buffer=buffer+"</div>"; response.getWriter().println(buffer); %>
i want to show data in text field not in any divison ....how to show it??
means i want to autocomplete the text field using ajax. plz tell me how to do it??
Ads