需要通过一个相当于代理的类来完成,真正的servlet当做属性初始化进去。(当然,这个代理类是公共的,可以在web.xml配置多个)
我这里举例,做一个servlet,用于全站生成验证码的地方使用,不多说,全部代码都贴出来好了。
CaptchaService
package com.mcp.service.common;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
public interface CaptchaService {
/**
* 生成验证码图片,验证码在session中
*
* @return 验证码图片
*/
public BufferedImage generateCaptchaImg(HttpSession session);
/**
* 验证验证码正确与否,验证码在session中
*
* @param captcha
* 被验证的验证码
* @return
*/
public boolean verifyCaptcha(String captcha, HttpSession session);
}
CaptchaServiceImpl
package com.mcp.service.common.impl;
import com.mcp.cons.CommonCons;
import com.mcp.service.common.CaptchaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
@Service
public class CaptchaServiceImpl implements CaptchaService {
/**
* 验证码字符个数
*/
private int codeCount = 4;
/**
* codeSequence 表示字符允许出现的序列值
*/
private static char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', '3', '4', '5', '6',
'7', '8', '9'};
@Override
public BufferedImage generateCaptchaImg(HttpSession session) {
// FIXME:两个参数的session,都需要判空。
int width = 80;
int height = 30;
BufferedImage image = new BufferedImage(width, height, 1);
Graphics g = image.getGraphics();
Random random = new Random();
int fc = 200;
int bc = 250;
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r1 = fc + random.nextInt(bc - fc);
int g1 = fc + random.nextInt(bc - fc);
int b1 = fc + random.nextInt(bc - fc);
g.setColor(new Color(r1, g1, b1));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Arial", 0, 25));
int r2 = fc + random.nextInt(bc - fc);
int g2 = fc + random.nextInt(bc - fc);
int b2 = fc + random.nextInt(bc - fc);
g.setColor(new Color(r2, g2, b2));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width + 100);
int y = random.nextInt(height + 100);
int xl = random.nextInt(10);
int yl = random.nextInt(12);
g.drawOval(x, y, x + xl, y + yl);
}
StringBuffer sRand = new StringBuffer();
for (int i = 0; i < codeCount; i++) {
// 得到随机产生的验证码数字。
String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
g.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
g.drawString(strRand, 14 * i + 5, 25);
sRand.append(strRand);
}
g.dispose();
session.setAttribute(CommonCons.CaptchaFlag.CAPTCHA_SESSION,
sRand.toString().toUpperCase());
return image;
}
@Override
public boolean verifyCaptcha(String captcha, HttpSession session) {
Object captchaObj = session
.getAttribute(CommonCons.CaptchaFlag.CAPTCHA_SESSION);
String captchaInSession = (null == captchaObj ? "" : captchaObj
.toString());
if (StringUtils.isEmpty(captchaInSession)
|| !captchaInSession.equalsIgnoreCase(captcha)) {
return false;
}
return true;
}
}
上边两个类很简单,就是专门生成验证码图片用的,都是正常的逻辑,spring的xml配置不发了,能正确注入就行,下边是关键
DelegatingServletProxy
package com.mcp.core.servlet;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class DelegatingServletProxy extends HttpServlet {
private static final long serialVersionUID = 1L;
private String targetServletBeanName;
private String targetServletBeanClassName;
private Servlet proxy;
@Override
public void init() throws ServletException {
this.targetServletBeanName = this.getInitParameter("targetServletBeanName");
this.targetServletBeanClassName = this.getInitParameter("targetServletBeanClassName");
if (StringUtils.isEmpty(targetServletBeanClassName) && StringUtils.isEmpty(targetServletBeanName)) {
//两个参数不能都为空
throw new IllegalArgumentException("targetServletBean and targetServletBeanClassName can not both be empty!");
}
this.getServletBean();
this.proxy.init(this.getServletConfig());
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
proxy.service(request,response);
}
private void getServletBean(){
ServletContext servletContext = this.getServletContext();
WebApplicationContext wac = null;
wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
if (StringUtils.isNotEmpty(targetServletBeanName)) {
this.proxy = (Servlet) wac.getBean(targetServletBeanName);
if (StringUtils.isNotEmpty(targetServletBeanClassName) && !StringUtils.equals(this.proxy.getClass().getName(), targetServletBeanClassName)) {
throw new IllegalArgumentException("beanName:"+targetServletBeanName+" and beanClassName:"+targetServletBeanClassName+" not point to the same class");
}
} else {
Class clazz;
try {
clazz = Class.forName(targetServletBeanClassName);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("class name of "+targetServletBeanClassName+" not found");
}
this.proxy = (Servlet) wac.getBean(clazz);
}
}
}
然后就是servlet
VerifyCodeServlet
package com.mcp.core.servlet;
import com.mcp.service.common.CaptchaService;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class VerifyCodeServlet extends HttpServlet {
@Resource
CaptchaService captchaSrv;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
ImageIO.write(captchaSrv.generateCaptchaImg(request.getSession()),
"JPG", response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}
在配置进web.xml就ok了
<!-- 验证码 -->
<servlet>
<servlet-name>verifyCodeServlet</servlet-name>
<servlet-class>com.mcp.core.servlet.DelegatingServletProxy</servlet-class>
<init-param>
<param-name>targetServletBeanClassName</param-name>
<param-value>com.mcp.core.servlet.VerifyCodeServlet</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>verifyCodeServlet</servlet-name>
<url-pattern>/verifyCodeServlet</url-pattern>
</servlet-mapping>
看到了吧,把正在处理的servlet当做一个属性初始化到代理类中,再细看代理类中的getServletBean方法就明了了。
如此访问verifyCodeServlet这个url就能到进到对应的post方法里,那个Service业务类就可以使用了。