Servlet实现登录

来源:互联网 发布:百度云管家mac下载 编辑:程序博客网 时间:2024/05/18 00:55

1. 登录表单

<form class="form-horizontal" method="post" action="http://localhost:8080/day01/login"> <div class="form-group">    <label for="username" class="col-sm-2 control-label">用户名</label>    <div class="col-sm-6">      <input type="text" class="form-control" id="username" placeholder="请输入用户名" name="username">    </div>  </div>   <div class="form-group">    <label for="inputPassword3" class="col-sm-2 control-label">密码</label>    <div class="col-sm-6">      <input type="password" class="form-control" id="inputPassword3" placeholder="请输入密码" name=password>    </div>  </div>  </form>

2. 登录的Servlet

public class LoginServlet extends HttpServlet {    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {                //设置中文编码方式                resp.setContentType("text/html;charset=utf-8");                //获取浏览器发过来的登录参数                String username=req.getParameter("username");                String passwordString=req.getParameter("password");                System.out.println(username+"--"+passwordString);                User user = null;                try {                    user = new UserService().login(username,passwordString);                } catch (SQLException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }                if(user==null){                    resp.getWriter().println("用户名和密码不匹配");                }else{                    resp.getWriter().println(user.getUsername()+"欢迎回来");                }    }}

3. UserService

public class UserService {    /**     * 用户登录     * @param username用户名     * @param passwordString 密码     * @return 用户     * @throws SQLException      */    public User login(String username, String passwordString) throws SQLException {        UserDao dao=new UserDao();        return dao.getUserByusernameAndpwd(username,passwordString);    }}

4. dao查询数据库(需要提前导入相应的jar包和工具类)

public class UserDao {    /**     * 登录     * @param username 用户名     * @param passwordString 密码     * @return 查询出的用户     * @throws SQLException      */    public User getUserByusernameAndpwd(String username, String passwordString) throws SQLException {        //创建queryRunner        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());        //编写sql        String sqlString="select * from user where username=? and password=?";        //执行sql        User user=qr.query(sqlString, new BeanHandler<>(User.class),username,passwordString);        return user;    }}

涉及到的工具包和工具类下载请移步

0 0
原创粉丝点击