java springmvc实现验证码功能

2025-05-27 0 27

本文实例为大家分享了springmvc实现验证码功能展示的具体代码,供大家参考,具体内容如下

先看效果图:

java springmvc实现验证码功能

思路:

首先验证码是一张图片,是一张有着随机字母、数字、图案等组成的图片,所以这图片肯定不是固定不变的,肯定是由后端随机制造出来的,前端用img的src去不断访问这个制造的方法。

第一步:前端页面编写

登录使用的是ajax方法,所以使用的是调用点击事件进行,验证码的图片放在a标签中是为了方便点击变换验证码。显示图片用的是img的src属性,因为使用的是spingmvc所以调用后台方法使用action的方式。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
<form>

<div id="login_tip">

管理员登录

</div>

<div><input type="text" id="user_code" name="user_code" class="username" placeholder="请输入账号"></div>

<div><input type="password" id="user_account" name="user_account" class="pwd" placeholder="请输入密码"></div>

<div id="btn_area">

<input type="text" id="verificationcode" name="verificationcode" placeholder="请输入验证码" class="verify">

<a href="javascript:void(0);" rel="external nofollow" onclick="verificationcode()">

<img id="randcodeimage" alt="验证码" src="verificationcode/generate.action" width="100" height="40"/>

</a>

</div>

<div style="float:left;">

<input type="button" name="button" id="sub_btn" onclick="login()" value="登录"/>

</div>

<div id="verification_code"><b></b></div>

</form>

第二步:编写js代码

因为登录采用的是ajxa,所以后台登录会验证一些数据,不正确的会返回数据到登录页面。这里说明一下,在调用生成验证码的方法后面为什么要加一个随机数,这里的随机数以及这个随机数的参数名称可以随意写,后端不做任何操作的,这里是防止浏览器对一个相同方法进行调用时取缓存的方法,而点击图片或验证码输入错误不会自动刷新而改变图片的问题做处理。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37
<script type="text/javascript">

function login(){

//这是使用ajax的方式提交

$.ajax({

type:'post',

url:'uase/query.action',

//data:$('#logininputform').serialize(),

data:{

'user_code' : $("#user_code").val(),

'user_account' :$("#user_account").val(),

'verificationcode':$("#verificationcode").val(),

},

datatype:'json',

success:function(obj){

var rad = math.floor(math.random() * math.pow(10, 8));

if(obj && obj.success=='true'){

window.location.href='uase/login.action';

}else{

document.getelementbyid("verification_code"). innerhtml =obj.msg;

//uuuy是随便写的一个参数名称,后端不会做处理,作用是避免浏览器读取缓存的链接

$("#randcodeimage").attr("src", "verificationcode/generate.action?uuuy="+rad);

$("#verificationcode").val("").focus(); // 清空并获得焦点

}

}

});

}

/**

*验证码刷新

*/

function verificationcode(){

var rad = math.floor(math.random() * math.pow(10, 8));

//uuuy是随便写的一个参数名称,后端不会做处理,作用是避免浏览器读取缓存的链接

$("#randcodeimage").attr("src", "verificationcode/generate.action?uuuy="+rad);

}

</script>

第三步:编写后台controller控制类

主方法为verificationcode,里面会用到一些随机数生产的方法以及一些辅助类,全用用上就可以了,因为我这里用到了可以更改类型的验证码,所以用到了一个自己编写的公共的工具类。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206
@requestmapping("/verificationcode")

public class verificationcodecontroller extends httpservlet{

private static final long serialversionuid = 1l;

/**

* 这里用作存入session的名称

*/

private static final string session_key_of_rand_code = "randcode"; // todo 要统一常量

/**

*

*/

private static final int count = 200;

/**

* 定义图形大小(宽)

*/

private static final int width = 105;

/**

* 定义图形大小(高)

*/

private static final int height = 35;

/**

* 干扰线的长度=1.414*linewidth

*/

private static final int linewidth = 1;

@requestmapping(value = "/generate", method = { requestmethod.post,

requestmethod.get })

public void verificationcode( 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/png");

// 在内存中创建图象

final bufferedimage image = new bufferedimage(width, height, bufferedimage.type_int_rgb);

// 获取图形上下文

final graphics2d graphics = (graphics2d) image.getgraphics();

// 设定背景颜色

graphics.setcolor(color.white); // ---1.color.white为白色

graphics.fillrect(0, 0, width, height);//填充衍射

// 设定边框颜色

//graphics.setcolor(getrandcolor(100, 200)); // ---2.这是以数字型来设置颜色,颜色模式是指使用三种基色:红、绿、蓝,通过三种颜色的调整得出其它各种颜色,这三种基色的值范围为0~255

graphics.drawrect(0, 0, width - 1, height - 1);

final random random = new random();

// 随机产生干扰线,使图象中的认证码不易被其它程序探测到

for (int i = 0; i < count; i++) {

graphics.setcolor(getrandcolor(150, 200)); // ---3.

final int x = random.nextint(width - linewidth - 1) + 1; // 保证画在边框之内

final int y = random.nextint(height - linewidth - 1) + 1;

final int xl = random.nextint(linewidth);

final int yl = random.nextint(linewidth);

graphics.drawline(x, y, x + xl, y + yl);

}

// 取随机产生的认证码(4位数字)

final string resultcode = exctractrandcode();

for (int i = 0; i < resultcode.length(); i++) {

// 将认证码显示到图象中,调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成

// graphics.setcolor(new color(20 + random.nextint(130), 20 + random

// .nextint(130), 20 + random.nextint(130)));

// 设置字体颜色

graphics.setcolor(color.black);

// 设置字体样式

//graphics.setfont(new font("arial black", font.italic, 18));

graphics.setfont(new font("times new roman", font.bold, 24));

// 设置字符,字符间距,上边距

system.out.print(resultcode.charat(i));

graphics.drawstring(string.valueof(resultcode.charat(i)), (23 * i) + 8, 26);

}

system.out.println("直接输出:"+resultcode);

// 将认证码存入session

request.getsession().setattribute(session_key_of_rand_code, resultcode);

// 图象生效

graphics.dispose();

// 输出图象到页面

imageio.write(image, "jpeg", response.getoutputstream());

}

/**

* @return 随机码

*/

private string exctractrandcode() {

final string randcodetype = resourceutil.getrandcodetype();

int randcodelength = integer.parseint(resourceutil.getrandcodelength());

if (randcodetype == null) {

return randcodeimageenum.number_char.generatestr(randcodelength);

} else {

switch (randcodetype.charat(0)) {

case '1':

return randcodeimageenum.number_char.generatestr(randcodelength);

case '2':

return randcodeimageenum.lower_char.generatestr(randcodelength);

case '3':

return randcodeimageenum.upper_char.generatestr(randcodelength);

case '4':

return randcodeimageenum.letter_char.generatestr(randcodelength);

case '5':

return randcodeimageenum.all_char.generatestr(randcodelength);

default:

return randcodeimageenum.number_char.generatestr(randcodelength);

}

}

}

/**

* 描述:根据给定的数字生成不同的颜色

* @param 这是以数字型来设置颜色,颜色模式是指使用三种基色:红、绿、蓝,通过三种颜色的调整得出其它各种颜色,这三种基色的值范围为0~255

* @param 这是以数字型来设置颜色,颜色模式是指使用三种基色:红、绿、蓝,通过三种颜色的调整得出其它各种颜色,这三种基色的值范围为0~255

* @return 描述:返回颜色

*/

private color getrandcolor(int fc, int bc) { // 取得给定范围随机颜色

final random random = new random();

if (fc > 255) {

fc = 255;

}

if (bc > 255) {

bc = 255;

}

final int r = fc + random.nextint(bc - fc);

final int g = fc + random.nextint(bc - fc);

final int b = fc + random.nextint(bc - fc);

return new color(r, g, b);

}

/**

* 验证码辅助类

*/

enum randcodeimageenum {

/**

* 混合字符串

*/

all_char("0123456789abcdefghijkmnpqrstuvwxyzabcdefghijklmnopqrstuvwxyz"), // 去除小写的l和o这个两个不容易区分的字符;

/**

* 字符

*/

letter_char("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"),

/**

* 小写字母

*/

lower_char("abcdefghijklmnopqrstuvwxyz"),

/**

* 数字

*/

number_char("0123456789"),

/**

* 大写字符

*/

upper_char("abcdefghijklmnopqrstuvwxyz");

/**

* 待生成的字符串

*/

private string charstr;

/**

* @param charstr

*/

private randcodeimageenum(final string charstr) {

this.charstr = charstr;

}

/**

* 生产随机验证码

*

* @param codelength

* 验证码的长度

* @return 验证码

*/

public string generatestr(final int codelength) {

final stringbuffer sb = new stringbuffer();

final random random = new random();

final string soursestr = getcharstr();

for (int i = 0; i < codelength; i++) {

sb.append(soursestr.charat(random.nextint(soursestr.length())));

}

return sb.tostring();

}

/**

* @return the {@link #charstr}

*/

public string getcharstr() {

return charstr;

}

}

}

第四步:编写公用的工具类

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26
/**

* 项目参数工具类

*

*/

public class resourceutil {

private static final resourcebundle bundle = java.util.resourcebundle.getbundle("sysconfig");

/**

* 获取随机码的长度

*

* @return 随机码的长度

*/

public static string getrandcodelength() {

return bundle.getstring("randcodelength");

}

/**

* 获取随机码的类型

*

* @return 随机码的类型

*/

public static string getrandcodetype() {

return bundle.getstring("randcodetype");

}

}

第五步:配置sysconfig.properties

?

1

2
randcodelength=4

randcodetype=5

第六步:到这里就大功告成了,可以试试效果了

原文链接:http://blog.csdn.net/qq_35572020/article/details/53033203

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java springmvc实现验证码功能 https://www.kuaiidc.com/77124.html

相关文章

发表评论
暂无评论