package cn.itcast.web;
import cn.itcast.domain.Login;
import cn.itcast.service.Impl.ServiceImpl;
import cn.itcast.service.Service_SafeLogin;
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 java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置获取的编码格式
request.setCharacterEncoding("utf-8");
//获取验证码并删除,防止重复使用
String verifyCode = request.getParameter("verifyCode");
HttpSession session = request.getSession();
String checkCode = (String) session.getAttribute("CHECKCODE_SERVER");
session.removeAttribute("CHECKCODE_SERVER");
//判断验证码是否正确
if(checkCode!=null&& checkCode.equalsIgnoreCase(verifyCode)){
//验证码正确
//查询数据库
Login login = new Login();
Service_SafeLogin service = new ServiceImpl();
Map<String, String[]> prnMap = request.getParameterMap();
try {
org.apache.commons.beanutils.BeanUtils.populate(login,prnMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
Login isLogin = service.login(login);
//判断是否 登录成功
if (isLogin!=null){
//登录成功
response.sendRedirect(request.getContextPath()+"/index.jsp");
}else{
//登录失败
request.setAttribute("error_login","您输入的用户名或密码有误");
request.getRequestDispatcher(request.getContextPath()+"/login.jsp").
forward(request,response);
}
}else{
//验证码不正确
request.setAttribute("error","您输入的验证码有误");
request.getRequestDispatcher(request.getContextPath()+"/login.jsp").
forward(request,response);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
|
|