I am using azax to dynamically change the jsp page and I want to send data from that jsp page to a servlet. The jsp code:
<input type="submit" oninput="loadXMLDoc(this.value)" value="ok" name="ok">
<div id="myDiv">
Insert Id:<input id="p1" type="text" name="edit1" value=""style="visibility:hidden" size="30"/>
</div>
function loadXMLDoc(str){
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","edit?q="+str,true);
xmlhttp.send();
}
The servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter(); Connection conn=null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "studentdatabase";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "1234";
String student=request.getParameter("str");
Statement stmt;out.println(student);
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
String query = "select name1,telephone,email,department from studentinfo where studentid='"+student+"";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
String s = rs.getObject(1).toString();
out.println("<p> " +s+ "</p>");
}
conn.close;
//System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
The String student shows null
even though there is value in the database for studentid=student.
Since you are using HTTP-POST you have to put your params into the send method.
...
var params = "q="+str;
xmlhttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.