关闭

JSP连接数据库

标签: jsp
97人阅读 评论(0) 收藏 举报
分类:

jsp利用jdbc连接mysql数据库并验证用户名、密码是否正确,正确的话跳转新页面,错误的话返回登录页面

<%@ page language="java" import="java.util.*" import="java.sql.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'manage.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
    <%
    Connection con = null;
    PreparedStatement pstat = null;
    //将请求和响应都设置为utf-8
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=utf-8");

    String name=request.getParameter("name");
    String pass=request.getParameter("password");
    //步骤1.导入jar包,将mysql的jar包导入tomcat的lib文件夹
    try{
    //步骤2.加载jdbc驱动
    Class.forName("com.mysql.jdbc.Driver");
    //步骤3.建立连接
    con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/userdb", "root", "123456");
    //步骤4.建立sql执行器
    String sql="select name,password from user where name=? and password=?";
    pstat = con.prepareStatement(sql); 
    //步骤5.设置执行sql语句的参数
    pstat.setString(1, name);
    pstat.setString(2, pass);
    //步骤6.执行sql语句
    ResultSet rs = pstat.executeQuery(); //结果集
    if(rs.next()){
        request.getRequestDispatcher("content.jsp").forward(request, response);
    }else{
        response.sendRedirect("Login.jsp");
    }
    }catch(Exception e){
        e.printStackTrace();   
    }
     %>
  </body>
</html>
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:844次
    • 积分:37
    • 等级:
    • 排名:千里之外
    • 原创:3篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档