用MVC开发模式实现servlet简单的登录功能(带图片验证码)

首先需要链接数据库的jar包 mysql-connector-java-5.0.4-bin.jar


用到的工具类

验证码图片的工具类
package com.yinhe.util;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
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;

public class CodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String codes="abcdefghijklmnopqrstuvwxyz";	
		BufferedImage img=new BufferedImage(80,30,BufferedImage.TYPE_3BYTE_BGR);
		Graphics g=img.getGraphics();
		//填充图片
		g.setColor(new Color(255,255,255));
		g.fillRect(0, 0, 80, 30);
		//画入五个随机数
		Random rm=new Random();
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<5;i++){
			int index=rm.nextInt(codes.length());
			char code=codes.charAt(index);
			g.setColor(new Color(rm.nextInt(256),rm.nextInt(256),rm.nextInt(256)));
			g.setFont(new Font("宋体", Font.BOLD, 25));
			g.drawString(code+"", 2+15*i, 22);
			sb.append(code);
		}
		
		//画干扰线
		for(int i=0;i<10;i++){
			g.setColor(new Color(rm.nextInt(256),rm.nextInt(256),rm.nextInt(256)));
			g.drawLine(rm.nextInt(100), rm.nextInt(50), rm.nextInt(100), rm.nextInt(50));
		}
		
		//将验证码图片回写给浏览器
		response.setContentType("image/jpeg;charset=utf-8");
		OutputStream out=response.getOutputStream();
		ImageIO.write(img, "jpeg", out);
		
		//将随机字符串保存在session中
		request.getSession().setAttribute("code", sb.toString());
	}

}
链接数据库的工具类

package com.yinhe.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DbOperation {
    protected Connection conn;
    protected PreparedStatement ps;
    protected ResultSet rs;
    private final String uname="root";
    private final String psw="root";
    //获取数据库链接
    public void getConn(){        
        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取链接
            conn = DriverManager.getConnection(
                    "jdbc:mysql:///test",uname,psw);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }    
    }
    //关闭
    public void closeAll(){
            try {
                if(conn!=null){
                    conn.close();
                }
                if(ps!=null){
                    ps.close();
                }
                if(rs!=null){
                    rs.close();
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
    
    //更新  Object... 会把传过来的任意个object类型的变量封装成一个数组
    public void extUpdate(String sql, Object... obj){
        try {
            ps=conn.prepareStatement(sql);
            for(int i=0;i
封装类User

package com.yinhe.vo;

public class User {
	private int uid;
	private String username;
	private String psw;
	public int getUid() {
		return uid;
	}
	public void setUid(int uid) {
		this.uid = uid;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPsw() {
		return psw;
	}
	public void setPsw(String psw) {
		this.psw = psw;
	}
	public User(String username, String psw) {
		super();
		this.username = username;
		this.psw = psw;
	}
	
}



前台需要的登录页面


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>



	
username:
password:
yanzhengma: 换一张 ${message}

controller层

package com.yinhe.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yinhe.service.LoginService;
import com.yinhe.service.serviceImpl.LoginServiceImpl;
import com.yinhe.vo.User;

public class LoginServlet extends HttpServlet {
	private LoginService ls = new LoginServiceImpl();
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//获取前台参数
		String username=req.getParameter("username");
		String psw = req.getParameter("psw");
		String yzm = req.getParameter("yzm");
		//
		String yzmb = (String) req.getSession().getAttribute("code");
		if (yzm.equals(yzmb)){
			User user = new User(username,psw);
			String count = ls.doLogin(user);
			if (count.equals("0")){
				req.setAttribute("message", "账户或密码错误");
				req.getRequestDispatcher("/login.jsp").forward(req, resp);
			}
			else if (count.equals("1")){
				req.getSession().setAttribute("username", user.getUsername());
				req.getRequestDispatcher("/main.jsp").forward(req, resp);
			}
		}
		else{
			req.setAttribute("message", "验证码错误");
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
		}
	}
}
Dao层接口
package com.yinhe.dao;

import com.yinhe.vo.User;

public interface LoginDao {
    public String doLogin(User user);
}

Dao代码

package com.yinhe.dao.daoImpl;

import java.sql.SQLException;

import com.yinhe.dao.LoginDao;
import com.yinhe.util.DbOperation;
import com.yinhe.vo.User;


public class LoginDaoImpl extends DbOperation implements LoginDao {

	@Override
	public String doLogin(User user)  {
		getConn();
		String sql = "select count(*) from user where username=? and psw=?";
		extQuery(sql, user.getUsername(),user.getPsw());
		int count = 0;
		try {
			if(rs.next()){
				count = rs.getInt(1);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		closeAll();
		return count + "";
	}

}
Service层接口

package com.yinhe.service;

import com.yinhe.vo.User;

public interface LoginService {
    public String doLogin(User user);
}


Service层代码



package com.yinhe.service.serviceImpl;

import com.yinhe.dao.LoginDao;
import com.yinhe.dao.daoImpl.LoginDaoImpl;
import com.yinhe.service.LoginService;
import com.yinhe.vo.User;

public class LoginServiceImpl implements LoginService {
	private LoginDao ld = new LoginDaoImpl(); 
	@Override
	public String doLogin(User user) {
		return ld.doLogin(user);
	}
	
}



你可能感兴趣的:(servlet)