关于注册页面和登录页面的业务流程
form表单中确定action提交地址 method 确定提交的方法---》写出相对应的Servlet,假如接受的数据不多 ,那么用
String username = request.getParameter("username");
String password = request.getParameter("password");接受账户和密码 假如数据多 那么需要工具类集合对数据进行处理 ,对于regist需要建立对应的数据库 和domain--->生成get 和set方法,便于插入数据,将这些数据进行转发,request.getRequestDispatcher("/login.jsp").forward(request, response);登录成功 跳转首页面response.sendRedirect(request.getContextPath());详细代码和效果图 如下
package cn.lijun.Demo
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import com.ithiema.register.User;
import com.ithiema.utils.DataSourceUtils;
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1 解决乱码
request.setCharacterEncoding("UTF-8");
//2、获得用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
User login = null;
try {
login = login(username,password);
} catch (SQLException e) {
e.printStackTrace();
}
//3、通过user是否为null判断用户名和密码是否正确
if(login!=null){
//用户名和密码正确
//登录成功 跳转到网站的首页
response.sendRedirect(request.getContextPath());
}else{
//4用户名或密码错误
//跳回当前login.jsp
//使用转发 转发到login.jsp 向request域中存储错误信息
request.setAttribute("loginInfo", "用户名或密码错误");
//转发
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
public User login(String username,String password) throws SQLException{
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from user where username=? and password=?";
//只有一个对象
User user = runner.query(sql, new BeanHandler<User>(User.class), username,password);
return user;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}