旅游网站系统----登录功能

 上一篇》》注册---邮件激活_无尽的沉默的博客-CSDN博客

一.登录功能原理分析

旅游网站系统----登录功能_第1张图片

二.代码实现

2.1前端代码

script中的ajax异步提交(绑定登录按钮事件)

旅游网站系统----登录功能_第2张图片

完整的的login.html





    
    
    
    黑马旅游网-登录  
    
    
    
    
    
      
    
	
	
	
	





    
    

2.2后端代码

2.2.1编写Web层的Loginservlet

package cn.itcast.travel.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.itcast.travel.dao.UserDao;
import cn.itcast.travel.dao.impl.UserDaoImpl;
import cn.itcast.travel.domain.ResultInfo;
import cn.itcast.travel.domain.User;
import cn.itcast.travel.service.UserService;
import cn.itcast.travel.service.impl.UserServiceImpl;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取验证码
		String code=request.getParameter("check");
		HttpSession session=request.getSession();
		String scode=(String) session.getAttribute("CHECKCODE_SERVER");
		session.removeAttribute("CHECKCODE_SERVER");  //保证验证码只能用一次,防止倒退后验证码还能使用
		if(scode==null||!scode.equalsIgnoreCase(code)) {
			//验证码错误
			ResultInfo resultInfo=new ResultInfo();
			resultInfo.setFlag(false);
			resultInfo.setErrorMsg("验证码错误");
			//将对象变成json格式
			ObjectMapper obmMapper=new ObjectMapper();
			response.setContentType("application/json;charset=utf-8");
			String json=obmMapper.writeValueAsString(resultInfo);
			//回写客户端
			response.getWriter().write(json);
		}
		else {
			//1.获取用户名和密码
			Map map=request.getParameterMap();
			//2.封装用户对象
			User user=new User();
			try {
				BeanUtils.populate(user, map);
			} catch (IllegalAccessException | InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//3.调用service层的方法查询
			UserService userService=new UserServiceImpl();
			
			//根据用户的用户名和用户密码查询用户所有的信息
			User user2=userService.login(user);
			
			ResultInfo resultInfo=new ResultInfo();//响应的信息
			//4.判断用户是否存在
			if(user2!=null) {
				//判断激活码是否激活
				if(!"Y".equals(user2.getStatus())) {//没有激活激活码
					//如果没有激活,就去根据用户的激活码去激活
					resultInfo.setFlag(false);
					resultInfo.setErrorMsg("激活码尚未激活,请先激活");
	//				UserDao userDao=new UserDaoImpl();
	//				userDao.updateStatus(user2);//根据用户去修改激活状态
				}
				else {  //激活码已经激活,登录成功,前台进行跳转
					resultInfo.setFlag(true);
					//登录成功且激活码已经激活
					request.getSession().setAttribute("user",user2);//登录成功标记存储到session
				}
			}
			else {
				//登录不成功,用户名或者密码不正确
				resultInfo.setFlag(false);
				resultInfo.setErrorMsg("用户名或者密码不正确");
			}
			//将对象变成json格式
			ObjectMapper obmMapper=new ObjectMapper();
			response.setContentType("application/json;charset=utf-8");
			String json=obmMapper.writeValueAsString(resultInfo);
			//回写客户端
			response.getWriter().write(json);

	  }//else
	}
}

 2.2.2编写servcie层的UserService类中的login方法

public User login(User user) {
    return userDao.findByUsernameAndPassword(user.getUsername(),user.getPassword());
}

完整的UserService抽象类以及UserServiceImpl实现类

UserService抽象类

package cn.itcast.travel.service;

import cn.itcast.travel.domain.User;

public interface UserService {
	//注册用户
	public boolean regist(User user);

	public boolean active(String code);

	public User login(User user);
}

UserServiceImpl实现类

package cn.itcast.travel.service.impl;

import java.util.UUID;

import cn.itcast.travel.dao.UserDao;
import cn.itcast.travel.dao.impl.UserDaoImpl;
import cn.itcast.travel.domain.User;
import cn.itcast.travel.service.UserService;
import cn.itcast.travel.util.MailUtils;
import cn.itcast.travel.util.UuidUtil;

public class UserServiceImpl implements UserService {
	UserDao uDao=new UserDaoImpl();
    //注册用户
	@Override
	public boolean regist(User user) {
		// 通过用户名来查询用户信息
		User user2=uDao.findByUsername(user.getUsername());
		if(user2!=null) {
			//说明已经注册了信息,用户名注册失败
			return false;
		}
		//没有注册,保存用户的信息
		//生成激活码,用户的唯一标志
		user.setCode(UuidUtil.getUuid());
		//设置激活状态
		user.setStatus("N");
		//保存用户的信息
		System.out.println(user);
		uDao.save(user);
		//激活邮件发送,邮件正文
	    String content="点击激活【淘淘旅游网】";
		MailUtils.sendMail(user.getEmail(), content, "激活邮件");
		return true;
	}
    //激活激活码
	@Override
	public boolean active(String code) {
		//根据激活码查询用户信息 ,注意激活码是唯一的
		User user =uDao.findByCode(code);
		if(user!=null) { //存在该用户,调用dao的方法修改激活状态
			//如果存在该用户,根据用户修改激活状态
			uDao.updateStatus(user);
			return true;
		}
		else {
			return false;
		}
		
	}
	//登录查询检测
	@Override
	public User login(User user) {
		// TODO Auto-generated method stub
		return uDao.findByUsernameAndPassword(user);
	}

}

 2.2.3编写DAO层的UserDaoImpl类中的findByUsernameAndPassword()方法

public User findByUsernameAndPassword(String username, String password) {
    User user = null;
    try {
        //1.定义sql
        String sql = "select * from tab_user where username = ? and password = ?";
        //2.执行sql
        user = template.queryForObject(sql, new BeanPropertyRowMapper(User.class), username,password);
    } catch (Exception e) {

    }

    return user;
}

完整的UserDao抽象类以及UserDaoImpl实现类

package cn.itcast.travel.dao;
import cn.itcast.travel.domain.User;

public interface UserDao {
	  //根据用户名来查询用户信息
      public User findByUsername(String username);
      //用户信息保存
      public void save(User user);
      //根据用户来修改用户的激活码
	  public void updateStatus(User user);
	  //根据激活码查询用户信息
	  public User findByCode(String code);
	  //登录根据用户名和密码查询
	  public User findByUsernameAndPassword(User user);
      
}
package cn.itcast.travel.dao.impl;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import cn.itcast.travel.util.JDBCUtils;
import cn.itcast.travel.dao.UserDao;
import cn.itcast.travel.domain.User;


public class UserDaoImpl implements UserDao {
	//操作数据库的对象
	private JdbcTemplate jdbcTemplate=new JdbcTemplate(JDBCUtils.getDataSource());
	@Override
	public User findByUsername(String username) {
		//根据用户名来查询用户信息
		User user=null;
		try {//这个trycatch是为了防止jdbctemplate查询时没查到用户,封装用户会出异常,不是返回null 而设置的
			// 1.编写sql语句
			String sql="select* from tab_user where username = ?";
			//2.执行sql语句
			user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper(User.class),username);
		} catch (DataAccessException e) {
		}
		return user;
	}
	
    //注册成功后保存用户信息
	@Override
	public void save(User user) {
		// 1.定义sql
		String sql="insert into tab_user(username,password,name,birthday,sex,telephone,email,status,code) values(?,?,?,?,?,?,?,?,?)";
		//2.执行sql语句
		jdbcTemplate.update(sql,user.getUsername(),
				                user.getPassword(),
				                user.getName(),
				                user.getBirthday(),
				                user.getSex(),
				                user.getTelephone(),
				                user.getEmail(),
				                user.getStatus(),
				                user.getCode()
				           );
		
	}
	
    //根据指定的用户来修改用户的激活码状态
	@Override
	public void updateStatus(User user) {
		// 1.编写sql语句
		String sql="update tab_user set status= 'Y' where code= ?";
		//执行sql语句
		jdbcTemplate.update(sql,user.getCode());
	}
	
    //根据激活码来查询用户的信息
	@Override
	public User findByCode(String code) {
		
		
		User user=null;
		try {
			// 1.编写sql语句
			String sql="select * from tab_user where code= ?";
			//2.执行sql,返回user
			user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper(User.class),code);
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
		return user;
	}
    //根据用户名和密码查询
	@Override
	public User findByUsernameAndPassword(User user) {
		//根据用户名和密码来查询用户所有信息
		User user2=null;
		try {//这个trycatch是为了防止jdbctemplate查询时没查到用户,封装用户会出异常,不是返回null 而设置的
			 // 1.编写sql语句
			 String sql="select* from tab_user where username = ? and password= ?";
			 //2.执行sql语句
			 user2 = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper(User.class),user.getUsername(),user.getPassword());
		} catch (Exception e) {
	    }
		return user2;
	}  
}

2.2.4 index页面中(登录后)用户姓名提示功能

效果:

header.html代码 

​​​​

findUserServlet代码 

//从session中获取登录用户
Object user = request.getSession().getAttribute("user");
//将user写回客户端

ObjectMapper mapper = new ObjectMapper();
response.setContentType("application/json;charset=utf-8");
mapper.writeValue(response.getOutputStream(),user);

完整的 findUserServlet类

package cn.itcast.travel.web.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.itcast.travel.domain.User;

/**
 * Servlet implementation class FindUserServlet
 */
@WebServlet("/findUserServlet")
public class FindUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		  //1.登陆成功且已经激活后后 获取存储在session域中的user
		   Object user=request.getSession().getAttribute("user");
		   //2.将user写会到客户端
		   ObjectMapper objectMapper=new ObjectMapper();
		   response.setContentType("application/json;charset=utf-8");
		   objectMapper.writeValue(response.getOutputStream(),user);
	}
}

2.2.5 退出

什么叫做登录了?session中有user对象。

实现步骤:

  1. 访问servlet,将session销毁
  2. 跳转到登录页面

代码实现:

Header.html

旅游网站系统----登录功能_第3张图片

完整的Header.html



    
    
     
    
    

 在exitServlet中销毁session域的user属性

package cn.itcast.travel.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/exitServlet")
public class ExitServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.销毁session
        request.getSession().invalidate();
        //2.跳转登录页面
        response.sendRedirect(request.getContextPath()+"/login.html");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

你可能感兴趣的:(旅游商城系统开发,servlet)