Servlet实现前后端交互

原理:通过ajax调用HttpServlet来实现前后端数据交互

1.前端方面,通过ajax实现调用(别忘记引用jQuery)

实例:





Insert title here
	


	name:
	age:
	sex:
	


	
	

2.后台通过继承HTTPservlet实现后台调用

即运行一下servlet获得地址放到前台的url中

package ser;

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 myser
 */
@WebServlet("/myser")
public class myser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public myser() {
        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
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		
		String rep = "xfgxf";
		rep="{\"name\":\"小王\",\"age\":22,\"sex\":\"男\"}";
		//doGet(request, response);
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json; charset=utf-8");
		response.getWriter().write(rep);
		
		String name=request.getParameter("name");
		String age=request.getParameter("age");
		String sex=request.getParameter("sex");

		System.out.println(name+""+age+""+sex);
		
	}

}

你可能感兴趣的:(html,java,数据库)