首页 > 数据库技术 > 详细

Servlet-3 :JDBC+重定向

时间:2020-05-08 22:54:23      阅读:62      评论:0      收藏:0      [点我收藏+]

请求重定向 redirect
1) Servlet接收到浏览器端请求并处理完成后,给浏览器端一个特殊的响应,这个特殊的响应要求浏览器去请求一个新的资源,整个过程中浏览器端会发出两次请求,且浏览器地址栏会改变为新资源的地址。
2) 重定向的情况下,原Servlet和目标资源之间就不能共享请求域数据了
3) 实现重定向的API

技术分享图片

技术分享图片

技术分享图片
package com.atguigu.login.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atguigu.login.DAO.UserDAOImpl;
import com.atguigu.login.bean.User;

public class LoginServlet extends HttpServlet{
    
    @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 {
        System.out.println("登录信号");
        
        req.setCharacterEncoding("utf-8");
        //获取用户名
        String username = req.getParameter("username");
        //获取密码
        String password = req.getParameter("password");
        System.out.println(username + " , " + password ); 
        
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        //获取Dao对象
                UserDAOImpl userDao = new UserDAOImpl();
                
                User user = userDao.getUserByUsernameAndPassword(username, password);
        
        /*
                    if("Admin".equalsIgnoreCase(username) && "123456".equals(password)) {
                    //登录成功
                    out.println("<h1><font color=‘green‘>Login Success! 登录成功<font><h1>");
                }else {
                    //登录失败
                    //PrintWriter out = resp.getWriter();
                    out.println("<h1><font color=‘red‘>Login Fail! 登录失败</font></h1>");
                }
         */
                if(user == null) {
                    //通过重定向的方式去往登录页面
                    /*
                     * 服务器会给浏览器发送一个302状态码以及一个新的地址, 
                     *  
                     */
                    resp.sendRedirect("login.html");  
                    
                    
                    
                    
                }else {
                    //登录成功
                    out.println("<h1><font color=‘green‘>Login Success! 登录成功<font><h1>");
                }
    }

}
public class LoginServlet extends HttpServlet
技术分享图片
package com.atguigu.login.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class ConnectionUtil {
    private static String driver = null; 
    private static String url = null ;
    private static String username = null ;
    private static String password = null ;
    private static Properties props = new Properties();
    
    private static ThreadLocal<Connection > tl = new ThreadLocal<>();
    static {
        try {
            //类加载器读取文件
            InputStream in =
                    ConnectionUtil.class.getClassLoader().getResourceAsStream("db.properties");
            props.load(in);
            
            driver =props.getProperty("jdbc.driver");
            url = props.getProperty("jdbc.url");
            username= props.getProperty("jdbc.username");
            password = props.getProperty("jdbc.password");
            
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    public static  Connection  getConn()  throws Exception{
        //先尝试从tl中获取
        Connection conn = tl.get();
        if(conn == null ) {
            conn = (Connection) DriverManager.getConnection(url, username, password);
            tl.set(conn);
        }
        return conn ;
    }
    
    
    /**
     * 关闭连接的方法
     */
    public static void closeConn()  throws Exception{
        //先尝试从tl中获取
        
        Connection conn = tl.get();
        
        if(conn != null ) {
             conn.close();
        }
        
        tl.set(null);
    }
    

    

}
public class ConnectionUtil
技术分享图片
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
jdbc.username=root
jdbc.password=123456
db.properties
技术分享图片
package com.atguigu.login.DAO;

import com.atguigu.login.bean.User;

public interface UserDAO {
    public User getUserByUsernameAndPassword(String username,String password);

}
public interface UserDAO
技术分享图片
package com.atguigu.login.DAO;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.atguigu.login.bean.User;
import com.atguigu.login.utils.ConnectionUtil;


public class UserDAOImpl implements UserDAO{

    @Override
    public User getUserByUsernameAndPassword(String username, String password) {
        User u = null ;
        /*try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }//com.mysql.cj.jdbc.Driver
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT";
        String user="root";
        String pawd="123456";*/
        try {
            
//            Connection conn = DriverManager.getConnection(url, user, pawd);
            Connection conn=ConnectionUtil.getConn();
            
            
            String sql="select id, username,password from stu where username = ? and password = ?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            ResultSet  rs = ps.executeQuery();
            
            if(rs.next()) {
                u = new User();
                u.setId(rs.getInt("id"));
                u.setUsername(rs.getString("username"));
                u.setPassword(rs.getString("password"));
            }
            
            return u ; 
            
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
        return null;
        
    }
}
public class UserDAOImpl implements UserDAO
技术分享图片
package com.atguigu.login.bean;

public class User {
    private Integer id ; 
    private String username ; 
    private String password ;
    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;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
    }
}
public class User

 

Servlet-3 :JDBC+重定向

原文:https://www.cnblogs.com/lemonzhang/p/12852994.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!