When we use ajax encapsulated by jQuery in the web
Callbacks can be executed
But this callback function accepts fixed data types
In the servlet background
Well known transmission types are
- text
- json
Of course, this is transmitted to jQuery
If jsp is used
That's another thing
So far, I haven't specifically tested whether servlet s can transfer several basic types of java
And whether the encapsulated classes can be transferred
But most of the data can be realized through text and json
Example code:
JavaScript part:
function ajax_login(){
var way = ""
if(document.getElementById("button_user").style.color == 'rgb(229, 154, 0)'){
way = "user_login";
}else{
way = "merchant_login"
}
var username_email_mobilephne = document.getElementById("login_username_email_mobilephone").value;
var password = document.getElementById("login_password").value;
$.ajax({
url: "../MedicatedDietHallServlet", //Server url to request
data: {
username_email_mobilephne: username_email_mobilephne,
password: password,
way: way
},
async: true,
cache: false,
type: "GET",
dataType: "text",
success: function(result) {
if(result == "true") {
window.location.href="home.html";
} else {
alert("Your user name/mailbox/Wrong phone number or password");
}
},
error: function(){
alert("Failed to connect to server or return data");
}
})
}
Java part:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("A user GET Mode connection Servlet Success");
// response.setContentType("text/html;charset=utf-8");
// request.setCharacterEncoding("utf-8");
// String username=URLDecoder.decode(request.getParameter("username"),"utf-8");
if(request.getParameter("way").equals("user_register")){
Id_maker id_maker = new Id_maker();
User user = new User(
id_maker.makeId(),
request.getParameter("username"),
request.getParameter("email"),
request.getParameter("mobilephone"),
request.getParameter("password")
);
user.showMyself();
Sqlserver_People_Controller controller = new Sqlserver_People_Controller();
controller.user_register(user);
response.getWriter().print("true");
}else if(request.getParameter("way").equals("user_login")){
Sqlserver_People_Controller controller = new Sqlserver_People_Controller();
User user = null;
user = controller.user_login(request.getParameter("username_email_mobilephne"));
if(user!=null && user.getPassword().equals(request.getParameter("password"))){
user.showMyself();
userNumber++;
response.getWriter().print("true");
}else{
response.getWriter().print("false");
}
}
}