一,登录
*访问路径
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet{
//提供方法给别个访问才可以
//Servlet可以支持多重访问方式
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
获取主页表单提交到数据并返回
设置编码方式
*注意相应也许设置编码方式 不然会乱码
编码方式三种 顺序上到下
"gtf-8"
"gbk"
"gb2312"
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("gbk");
String uname=req.getParameter("uname");
String upwd=req.getParameter("upwd");
PrintWriter out = resp.getWriter();
if(uname==""||upwd==""){
out.print("<script>alert('用户名或密码不能为空');location.href='index.jsp';</script>");
}
else{
IUserBiz ib=new UserBiz();
List<Users> ls=ib.getAll();
boolean f=false;
for(Users u:ls){
if(uname.equals(u.getUsername())&&upwd.equals(u.getPassword())){
f=true;
req.setAttribute("uname", uname);
break;
}
}
if(!f){
out.print("<script>alert('用户名或密码错误');location.href='index.jsp';</script>");
}
else{
req.getRequestDispatcher("index.jsp").forward(req,resp );
}
}
}
}
二,注册
@WebServlet("/rigister.do")
public class RigisterServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置编码方式
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("gbk");
//拿到表单的值
String sname= req.getParameter("sname");
String pwd= req.getParameter("pwd");
String spwd= req.getParameter("spwd");
String name= req.getParameter("name");
String sex= req.getParameter("sex");
PrintWriter out=resp.getWriter();
//
if(sname==""||pwd==""){
out.print("<script>alert('用户名或密码不能为空');location.href='rigister.jsp';</script>");
}
else if(!pwd.equals(spwd)){
out.print("<script>alert('两次密码不一致');location.href='rigister.jsp';</script>");
}
else{
Users user=new Users(sname,pwd,name,sex);
IUserBiz ib=new UserBiz();
ib.adduser(user);
req.getRequestDispatcher("index.jsp").forward(req, resp);
}
}
}