ajax向后台发送数据

  这是ajax向后台发送服务器的一个小demo。





Insert title here





  
股票实时行情
代码名称价格

后台模拟数据

package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

import bean.Stock;

public class ActionServlet extends HttpServlet {
	@Override
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		String uri=request.getRequestURI();
		String action=uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf("."));
		System.out.println(action);
		if("/quoto".equals(action)) {
			//模拟生成几只股票的信息
			Random r=new Random();
			List stocks=new ArrayList();
			for(int i=0;i<8;i++) {
				Stock s=new Stock();
				s.setCode("60087"+r.nextInt(10));
				s.setName("中国嘉陵"+r.nextInt(10));
				s.setPrice(r.nextInt(500));
				stocks.add(s);
			}
			ObjectMapper om=new ObjectMapper();
			String json=om.writeValueAsString(stocks);
			out.println(json);
			System.out.println(json);
			
		}else if("/getNumber".equals(action)) {
			Random r=new Random();
			int number=r.nextInt(10000);
			System.out.println("number:"+number);
//			ObjectMapper om=new ObjectMapper();
//			String jsonum=om.writeValueAsString(number);
//			out.println(jsonum);
			out.println(number);
		}else if("/saveInfo".equals(action)) {
			String name=request.getParameter("name");
			String phone=request.getParameter("phone");
			String address=request.getParameter("address");
			System.out.println("name:"+name+",phone:"+phone+",address:"+address);
			out.print("保存送货信息成功!");
		}
	}

}

 

你可能感兴趣的:(java之ssh框架)