用servlet、request和Druid技术写登录案例

用户登录案例需求:
  1.编写login.html登录页面
    username & password 两个输入框
  2.使用Druid数据库连接池技术,操作mysql,day14数据库中user表
  3.使用JdbcTemplate技术封装JDBC
  4.登录成功跳转到SuccessServlet展示:登录成功!用户名,欢迎您
  5.登录失败跳转到FailServlet展示:登录失败,用户名或密码错误

https://repo1.maven.org/maven2/com/alibaba/druid/icon-default.png?t=M276https://repo1.maven.org/maven2/com/alibaba/druid/        Spring jar包大全icon-default.png?t=M276https://repo.spring.io/ui/native/libs-release-local/org/springframework/spring-core/5.3.9/Commons jar包大全icon-default.png?t=M276https://commons.apache.org/proper/commons-logging/download_logging.cgi        注意:同一类jar包版本号必须是统一的,不然会起冲突。

1.编写login.html登录页面




    
    登录页面


    
用户名:
密 码:

2.使用Druid数据库连接池技术,操作mysql

用servlet、request和Druid技术写登录案例_第1张图片

2.1添加lib包,在包中放入相应的Jar包,将lib包add as Library,在src文件下创建druid.properties文件

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=utf-8&userSSL=false&serverTimezone=GMT%2B8
username=root
password=123456
initialSize=5
maxActive=10
maxWait=3000

filters=stat
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200

注意:url连接后设置数据库时区、编码方式等。

  2.2创建JDBCUtil.java

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtil {
    private static   DataSource ds;
    static {
        try {
        //1.加载配置文件
        Properties pro = new Properties();

        //使用ClassLoader加载配置文件,获取字节输入流
        InputStream resourceAsStream = JDBCUtil.class.getClassLoader().getResourceAsStream("druid.properties");
        pro.load(resourceAsStream);
        //2.初始化连接池对象
             ds = DruidDataSourceFactory.createDataSource(pro);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static  DataSource getDataSource(){
        return ds;
    }

    public static Connection GetConnection() throws SQLException {
        return ds.getConnection();
    }

}

3创建User实例

public class User {
    private String name;
    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

4创建UserDao方法

import cn.hubu.domain.User;
import cn.hubu.util.JDBCUtil;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

//操作数据库的User类
public class UserDao {
    //声明JDBCTemplate对象共用
    private JdbcTemplate template = new JdbcTemplate(JDBCUtil.getDataSource());
    /*
    * 登录方法
    * loginUser只有用户名和密码
    * user包含用户全部数据,没有查询到,返回null
    * */
    public User login(User loginUser){

        try {
            //编写sql
            String sql="select * from user where name=? and password=?";
            //调用query方法
            User user =template.queryForObject(
                    sql,
                    new BeanPropertyRowMapper(User.class),
                    loginUser.getName(),
                    loginUser.getPassword()
                    );
            return user;
        } catch (DataAccessException e) {
            e.printStackTrace();
            return null;
        }

    }
}

5建立UserDao测试类,UserDaoTest.java

import cn.hubu.dao.UserDao;
import cn.hubu.domain.User;
import org.junit.Test;

public class UserDaoTest {

    @Test
    public void TestLogin(){
        User loginuser = new User();
        loginuser.setName("2019");
        loginuser.setPassword("1234");

        UserDao dao = new UserDao();
        User user = dao.login(loginuser);

        System.out.println(user);
    }
}

6 创建loginServlet.java文件。

  获取参数map集合,将map集合注入loginUser类中

import cn.hubu.dao.UserDao;
import cn.hubu.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;

@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    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");

        Map map = request.getParameterMap();
        //3.封装User对象
        User loginUser =new User();
        loginUser.setName(username);
        loginUser.setPassword(password);
        try {
            BeanUtils.populate(loginUser,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //4.调用UserDao中Login方法
        UserDao dao = new UserDao();
        User user = dao.login(loginUser);

        //5.判断user
        if(user==null){
            //登录失败
            request.getRequestDispatcher("/failServlet").forward(request,response);
        }else{
            //登录成功
            //存储数据
            request.setAttribute("user",user);
            //转发
            request.getRequestDispatcher("/successServlet").forward(request,response);
        }


    }
}

7 创建登录失败servlet

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;

@WebServlet("/failServlet")
public class failServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //给页面写一句话

        //设置编码
        response.setContentType("text/html;charset=utf-8");
        //输出
        response.getWriter().write("登录失败,用户名或密码错误!");
    }
}

8 创建登录成功servlet

import cn.hubu.domain.User;

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;

@WebServlet("/successServlet")
public class SuccessServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //获取request中的user对象
        User user =(User) request.getAttribute("user");
        //
        if(user!=null){
            //设置编码格式
            response.setContentType("text/html;charset=utf-8");
            //输出
            response.getWriter().write("登录成功!"+user.getName()+"欢迎你");
        }

    }
}

9.项目包全局图

用servlet、request和Druid技术写登录案例_第2张图片

你可能感兴趣的:(mysql,数据库,服务器)