package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dao.LoginDao;
//@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet{
//此方法响应 get 方式的请求:如 表单中method的值为get,或使用超链接发出请求
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req,resp);
}
//此方法响应 post 方式的请求: 如 表单中method的值为post
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//取表单参数
String login_name = req.getParameter("username");
String password = req.getParameter("password");
LoginDao dao = new LoginDao();
//调LoginDao的checkLoginUser()检查账户名、密码是否存在
boolean flag = dao.checkLoginUser(login_name, password);
if(flag){//若存在,则转向内容页main.jsp,同时在session范围打上登陆成功的标志
HttpSession session = req.getSession();
session.setAttribute("login","ok");
resp.sendRedirect("pages/vetsearch.jsp");//网页重定向(客户端跳转)p141
}else{ //若不存在,则给出提示,并转至登陆页
//先设客户端浏览器的编码方式,再用out对象向浏览器输出内容,否则会出现中文乱码
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
out.println("账户名或密码错误,请重新登陆!");
resp.setHeader("refresh","2;url=index.jsp");//(网页重定向)
}
}
//此方法在servlet销毁时被调用
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
}
//此方法在servlet初始化时被调用
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
}
}
评论7
最新资源