版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Coder_Boy_/article/details/82747955
项目名称:中国电信运营支持系统-网络版(十)
验证码
登录验证码
案例演示:
工程案例目录结构
DBUtil.java
package util;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
/**
* 该类用来管理连接
* 数据库连接信息,保存在属性文件中
* 使用连接池获取连接
* @author Cher_du
*
*/
public class DBUtil {
private static BasicDataSource ds;
static{
//加载属性文件数据
Properties prop = new Properties();
try {
prop.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
String driverclass = prop.getProperty("jdbc.driverclass");
String url=prop.getProperty("jdbc.url");
String user = prop.getProperty("jdbc.user");
String password = prop.getProperty("jdbc.password");
String strMaxActive =prop.getProperty("dbcp.maxActive");
String strInitSize =prop.getProperty("dbcp.initSize");
//实例化,并初始化连接池
ds = new BasicDataSource();
ds.setDriverClassName(driverclass);
ds.setUrl(url);
ds.setUsername(user);
ds.setPassword(password);
ds.setMaxActive(Integer.parseInt(strMaxActive));
ds.setInitialSize(Integer.parseInt(strInitSize));
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("读取属性文件错误",e);
}
}
//2、创建连接
public static Connection getConnection() throws SQLException{
return ds.getConnection();
}
//3、归还连接
public static void close(Connection conn){
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("归还连接错误",e);
}
}
}
//测试
public static void main(String[] args) throws SQLException {
Connection conn = getConnection();
System.out.println(conn.getClass().getName());
close(conn);
}
}
login.jsp
<%@page pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>案例-NetCTOSS</title>
<link type="text/css" rel="stylesheet" media="all" href="styles/global.css"/>
<link type="text/css" rel="stylesheet" media="all" href="styles/global_color.css"/>
</head>
<body class="index">
<div class="login_box">
<form action="login.do" method="post">
<table>
<tr>
<td class="login_info">账号:</td>
<td colspan="2"><input name="adminCode" value="${param.adminCode }" type="text" class="width150" /></td>
<td class="login_error_info"><span class="required">30长度的字母、数字和下划线</span></td>
</tr>
<tr>
<td class="login_info">密码:</td>
<td colspan="2"><input name="password" value="${param.password }" type="password" class="width150"/></td>
<td><span class="required">30长度的字母、数字和下划线</span></td>
</tr>
<tr>
<td class="login_info">验证码:</td>
<td class="width70"><input name="code" type="text" class="width70"/></td>
<td><img src="createImg.do" onclick="this.src='createImg.do?x='+Math.random();" alt="验证码" title="点击更换"/></td>
<td><span class="required"></span></td>
</tr>
<tr>
<td></td>
<td class="login_button" colspan="2">
<a href="javascript:document.forms[0].submit();"><img src="images/login_btn.png" alt="" /></a>
</td>
<td><span class="required">${error }</span></td>
</tr>
</table>
</form>
</div>
</body>
</html>
MainServlet.java
package web;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dao.AdminDao;
import dao.CostDao;
import entity.Admin;
import entity.Cost;
import util.ImageUtil;
public class MainServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
String path = req.getServletPath();
if("/findCost.do".equals(path)){
//查询资费
System.out.println(path);
findCost(req,res);
}else if("/toAddCost.do".equals(path)){
//打开增加资费页
toAddCost(req,res);
}else if("/addCost.do".equals(path)){
//增加保存资费
addCost(req,res);
}else if("/toUpdateCost.do".equals(path)){
//打开修改资费页
toUpdateCost(req,res);
}else if("/updateCost.do".equals(path)){
//修改资费
updateCost(req,res);
}else if("/deleteCost.do".equals(path)){
//删除资费
deleteCost(req,res);
}else if("/toLogin.do".equals(path)){
//打开登录页
toLogin(req,res);
}else if("/toIndex.do".equals(path)){
//打开主页
toIndex(req,res);
}else if("/login.do".equals(path)){
//登录验证
login(req,res);
}else if("/logout.do".equals(path)){
//退出
logout(req,res);
}else if("/createImg.do".equals(path)){
//生成验证码
createImg(req,res);
}else{
//错误的路径
throw new RuntimeException("没有这个页面");
}
}
protected void createImg(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
System.out.println("createImg.do");
//生成随机的验证码和图片
Object[] objs = ImageUtil.createImage();
//将验证码存入session
HttpSession session = req.getSession();
session.setAttribute("imgCode", objs[0]);
//将图片输出给浏览器
BufferedImage img = (BufferedImage)objs[1];
//格式见/tomcat/conf/web.xml
res.setContentType("image/png");
//该输出流的目标就是浏览器
OutputStream os= res.getOutputStream();
ImageIO.write(img, "png", os);
os.close();
}
protected void logout(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
//注销session
req.getSession().invalidate();
//重定向到登录
res.sendRedirect(req.getContextPath()+"/toLogin.do");
}
protected void login(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
//接收表单数据
String adminCode = req.getParameter("adminCode");
String password = req.getParameter("password");
System.out.println("login=="+adminCode+":"+password);
//校验
String code = req.getParameter("code");
HttpSession session = req.getSession();
String imgCode = (String)session.getAttribute("imgCode");System.out.println(imgCode);
if(code ==null || code.equals("")|| !code.equalsIgnoreCase(imgCode)){
req.setAttribute("error", "验证码错误");
req.getRequestDispatcher("WEB-INF/main/login.jsp").forward(req, res);
return;
}
AdminDao dao = new AdminDao();
Admin admin = dao.findByCode(adminCode);
if(admin == null){
//账号不存在
req.setAttribute("error", "账号不存在");
req.getRequestDispatcher("WEB-INF/main/login.jsp").forward(req, res);
}else if(!admin.getPassword().equals(password)){
//密码错误
req.setAttribute("error", "密码错误");
req.getRequestDispatcher("WEB-INF/main/login.jsp").forward(req, res);
}else{
//校验通过
//将账号存入cookie
Cookie c = new Cookie("adminCode",adminCode);
res.addCookie(c);
//登录成功后,将账号存入session,
//以记录用户的登录状态,将来好做检查
session.setAttribute("adminCode", adminCode);
//当前:/netctoss/login.do
//目标:/netctoss/toIndex.do
res.sendRedirect("toIndex.do");
}
}
protected void toIndex(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
System.out.println("toIndex......");
req.getRequestDispatcher("WEB-INF/main/index.jsp").forward(req, res);
}
protected void toLogin(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
//当前:/netctoss/toLogin.do
//目标:/netctoss/WEB-INF/main/login.jsp
System.out.println("toLogin.do");
req.getRequestDispatcher("WEB-INF/main/login.jsp").forward(req, res);
}
protected void deleteCost(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String costId = req.getParameter("costId");
CostDao dao = new CostDao();
dao.delete(new Integer(costId));
System.out.println("deleteCost......");
//3.重定向到查询
//当前:/netctoss/deleteCost.do
//目标:/netctoss/findCost.do
res.sendRedirect("findCost.do");
}
protected void updateCost(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
//1.接收表单数据
String costId = req.getParameter("costId");
String name = req.getParameter("name");
String costType = req.getParameter("costType");
String descr = req.getParameter("descr");
String baseDuration = req.getParameter("baseDuration");
String baseCost = req.getParameter("baseCost");
String unitCost = req.getParameter("unitCost");
//2.保存这些数据
Cost c = new Cost();
c.setCostId(new Integer(costId));
c.setName(name);
c.setCostType(costType);
c.setDescr(descr);
if(baseDuration !=null && !baseDuration.equals("")){//
c.setBaseDuration(new Integer(baseDuration));
}
if(baseCost !=null && !baseCost.equals("")){
c.setBaseCost(new Double(baseCost));
}
if(unitCost !=null && !unitCost.equals("")){
c.setUnitCost(new Double(unitCost));
}
CostDao dao = new CostDao();
System.out.println(c);
dao.update(c);
//3.重定向到查询
//当前:/netctoss/addCost.do
//目标:/netctoss/findCost.do
res.sendRedirect("findCost.do");
}
protected void toUpdateCost(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
System.out.println("toUpdateCost.......");
//接收参数
String id = req.getParameter("id");
//查询要修改的资费
CostDao dao = new CostDao();
Cost cost = dao.findById(new Integer(id));
//转发到修改页
req.setAttribute("cost", cost);
req.getRequestDispatcher("WEB-INF/cost/update.jsp").forward(req, res);
}
protected void addCost(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
//1.接收表单数据
String name = req.getParameter("name");
String costType = req.getParameter("costType");
String descr = req.getParameter("descr");
String baseDuration = req.getParameter("baseDuration");
String baseCost = req.getParameter("baseCost");
String unitCost = req.getParameter("unitCost");
//2.保存这些数据
Cost c = new Cost();
c.setName(name);
c.setCostType(costType);
c.setDescr(descr);
if(baseDuration !=null && !baseDuration.equals("")){//
c.setBaseDuration(new Integer(baseDuration));
}
if(baseCost !=null && !baseCost.equals("")){
c.setBaseCost(new Double(baseCost));
}
if(unitCost !=null && !unitCost.equals("")){
c.setUnitCost(new Double(unitCost));
}
CostDao dao = new CostDao();
dao.save(c);
//3.重定向到查询
//当前:/netctoss/addCost.do
//目标:/netctoss/findCost.do
res.sendRedirect("findCost.do");
}
protected void toAddCost(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
//当前:/netctoss/toAddCost.do
//目标:/netctoss/WEB-INF/cost/add.jsp
req.getRequestDispatcher("WEB-INF/cost/add.jsp").forward(req, res);
}
protected void findCost(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
//v1
// //查询资费
// CostDao dao = new CostDao();
// List<Cost> list = dao.findAll();
// //转发到查询页面
// req.setAttribute("costs", list);
// //当前:/netctoss/findCost.dao
// //目标:/netctoss/WEB-INF/cost/find.jsp
// System.out.println("into--findCost");
// req.getRequestDispatcher("WEB-INF/cost/find.jsp").forward(req, res);
//v2 分页
//获取请求参数
String page = req.getParameter("page");
if(page == null || page.equals("")){
page = "1";
}
System.out.println(page);
//获取常量
String size = this.getServletContext().getInitParameter("size");
//查询资费
CostDao dao = new CostDao();
List<Cost> list= dao.findByPage(new Integer(page), new Integer(size));
//查询总行数,计算出总页数
int rows = dao.findRows();
int total =rows/(new Integer(size));
if(rows%new Integer(size) != 0){
total++;
}
//转发到查询页面
req.setAttribute("costs", list);
req.setAttribute("total", total);
req.setAttribute("page", page);
//当前:/netctoss/findCost.do
//目标:/netctoss/WEB-INF/cost/find.jsp
req.getRequestDispatcher("WEB-INF/cost/find.jsp").forward(req, res);
}
}
将netctoss工程部署到Tomcat上,运行Tomcat启动案例工程,
浏览器录入http://localhost:8088/netctoss/toLogin.do【错误的请求路径】即可:如果没有错误,最终页面显示效果应如下图:
点击验证码图片 更换验证码
若录入验证码错误则 提示验证码错误
验证码正确 且账号与密码正确 才能登录到主页