Entity:
package entity;
public class MyJson {
public MyJson() {
// TODO Auto-generated constructor stub
}
private String status;
private String type;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
还有一个Customer类的实体在这就不放代码了。
servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
response.addHeader("Access-Control-Allow-Origin", "*");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
String username=request.getParameter("username");
String password = request.getParameter("password");
Customer customer = new Customer();
customer.setAccount(username);
customer.setPassword(password);
PrintWriter out = null;
out = response.getWriter();
MyJson myJson = new MyJson();
LoginService loginService = new LoginServiceImpl();
if(loginService.loginSucess(customer)){
myJson.setStatus("ok");
}else{
myJson.setStatus("no");
}
JSONObject jsonObject = JSONObject.fromObject(myJson);
out.write(jsonObject.toString());
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>old_books</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
</web-app>
前端:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
var data = {};
//获取input中的值传到后端
data['username'] = $('#username').val();
data['password'] = $('#password').val();
$.ajax({
url:"http://localhost:8080/old_books/Login",
type:"POST",
data:data,
dataType:"json",
success:function(data){
//alert("111")
alert(data.status);
},
error:function(XMLHttpRequest, textStatus, errorThrown){
alert("XMLHttpRequest:"+XMLHttpRequest.readyState+"\ntextStatus:"+textStatus+"\nerrorThrown:"+errorThrown);
}
});
});
});
</script>
</head>
<body>
<button>向页面发送 HTTP POST 请求,并获得返回的结果</button>
<input type="text" id="username" name="username">
<input type="text" id="password" name="password">
</body>
</html>