package cn.itcast.travel.web.servlet;
import cn.itcast.travel.domain.ResultInfo;
import cn.itcast.travel.domain.User;
import cn.itcast.travel.service.impl.ServiceImpl;
import cn.itcast.travel.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;
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{
// {'error':'您的用户名或密码错误'}
//{"flag":false,"data":null,"errorMsg":"??????????"}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
ResultInfo resultInfo = new ResultInfo();
HttpSession session = request.getSession();
Map<String, String[]> map = request.getParameterMap();
//判断验证码是否正确。。。
String checkCode = request.getParameter("checkCode");
String code = (String) session.getAttribute("CHECKCODE_SERVER");
response.setContentType("application/json;charset=utf-8");
if (!StringUtils.equalsIgnoreCase(checkCode,code)){
//验证码错误
resultInfo.setFlag(false);
resultInfo.setErrorMsg("您的验证码错误");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(response.getWriter(),resultInfo);
return;
}
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//调用service层校验用户名和密码
ServiceImpl service = new ServiceImpl();
User login = service.login(user);
if (login!=null){
//判断激活码是否激活
if ("N".equals(login.getStatus())){
//未激活
resultInfo.setFlag(false);
resultInfo.setErrorMsg("您的账户未激活");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(response.getWriter(),resultInfo);
return;
}
//登录成功将用户信息存进session域
session.setAttribute("login",login);
request.getRequestDispatcher("/index.html").forward(request,response);
}else{
//登录失败
response.setContentType("application/json;charset=utf-8");
resultInfo.setFlag(false);
resultInfo.setErrorMsg("您的用户名或密码错误");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(response.getWriter(),resultInfo);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
|
|