登陆网页代码如下:
public class LoginController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("<form action='' method='post'>");
stringBuilder.append("登录名称:<input type='text' name='loginName' value=''><br>");
stringBuilder.append("登录密码:<input type='password' name='loginPwd' value=''><br>");
stringBuilder.append("验证码:<input type='text' name='validCode' value=''><img src='./captche' width='250' height='150'><br>");
stringBuilder.append("<input type='reset' name='reset' value='取消'>");
stringBuilder.append("<input type='submit' name='submit' value='登录'>");
stringBuilder.append("</form>");
showMsg(response, stringBuilder.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String loginName = req.getParameter("loginName");
String loginPwd = req.getParameter("loginPwd");
String validCode = req.getParameter("validCode");
String Code = (String) req.getSession().getAttribute("Code").toString();
//如果输入的登录名称是自己的学号,密码1234,那么输出你好,学号,否则输出账号或密码错误
String msg = "请输入账号密码";
if(loginName.equals("3187102XXX")&& loginPwd.equals("1234")&&Code.equals(validCode)) {
msg = "你好" + loginName;
}
else {
msg = "账号密码或验证码错误";
}
showMsg(resp,msg);
}
具体的方法可以参考小编以前的博文:使用IDEA实现登陆页面https://blog.csdn.net/qq_37630245/article/details/105297515
这里的判断语句将判断账号密码以及验证码是否正确,具体代码如下:
if(loginName.equals("3187102444")&& loginPwd.equals("1234")&&Code.equals(validCode)) {
msg = "你好" + loginName;
}
else {
msg = "账号密码或验证码错误";
}
showMsg(resp,msg);
}
生成验证码的代码如下
首先在全局变量中定义宽度和高度的数值:
public class CaptcheController extends HttpServlet {
private final int width=250;
private final int height=150;
在类SteUtil中添加如下代码:
public class SteUtil {
public static String randString(int count) {
StringBuilder builder = new StringBuilder();
String text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random rnd = new Random();//随机数发生器
//生成4个随机数
for (int i = 0; i < count; i++) {
int pos = rnd.nextInt(text.length());
String s = text.substring(pos, pos + 1);
builder.append(s);
}
return builder.toString();
}
public static boolean isBlank(String str){
if(str == null || "".equals(str)){
return true;
}else{
return false;
}
}
}
使用req将验证码和登陆页面连接在一起:
String text = SteUtil.randString(4);
req.getSession().setAttribute("Code",text);
注意,这里的Code与登陆页面中的Code大小写要相同!!!
验证码具体的生成方法可以参考小编之前的文章:
使用IDEA产生随机验证码
https://blog.csdn.net/qq_37630245/article/details/105459524
运行结果
运行的初始页面:
若账号密码及验证码正确:
若账号密码或验证码不正确: