美文网首页
黑猴子的家:JavaWeb 之 Servlet 小项目

黑猴子的家:JavaWeb 之 Servlet 小项目

作者: 黑猴子的家 | 来源:发表于2019-12-13 10:22 被阅读0次

    通过web_servlet05 ,打通任督二脉,完成登陆和注册功能,这里面分了两个项目,功能一样,其中一个使用了才c3p0连接池和dbutil框架

    Jsp -> view
    Servlet -> Ctroller
    dao、entity .. -> model
    mvc -> view 提交到Ctroller,Ctroller访问model,model把数据返回给Ctroller, Ctroller再放回到jsp页面

    1、需求

    实现用户的登陆和注册功能


    2、code

    1)UserDao
    package com.alex.web.dao;
    
    import com.alex.web.entity.User;
    
    public interface UserDao {
    
        public User login(String username,String userpswd)  throws Exception;
        
    }
    
    2)UserDaoImpl
    package com.alex.web.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    
    import com.alex.web.entity.User;
    import com.alex.web.util.DBUtil;
    
    public class UserDaoImpl implements UserDao {
    
        
        /**
            CREATE TABLE t_user(
              id INT PRIMARY KEY AUTO_INCREMENT,
              username VARCHAR(32),
              password VARCHAR(64),
              email VARCHAR(128),
              age INT
            );
         */
        @Override
        public User login(String username, String userpswd) throws Exception {
            Connection connection = null ;
            ResultSet resultSet = null ;
            PreparedStatement prepareStatement = null;
            User user = null ;
            try {
                connection = DBUtil.getConnection();
                String sql = "select * from t_user where username=? and password=?";
                prepareStatement = connection.prepareStatement(sql);
                prepareStatement.setObject(1, username);
                prepareStatement.setObject(2, userpswd);
                resultSet = prepareStatement.executeQuery();
                
                if (resultSet.next()) {
                    user = new User();
                    user.setId(resultSet.getInt("id"));
                    user.setUsername(resultSet.getString("username"));
                    user.setPassword(resultSet.getString("password"));
                    user.setEmail(resultSet.getString("email"));
                    user.setAge(resultSet.getInt("age"));
                }
            } catch (Exception e) {         
                e.printStackTrace();
                throw e ;
            } finally{
                DBUtil.closeConnection(resultSet,prepareStatement,connection);
            }
            return user;
        }
    }
    
    3)User
    package com.alex.web.entity;
    
    public class User {
        
        private Integer id;
        private String username;
        private String password;
        private String email;
        private int age;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + ", age="
                    + age + "]";
        }
    
    }
    
    4)LoginServlet
    package com.alex.web.servlet;
    
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.alex.web.dao.UserDao;
    import com.alex.web.dao.UserDaoImpl;
    import com.alex.web.entity.User;
    /**
     * Servlet作用:处理请求
     * 步骤:
     * ①获取请求数据.
     * ②调用业务层或DAO层方法,完成业务逻辑处理或数据处理.
     * ③根据调用的方法获取返回结果,根据结果来进行判断,然后跳转(转发,重定向)到不同页面.
     */
    public class LoginServlet extends HttpServlet {
        @Override
        public void service(HttpServletRequest req, HttpServletResponse resp)
                    throws ServletException, IOException{       
            try {
                String username = req.getParameter("username");
                String passwd = req.getParameter("passwd");
                resp.setContentType("text/html;charset=UTF-8");
                UserDao userDao = new UserDaoImpl();
                User loginUser = userDao.login(username, passwd);
                if(loginUser!=null){
                    req.getRequestDispatcher("/success.jsp").forward(req, resp);
                }else{
                    //  http://localhost:8080/WebServlet1/failure.html
                    resp.sendRedirect(req.getContextPath()+"/failure.jsp"); 
                }
            } catch (Exception e) {         
                e.printStackTrace();
                resp.sendRedirect(req.getContextPath()+"/error.jsp"); 
            }       
        }
    }
    
    5)DBUtil
    package com.alex.web.util;
    
    import java.io.FileInputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Properties;
    
    public class DBUtil {
    
        static String driverClass;
        static String url;
        static String user;
        static String password;
    
        static {
            try {
                // 加载配置文件
                Properties pro = new Properties();
                //pro.load(new FileInputStream("src/db.properties"));
                // 反射加载读取项目配置文件
                pro.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
                // 读取配置文件
                driverClass = pro.getProperty("driverClass");
                url = pro.getProperty("url");
                user = pro.getProperty("username");
                password = pro.getProperty("password");
    
                // 1.加载驱动
                Class.forName(driverClass);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
        /**
         * 功能:获取连接 异常抛就行,可根据自己的方式处理异常
         * 
         * @return 可用的连接对象
         * @throws IOException
         * @throws FileNotFoundException
         */
        public static Connection getConnection() throws Exception {
            return DriverManager.getConnection(url, user, password);
        }
    
        /**
         * 功能:关闭资源
         * 
         * @param set
         * @param statement
         * @param connection
         * @throws SQLException
         */
        public static void closeConnection(ResultSet set, Statement statement, Connection connection) throws SQLException {
            if (set != null)
                set.close();
            if (statement != null)
                statement.close();
            if (connection != null)
                connection.close();
        }
    }
    
    6)db.properties
    driverClass=com.mysql.jdbc.Driver
    url=jdbc:mysql:///test
    #url=jdbc:mysql://127.0.0.1:3306/test
    #url=jdbc:mysql:///test?rewriteBatchedStatements=true&useServerPrepStmts=false
    username=root
    password=root
    initialSize=5
    maxActive=10
    

    3、调试

    浏览器端使用F12
    服务器端使用小虫子进行断点调试

    相关文章

      网友评论

          本文标题:黑猴子的家:JavaWeb 之 Servlet 小项目

          本文链接:https://www.haomeiwen.com/subject/qtoxnctx.html