登录注册案例
页面准备
<form action="LoginServlet" method="post">
user:<input type="text" name="username"><br>
pwd:<input type="text" name="password"><br>
验证码:<input type="text" name="_img">
<img src="/Checkcode" id="_img"><br>
<input type="submit">
form>
<script>
window.onload = function () {
var _img = document.getElementById("_img");
_img.onclick = function () {
var date = new Date();
_img.src ="/Checkcode?"+date.getTime();
};
}
script>
数据库
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(25) DEFAULT NULL,
`password` varchar(25) DEFAULT NULL,
`nickname` varchar(25) DEFAULT NULL,
`createdtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updatedtime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
druid.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///test
username=root
password=root
# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=3000
实现类
public class User {
private int id;
private String username;
private String password;
private String nickname;
}
验证码
@WebServlet(urlPatterns = "/Checkcode")
public class Checkcode extends HttpServlet {
private static final int WIDTH = 100;
private static final int HEIGHT = 30;
private static final int LENGTH = 4;
public static final int LINECOUNT=20;
private static final String str="0123456789"+
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"+
"abcdefghijklmnopqrstuvwxyz";
private static Random random=new Random();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("image/jpeg");
resp.setHeader("pragma", "no-cache");
resp.setHeader("cache-control", "no-cache");
resp.setHeader("expires", "0");
BufferedImage image=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_3BYTE_BGR);
Graphics g=image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
String code=drawChar(g);
System.out.println("验证码:"+code);
for (int i=0;i<LINECOUNT;i++){
drawLine(g);
}
req.getSession().setAttribute("code",code);
g.dispose();
ImageIO.write(image, "JPEG", resp.getOutputStream());
}
public Color getColor(){
return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
}
public Font getFont() {
return new Font("Fixedsys", Font.CENTER_BASELINE, 20);
}
public String drawChar(Graphics g){
String code="";
g.setFont(getFont());
for (int i=0;i<LENGTH;i++){
char c=str.charAt(random.nextInt(str.length()));
g.setColor(getColor());
g.drawString(c+"", 20* i + 10, 20);
code=code+c;
}
return code;
}
public void drawLine(Graphics g) {
int x = random.nextInt(WIDTH);
int y = random.nextInt(HEIGHT);
int xl = random.nextInt(13);
int yl = random.nextInt(15);
g.setColor(getColor());
g.drawLine(x, y, x + xl, y + yl);
}
}
工具类
public class JDBCUtils {
private static DataSource ds ;
static{
try {
Properties pro = new Properties();
pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static DataSource getDataSource(){
return ds;
}
}
web层
@WebServlet(urlPatterns = "/ServletLogin")
public class ServletLogin extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
Map<String, String[]> map = request.getParameterMap();
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
UserService service = new UserServiceImpl();
User u = service.loginUser(user);
if(u != null){
System.out.println("登录成功");
request.getRequestDispatcher("/success.html").forward(request,response);
}else {
System.out.println("登录失败");
request.getRequestDispatcher("/login.html").forward(request,response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
@WebServlet(urlPatterns = "/registUserServlet")
public class registUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String _img = request.getParameter("_img");
HttpSession session = request.getSession();
String code = (String) session.getAttribute("code");
session.removeAttribute("code");
if(!_img.equalsIgnoreCase(code)){
request.setAttribute("msg","验证码不正确!");
request.getRequestDispatcher("/regist.jsp").forward(request,response);
return;
}
Map<String, String[]> map = request.getParameterMap();
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
UserService service = new UserServiceImpl();
Boolean blg = service.registUser(user);
if(blg){
System.out.println("注册成功");
request.getRequestDispatcher("/login.html").forward(request,response);
}else{
System.out.println("用户名已存在!!");
request.getRequestDispatcher("/regist.html").forward(request,response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
service层
public interface UserService {
Boolean registUser(User user);
User loginUser(User user);
}
public class UserServiceImpl implements UserService {
private UserDao dao = new UserDaoImpl();
@Override
public Boolean registUser(User user) {
User u = dao.findByUserName(user.getUsername());
if(u == null){
dao.registUser(user);
return true;
}
return false;
}
@Override
public User loginUser(User user) {
return this.dao.loginUser(user);
}
}
dao层
public interface UserDao {
User findByUserName(String username);
void registUser(User user);
User loginUser(User user);
}
public class UserDaoImpl implements UserDao {
private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
@Override
public User findByUserName(String username) {
try {
String sql ="select * from user where username = ?";
return this.jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), username);
} catch (Exception e) {
return null;
}
}
@Override
public void registUser(User user) {
String sql ="INSERT INTO `customer`.`user`(`id`, `username`, `password`, `nickname`, `createdtime`, `updatedtime`) VALUES (?, ?, ?, ?, ?, ?)";
this.jdbcTemplate.update(sql,null,user.getUsername(),user.getPassword(),user.getNickname(),new Date(),new Date());
}
@Override
public User loginUser(User user) {
try {
String sql = "select * from user where username =? and password = ?";
return this.jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class),user.getUsername(),user.getPassword());
} catch (Exception e) {
return null;
}
}
}
测试