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;
private int height = 20;
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);
}
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);
}
HttpSession session = request.getSession();
session.setAttribute(sessionKey, randomCode.toString());
return randomCode.toString();
}
public String getCode(String sessionKey) throws Exception {
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);
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);
}
StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0;
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);
}
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");
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 {
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;
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();
public static Map<String, Object> getSessionMap() {
return ActionContext.getContext().getSession();
}
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;
}
public static HttpServletRequest getRequest() {
return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
}
public static HttpServletResponse getResponse() {
return ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse();
}
public static String getParameter(String name) {
return getRequest().getParameter(name);
}
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);
}
}
public static void renderText(final String text, final String... headers) {
render(TEXT_TYPE, text, headers);
}
public static void renderHtml(final String html, final String... headers) {
render(HTML_TYPE, html, headers);
}
public static void renderXml(final String xml, final String... headers) {
render(XML_TYPE, xml, headers);
}
public static void renderJson(final String jsonString,
final String... headers) {
render(JSON_TYPE, jsonString, headers);
}
public static void renderJson(HttpServletResponse response, final Object data) {
response.setContentType(JSON_TYPE + ";charset=" + DEFAULT_ENCODING);
try {
mapper.writeValue(response.getWriter(), data);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
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);
}
}
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);
}
}
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();
render(JS_TYPE, result, headers);
}
private static HttpServletResponse initResponse(final String contentType,
final String... 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();
String fullContentType = contentType + ";charset=" + encoding;
response.setContentType(fullContentType);
if (noCache) {
WebUtils.setNoCacheHeader(response);
}
return response;
}
}