Eclipse前后台交互

  • Post author:
  • Post category:其他

在Eclipse中要实现前后台交互需要两个文件,一个HTML文件,另一个是servlet文件。

html文件代码如下所示:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>first</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
	姓名:<input type="text" id="username"/><br/>
	密码:<input type="text" id="password"/><br/>
	<input type="button" value="提交" onclick="get()"/><br/>
</body>
<script>
	function get(){
		//获取用户的数据
		var username=$("#username").val();//¥(#name)是为了获取提交的姓名框,val是为了获取数据
		var password=$("#password").val();
		$.ajax({
			type:"get",//决定向后台servlet提交所使用的方法
			url:"http://localhost:8080/JinRong/FirstServlet",
			data:{"username":username,"password":password},//提交数据
			success:function(data){//获取成功返回数据
				console.log(data);//返回前台成功后的消息给后台
			}
		})
	}
</script>
</html>

servlet文件代码如下所示: 

package com.jinrong;

import java.io.IOException;
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 FirstServlet
 */
@WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FirstServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println(username + " " + password);
        String json="{\"code\":\"200\",\"message\":\"成功\"}";
		response.getWriter().append(json);
	}

	/**
	 * @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);
	}

}

运行后的前台提交数据会在后台显示,成功后会给前台返回json格式的信息。 

如果后台返回前台的信息出现乱码 ,代表上方字符集不一致,需要在servlet文件中添加如下代码即可,添加在定义{“code”:”200″,”message”:”成功”}代码的上方即可。

//设定字符集,防止前后交互出现乱码
response.setContentType("text/json;charset=utf-8");
response.setCharacterEncoding("utf-8");

如果后台需要返回前台的message信息,只需要在html文件中的ajax的function(data)中添加如下代码即可。 

console.log(data.message);


版权声明:本文为jyr2014原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。