package com.hopetesting.web.servlet;
import com.hopetesting.dao.UserDao;
import com.hopetesting.domain.User;
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 java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
/**
* @author newcityman
* @date 2019/9/1 - 0:24
*/
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1、设置编码
request.setCharacterEncoding("utf-8");
/*// 获取请求数据
String username = request.getParameter("username");
String password = request.getParameter("password");
// 3、封装user对象
User loginUser = new User();
loginUser.setPassword(password);
loginUser.setUsername(username);*/
User loginUser = new User();
try {
Map<String, String[]> map = request.getParameterMap();
/* Set<String> strings = map.keySet();
for (String string : strings) {
System.out.println(string);
String[] values = map.get(string);
for (String v : values) {
System.out.println(v);
}
System.out.println("===============");
}*/
BeanUtils.populate(loginUser,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
// 4、调用userdao的login方法
UserDao userDao = new UserDao();
User user = userDao.login(loginUser);
if (user==null){
// 登陆失败
// 转发
request.getRequestDispatcher("/failServlet").forward(request,response);
}else{
// 登录成功
// 存储数据
request.setAttribute("user",user);
// 转发
request.getRequestDispatcher("/successServlet").forward(request,response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
转载于:https://www.cnblogs.com/newcityboy/p/11441255.html