java后台给前端返回数据,原生的方法

1:接口请求返回数据(继承BaseController)

	@RequestMapping(value = "/demo")
	public void dopmitemdelete(String code) {
		try {
			if (code == 0) {
				returnSuccessJson(null);
			} else {
				returnErrorJson("失败");
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			returnErrorJson("异常失败!");
			return;
		}
	}

2:BaseController类

package com.xs.breast.view;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.xs.breast.commons.business.constant.Config;
import com.xs.breast.commons.business.vo.JsonResult;
import com.xs.breast.commons.framework.util.SpringMVCUtils;

public class BaseController {

	@Autowired
	protected HttpServletRequest request; 
    
    //验证码相关
    private int width = 90;// 定义图片的width
    private int height = 20;// 定义图片的height
    private int codeCount = 4;// 定义图片上显示验证码的个数
    private int xx = 15;
    private int fontHeight = 18;
    private int codeY = 16;
    char[] codeSequence = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

    public HttpServletResponse getResponse( ) {
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getResponse();
		return response;
	}
		
	protected void returnSuccessJson(Object data){
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(Config.JSON_RESULT_CODE_SUCCESS);
        jsonResult.setObj(data);
        SpringMVCUtils.renderJson(getResponse(),jsonResult);
    }
	
    protected void returnErrorJson(String msg) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(Config.JSON_RESULT_CODE_FAIL);
        jsonResult.setMsg(msg);
        SpringMVCUtils.renderJson(getResponse(),jsonResult);
    }
    
	protected void returnJson(Map<String, Object> callResut) {
		JsonResult jsonResult = new JsonResult();
		jsonResult.setCode((String) callResut.get("Code"));
		jsonResult.setObj(callResut.get("Data"));
		jsonResult.setMsg((String) callResut.get("Msg"));
		SpringMVCUtils.renderJson(getResponse(), jsonResult);
	}
    //生成随机4位数
	public String getRandomCode(String sessionKey) throws Exception {
		Random random = new Random();
		StringBuffer randomCode = new StringBuffer();
		for (int i = 0; i < codeCount; i++) {
            // 得到随机产生的验证码数字。
            String code = String.valueOf(codeSequence[random.nextInt(codeSequence.length-1)]);
            // 将产生的四个随机数组合在一起。
            randomCode.append(code);
        }
		// 将四位数字的验证码保存到Session中。
        HttpSession session = request.getSession();
        
        session.setAttribute(sessionKey, randomCode.toString());
        
		return randomCode.toString();
	}

	//生成随机4位数图片    
    public String getCode(String sessionKey) throws Exception {	
        // 定义图像buffer
        BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics gd = buffImg.getGraphics();
        // 创建一个随机数生成器类
        Random random = new Random();
        // 将图像填充为白色
        gd.setColor(Color.WHITE);
        gd.fillRect(0, 0, width, height);
        // 创建字体,字体的大小应该根据图片的高度来定。
        Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
        // 设置字体。
        gd.setFont(font);
        // 画边框。
        gd.setColor(Color.BLACK);
        gd.drawRect(0, 0, width - 1, height - 1);
        // 随机产生40条干扰线,使图象中的认证码不易被其它程序探测到。
        gd.setColor(Color.BLACK);
        for (int i = 0; i < 40; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            gd.drawLine(x, y, x + xl, y + yl);
        }
        // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
        StringBuffer randomCode = new StringBuffer();
        int red = 0, green = 0, blue = 0;
        // 随机产生codeCount数字的验证码。
        for (int i = 0; i < codeCount; i++) {
            // 得到随机产生的验证码数字。
            String code = String.valueOf(codeSequence[random.nextInt(codeSequence.length-1)]);
            // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
            red = random.nextInt(255);
            green = random.nextInt(255);
            blue = random.nextInt(255);
            // 用随机产生的颜色将验证码绘制到图像中。
            gd.setColor(new Color(red, green, blue));
            gd.drawString(code, (i + 1) * xx, codeY);
            // 将产生的四个随机数组合在一起。
            randomCode.append(code);
        }
        // 将四位数字的验证码保存到Session中。
        HttpSession session = request.getSession();
        
        session.setAttribute(sessionKey, randomCode.toString());
        // 禁止图像缓存。
        HttpServletResponse response = getResponse();
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(buffImg, "jpeg", sos);
        sos.close();
        
        return randomCode.toString();
    }
    
    protected boolean checkCodeIsRight(String code, String sessionKey) throws Exception {
    	
    	HttpSession session = request.getSession();
    	
    	String randomCode = (String) session.getAttribute(sessionKey);
    	
    	if( randomCode == null || !randomCode.equals(code) ){
    		return false;
    	}
    	
    	session.removeAttribute(sessionKey);
    	
    	return true;
    }
}

1:定义一个SpringMVCUtils.java

package com.xs.breast.commons.framework.util;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

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

import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.opensymphony.xwork2.ActionContext;

public class SpringMVCUtils {

	// -- header 常量定义 --//
	private static final String HEADER_ENCODING = "encoding";
	private static final String HEADER_NOCACHE = "no-cache";
	private static final String DEFAULT_ENCODING = "UTF-8";
	private static final boolean DEFAULT_NOCACHE = true;

	// -- content-type 常量定义 --//
	private static final String TEXT_TYPE = "text/plain";
	private static final String JSON_TYPE = "application/json";
	private static final String XML_TYPE = "text/xml";
	private static final String HTML_TYPE = "text/html";
	private static final String JS_TYPE = "text/javascript";

	private static ObjectMapper mapper = new ObjectMapper();


	/**
	 * struts里的Session实际上是一个Map集合, private Map session;
	 * 与servlet的HttpSession不同,struts2的session并不能在不同action里引用,
	 * 放入session的值,只能在本action里取,以及传递到页面上。 頁面使用這個session用 <s:property
	 * value="#session.session_owner_name.owner_name"/>
	 * 
	 * @return
	 */
	public static Map<String, Object> getSessionMap() {
		return ActionContext.getContext().getSession();
	}

	// -- 取得Request/Response/Session的简化函数 --//
	public static Map<String, Object> getRequestHashMapParam(){
		HttpServletRequest request = getRequest();
		Map resultMap = new HashMap<String, String>();
		Map paramMap = request.getParameterMap();
		Set keySet = paramMap.keySet();
		for(Object o:keySet){
			String key = (String)o;
			String[] param = (String[]) paramMap.get(key);
			if(param.length>1){
				resultMap.put(key, param);
			}else{
				resultMap.put(key, param[0]);
			}
		}
		return resultMap;
	}

	/**
	 * 取得HttpRequest的简化函数.
	 */
	public static HttpServletRequest getRequest() {
		return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
	}

	/**
	 * 取得HttpResponse的简化函数.
	 */
	public static HttpServletResponse getResponse() {
		return ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse();
	}

	/**
	 * 取得Request Parameter的简化方法.
	 */
	public static String getParameter(String name) {
		return getRequest().getParameter(name);
	}

	// -- 绕过jsp/freemaker直接输出文本的函数 --//
	/**
	 * 直接输出内容的简便函数.
	 * 
	 * eg. render("text/plain", "hello", "encoding:GBK"); render("text/plain",
	 * "hello", "no-cache:false"); render("text/plain", "hello", "encoding:GBK",
	 * "no-cache:false");
	 * 
	 * @param headers
	 *            可变的header数组,目前接受的值为"encoding:"或"no-cache:",默认值分别为UTF-8和true.
	 */
	public static void render(final String contentType, final String content,
			final String... headers) {
		HttpServletResponse response = initResponse(contentType, headers);
		try {
			response.getWriter().write(content);
			response.getWriter().flush();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * 直接输出文本.
	 * 
	 * @see #render(String, String, String...)
	 */
	public static void renderText(final String text, final String... headers) {
		render(TEXT_TYPE, text, headers);
	}

	/**
	 * 直接输出HTML.
	 * 
	 * @see #render(String, String, String...)
	 */
	public static void renderHtml(final String html, final String... headers) {
		render(HTML_TYPE, html, headers);
	}

	/**
	 * 直接输出XML.
	 * 
	 * @see #render(String, String, String...)
	 */
	public static void renderXml(final String xml, final String... headers) {
		render(XML_TYPE, xml, headers);
	}

	/**
	 * 直接输出JSON.
	 * 
	 * @param jsonString
	 *            json字符串.
	 * @see #render(String, String, String...)
	 */
	public static void renderJson(final String jsonString,
			final String... headers) {
		render(JSON_TYPE, jsonString, headers);
	}

	/**
	 * 直接输出JSON,使用Jackson转换Java对象.
	 * 
	 * @param data
	 *            可以是List<POJO>, POJO[], POJO, 也可以Map名值对.
	 * @see #render(String, String, String...)
	 */
	public static void renderJson(HttpServletResponse response, final Object data) {
		response.setContentType(JSON_TYPE + ";charset=" + DEFAULT_ENCODING);
		try {
			mapper.writeValue(response.getWriter(), data);
//			Writer out= new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));
//			mapper.writeValue(out, data);
		} catch (IOException e) {
			throw new IllegalArgumentException(e);
		}
	}
	/**
	 * 直接输出JSON,不需要传response
	 */
	public static void renderJson(final Object data) {
		HttpServletResponse response = initResponse(JSON_TYPE);
		try {
			mapper.writeValue(response.getWriter(), data);
		} catch (IOException e) {
			throw new IllegalArgumentException(e);
		}
	}

	/**
	 * 直接输出JSON,使用Jackson转换Java对象.
	 * 
	 * @param data
	 *            可以是List<POJO>, POJO[], POJO, 也可以Map名值对.
	 * @see #render(String, String, String...)
	 */
	public static void renderJson(final Object data, final String... headers) {
		HttpServletResponse response = initResponse(JSON_TYPE, headers);
		try {
			mapper.writeValue(response.getWriter(), data);
		} catch (IOException e) {
			throw new IllegalArgumentException(e);
		}
	}
	
	
	
	public static String toJsonString(Object data) {
		try {
			return mapper.writeValueAsString(data);
		} catch (IOException e) {
			throw new IllegalArgumentException(e);
		}
	}

	/**
	 * 直接输出支持跨域Mashup的JSONP.
	 * 
	 * @param callbackName
	 *            callback函数名.
	 * @param object
	 *            Java对象,可以是List<POJO>, POJO[], POJO ,也可以Map名值对, 将被转化为json字符串.
	 */
	public static void renderJsonp(final String callbackName,
			final Object object, final String... headers) {
		String jsonString = null;
		try {
			jsonString = mapper.writeValueAsString(object);
		} catch (IOException e) {
			throw new IllegalArgumentException(e);
		}

		String result = new StringBuilder().append(callbackName).append("(")
				.append(jsonString).append(");").toString();

		// 渲染Content-Type为javascript的返回内容,输出结果为javascript语句,
		// 如callback197("{html:'Hello World!!!'}");
		render(JS_TYPE, result, headers);
	}

	/**
	 * 分析并设置contentType与headers.
	 */
	private static HttpServletResponse initResponse(final String contentType,
			final String... headers) {
		// 分析headers参数
		String encoding = DEFAULT_ENCODING;
		boolean noCache = DEFAULT_NOCACHE;
		for (String header : headers) {
			String headerName = StringUtils.substringBefore(header, ":");
			String headerValue = StringUtils.substringAfter(header, ":");

			if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
				encoding = headerValue;
			} else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
				noCache = Boolean.parseBoolean(headerValue);
			} else {
				throw new IllegalArgumentException(headerName
						+ "不是一个合法的header类型");
			}
		}
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getResponse();
//		HttpServletResponse response = ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse();

		// 设置headers参数
		String fullContentType = contentType + ";charset=" + encoding;
		response.setContentType(fullContentType);
		if (noCache) {
			WebUtils.setNoCacheHeader(response);
		}

		return response;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值