首先你要写一个验证码的Controller,这里我给你粘一个:
using Systemusing System.Collections.Generic
using System.Drawing
using System.Drawing.Imaging
using System.IO
using System.Linq
using System.Web
using System.Web.Mvc
namespace Demo.Controllers
{
public class ValidateController : Controller
{
public FileResult ConfirmCode()
{
//生成4位随机数,并将其转为string型,传入session,4位数字由随机数从1000-9999中提取。
string ConfirmCode = string.Empty
Random rand = new Random()
ConfirmCode = rand.Next(1000, 9999).ToString()
Session["QuickChannelConfirmCode"] = ConfirmCode
Random rand1 = new Random()
Random rand2 = new Random()
int red = rand1.Next(50)
int green = rand2.Next(100)
int blue1 = (red + green > 400) ? 0 : 400 - red - green
int blue2 = (blue1 > 255) ? 255 : blue1
Color col = Color.FromArgb(red, green, blue2)
//int imageWidth = ConfirmCode.Length * 13
Bitmap bmp = new Bitmap(135, 44)
Graphics g = Graphics.FromImage(bmp)
g.Clear(Color.LightGray)
g.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, 134, 43)
Font font = new Font("Harrington", 30)
Brush brush = new SolidBrush(col)//col 为上文随机出的颜色
Point po = new Point(15, 0)
g.DrawString(ConfirmCode, font, brush, po)
Response.ContentType = "image/jpeg"
MemoryStream ms = new MemoryStream()
bmp.Save(ms, ImageFormat.Jpeg)
ms.Seek(0, SeekOrigin.Begin)
return new FileStreamResult(ms, "image/jpeg")
}
public ActionResult CheckCode(string id)
{
//string quickChannalConfirmCode = Request.QueryString["id"].ToString()
string quickChannalConfirmCode = id.ToUpper()
if (Session["QuickChannelConfirmCode"] == null || "".Equals(Session["QuickChannelConfirmCode"].ToString()))
{
return Json(false, JsonRequestBehavior.AllowGet)
}
string yanzheng = Session["QuickChannelConfirmCode"].ToString()
Session.Remove("QuickChannelConfirmCode")
if (quickChannalConfirmCode == yanzheng)
{
return Json(true, JsonRequestBehavior.AllowGet)
}
else
{
return Json(false, JsonRequestBehavior.AllowGet)
}
}
}
}
在页面上这样调用:
<img id="VerificationCodeImg" src="/Validate/ConfirmCode2" alt="验证码" />然后还要在页面加上验证:
<script type="text/javascript">function RefreshConfirmCode() {
var rad_num = parseInt(1000*Math.random())
$("#VerificationCodeImg").attr("src","/Validate/ConfirmCode/"+rad_num)
$("#YanZhengMa").val("")
}
$(function () {
$("#VerificationCodeImg").click(RefreshConfirmCode)
$("#LoginButton").click(function(event) {
var thisForm = $("form").first()
if (thisForm.valid()) {
var thisVerificationCode = $("#YanZhengMa").val()
if (thisVerificationCode) {
$.getJSON('/Validate/CheckCode', {id: thisVerificationCode}, function(json, textStatus) {
if (!json) {
RefreshConfirmCode()
thisForm.valid()
}
else {
thisForm.submit()
}
})
}
}
return false
})
})
</script>
在SpringMVC中提供了一个Validator接口,我们可以通过该接口来定义我们自己对实体对象的验证。接下来看一个示例。假设我们现在有一个需要进行验证的实体类User,其代码如下所示:
Java代码
public class User {
private String username
private String password
public String getUsername() {
return username
}
哥们这样的问题连一分也不给啊?给你控制层的代码,自己往jsp里传值吧。import java.awt.BasicStroke
import java.awt.Color
import java.awt.Font
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.geom.AffineTransform
import java.awt.image.BufferedImage
import java.io.IOException
import java.util.Random
import javax.imageio.ImageIO
import javax.servlet.ServletException
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpSession
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
@Controller
@RequestMapping("/checkCodeAction/")
public class CheckCode extends HttpServlet {
public CheckCode() {
super()
}
public void destroy() {
super.destroy()
}
public void init() throws ServletException {
super.init()
}
public Color getRandColor(int s, int e) {
Random random = new Random()
if (s >255) s = 255
if (e >255) e = 255
int r = s + random.nextInt(e - s)
int g = s + random.nextInt(e - s)
int b = s + random.nextInt(e - s)
return new Color(r, g, b)
}
@RequestMapping("service.do")
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//禁止缓存
response.setHeader("Pragma", "No-cache")
response.setHeader("Cache-Control", "No-cache")
response.setDateHeader("Expires", 0)
// 指定生成的响应是图片
response.setContentType("image/jpeg")
int width = 200
int height = 60
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB) //创建BufferedImage类的对象
Graphics g = image.getGraphics()//创建Graphics类的对象
Graphics2D g2d=(Graphics2D)g //通过Graphics类的对象创建一个Graphics2D类的对象
Random random = new Random() //实例化一个Random对象
Font mFont = new Font("华文宋体", Font.BOLD, 30) //通过Font构造字体
g.setColor(getRandColor(200, 250))//改变图形的当前颜色为随机生成的颜色
g.fillRect(0, 0, width , height)//绘制一个填色矩形
//画一条折线
BasicStroke bs=new BasicStroke(2f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL)//创建一个供画笔选择线条粗细的对象
g2d.setStroke(bs)//改变线条的粗细
g.setColor(Color.DARK_GRAY) //设置当前颜色为预定义颜色中的深灰色
int[] xPoints=new int[3]
int[] yPoints=new int[3]
for(int j=0j<3j++){
xPoints[j]=random.nextInt(width - 1)
yPoints[j]=random.nextInt(height - 1)
}
g.drawPolyline(xPoints, yPoints,3)
//生成并输出随机的验证文字
g.setFont(mFont)
String sRand=""
int itmp=0
for(int i=0i<4i++){
if(random.nextInt(2)==1){
itmp=random.nextInt(26)+65//生成A~Z的字母
}else{
itmp=random.nextInt(10)+48//生成0~9的数字
}
char ctmp=(char)itmp
sRand+=String.valueOf(ctmp)
Color color=new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110))
g.setColor(color)
/****随机缩放文字并将文字旋转指定角度**/
//将文字旋转指定角度
Graphics2D g2d_word=(Graphics2D)g
AffineTransform trans=new AffineTransform()
trans.rotate(random.nextInt(45)*3.14/180,15*i+10,7)
//缩放文字
float scaleSize=random.nextFloat()+0.8f
if(scaleSize>1.1f) scaleSize=1f
trans.scale(scaleSize, scaleSize)
g2d_word.setTransform(trans)
/************************/
g.drawString(String.valueOf(ctmp),30*i+40,16)
}
//将生成的验证码保存到Session中
HttpSession session=request.getSession(true)
session.setAttribute("randCheckCode",sRand)
g.dispose()
ImageIO.write(image,"JPEG",response.getOutputStream())
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)