jquery访问servlet并返回数据到页面的方法
本文实例讲述了jquery访问servlet并返回数据到页面的方法。分享给大家供大家参考。具体实现方法如下:
1.servlet:AjaxServlet.java如下:
packagecom.panlong.servlet;
importjava.io.IOException; importjava.io.PrintWriter; importjava.net.URLDecoder;
importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse;
publicclassAjaxServletextendsHttpServlet{ privatestaticfinallongserialVersionUID=1L; protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp) throwsServletException,IOException{ Integertotal=(Integer)req.getSession().getAttribute("total"); inttemp=0; if(total==null){ temp=1; }else{ temp=total.intValue()+1; } req.getSession().setAttribute("total",temp); try{ //1.取参数 resp.setContentType("text/html;charset=GBK"); PrintWriterout=resp.getWriter(); Stringold=req.getParameter("name"); //2.检查参数是否有问题 //Stringname=newString(old.getBytes("iso8859-1"),"UTF-8"); Stringname=URLDecoder.decode(old,"UTF-8"); if("".equals(old)||old==null){ out.println("用户名必须输入"); }else{ if("liling".equals(name)){ out.println("恭喜登录成功"); return; }else{ out.println("该用户名未注册,您可以注册["+name+"]这个用户名"+temp); } } }catch(Exceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } //3.检验操作 } protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp) throwsServletException,IOException{ doGet(req,resp); } }