π ajax standard form
inside an object, key:value are repeated.
data
= queryString
$.ajax({
π£ url:'MethodServlet',
π£ method:'get',
π£ data:'userid='+$('input[name=userid]').val
+'&passwd='+$('input[name=passwd]').val
π£ dataType:'text/xml/json',
π£ beforeSend:function(){}, //usually validation
π£ success:function(name whatever you want){
alert(name whatever you want);
},
π£ complete:function(){
}
});
π ajax form short.ver
$.get or post(URL,data,function(data,status,xhr),dataType)
$(document)
.on('click','#btnLogin',function(){
$.get/post("MethodServlet", //URL
{userid:$('input[name=userid]').val(),
passwd:$('input[name=passwd]').val()}, //data
function(txt){
alert(txt);
}, //function
'text'); //dataType
})
//data must be inside an object!! and key:value!!
//{key:value, key:value}
//Below the three codes are rarely used
//.done(function(){})
//.error(function(){})
//.always(function(){})
π Practice
πͺ Client
Get a number from the user. And click the 'result' button.
Before call Ajax check the data from the user is a number.
Call Ajax and get the result from the server and print it
π Server
Receive the number and evaluate the sum (1 ~ number from the user)
Get a number from the user.
Validation
Data from the user should be a NUMBER.
π .isNumeric()
is required
Call the servlet
Follow the template
$.get/post(URL,data,function(data,status,xhr),dataType)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Show</title>
</head>
<body>
<input type=text id=txtnum size=10> //get a number
<input type=button id=btnRun value='result'> //button
</body>
<script src="http://code.jquery.com/jquery-3.5.0.js"></script>
<script>
$(document)
.on('click','#btnRun',function(){
console.log('txtnum ['+$('#txtnum').val()+']');
if($.isNumeric($('#txtnum').val())){ //validation
$.get("web06Servlet", // call the servlet
{txtnum:$('input[id=txtnum]').val()},
function(txt){
console.log(txt);
$('#txtnum').val(txt);
},
'text');
}else{
alert("Wrong access")
}
})
</script>
</html>
Receive the number
Actually survlet only can get String. Other data types are not available. Therefore, change String to Integer.
String txtnum=request.getParameter("txtnum");
int n=Integer.parseInt(txtnum);
Evaluate the sum
int result=0;
for(int i=1; i<=n;i++) {result=result+i;}
package web06;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class web06Servlet
*/
@WebServlet("/web06Servlet")
public class web06Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public web06Servlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
String txtnum=request.getParameter("txtnum");
System.out.println("txtnum ["+txtnum+"]");
int n=Integer.parseInt(txtnum);
int result=0;
for(int i=1; i<=n;i++) {
result=result+i;
}
PrintWriter out=response.getWriter();
out.println(result);
out.close();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
π DB Connection
Oracle DB and Eclipse
Copy ojdbc6.jar
to lib folder(μ€λΌν΄ κΉλ¦° ν΄λμ μλκ±°)
D(or C drive):\app\username\product\11.2.0\dbhome_1\jdbc\lib
Before connecting
cmd - run sqlplus - id : system, password : - select emp_name from employees
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DB Connection</title>
</head>
<body>
<table id='tblData'>
</table><br><br>
<input type=button id=btnGet value='show'>
</body>
<script src='http://code.jquery.com/jquery-3.5.0.js'></script>
<script>
$(document)
.on('click','#btnGet',function(){
$.get('selectServlet', {}, function(txt){
alert("Enter the data");
ar=txt.split(',');
for(i=0;i<ar.length;i++){
//<tr><td>name</td></tr>
console.log(ar[i]);
name='<tr><td>'+ar[i]+'</td></tr>';
$('#tblData').append(name);
}
},'text');
return false;
});
</script>
</html>
package web07;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class selectServlet
*/
@WebServlet("/selectServlet")
public class selectServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
String url;
String userid;
String passwd;
/**
* @see HttpServlet#HttpServlet()
*/
public selectServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
url="jdbc:oracle:thin:@localhost:1521:orcl"; //orcl = SID(database name)
userid="system";
passwd="human123";
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
PrintWriter out=response.getWriter();
try {
String sql="select emp_name from employees order by emp_name";
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url,userid,passwd);
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
String str=""; //John, Smith,..(One row)
while(rs.next()) {
if(!str.equals("")) {
str+=",";
}
str+=rs.getString("emp_name");
}
out.println(str);
out.close();
} catch(Exception e) {
out.println("error");
} finally {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
while(rs.next()) {
if(!str.equals("")) {
str+=",";
β str+=rs.getString("emp_name"); β
}
}
β Correct code β
while(rs.next()) {
if(!str.equals("")) {
str+=",";
}
str+=rs.getString("emp_name");
}