如何用jsp jdbc servlet实现登录注册

 我来答
ae...8@33sn.cc
2017-07-31 · 超过17用户采纳过TA的回答
知道答主
回答量:80
采纳率:0%
帮助的人:31万
展开全部

第一步:web.xml

Java code?
   

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="
    xmlns:xsi="
    xsi:schemaLocation="
 
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
 
    <servlet>
        <description>This is the description of my J2EE component</description>
        <display-name>This is the display name of my J2EE component</display-name>
        <servlet-name>loginServlet</servlet-name>
        <servlet-class>com.servlet.loginServlet</servlet-class>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>loginServlet</servlet-name>
        <url-pattern>/loginServlet</url-pattern>
    </servlet-mapping>
</web-app>

   


第二步:数据库

Java code?
   
/*
SQLyog Ultimate v8.32 
MySQL - 5.5.23 : Database - student
*********************************************************************
*/
 
 
/*!40101 SET NAMES utf8 */;
 
/*!40101 SET SQL_MODE=''*/;
 
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`student` /*!40100 DEFAULT CHARACTER SET utf8 */;
 
USE `student`;
 
/*Table structure for table `user` */
 
DROP TABLE IF EXISTS `user`;
 
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user` varchar(50) NOT NULL,
  `pwd` varchar(50) NOT NULL,
  `name` varchar(50) NOT NULL,
  `age` int(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
 
/*Data for the table `user` */
 
insert  into `user`(`id`,`user`,`pwd`,`name`,`age`) values (1,'zhangsan','123','张三',21);
 
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

   



第三步:登录login.jsp

Java code?
   
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
        <title>xx系统</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>
        <div align="center"> <font size=" 2" color="#FF6633">用户登录</font>
    </div>
    <form id="form1" name="form1" method="post" action="loginServlet">
    <table width="357" border="0" align="center">
        <tr>
          <td width="128">用户名:</td>
          <td width="219"><label>
            <input name="user" type="text" id="user" />
          </label></td>
        </tr>
        <tr>
          <td>密 码:</td>
          <td><label>
            <input name="pwd" type="password" id="pwd" />
          </label></td>
        </tr>
        <tr>
          <td><label>
            <input type="submit" name="Submit" value="登录" />
          </label></td>
          
        </tr>
    </table>
    <p>&nbsp;</p>
    </form>
    </body>
    </html>

   


第四步:success.jsp

Java code
   
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    ${address }</br>
    ${port }</br>
     
</body>
</html>

   


第五步:loginServlet.java

Java code
   
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.sql.SQLException;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import com.dao.Dao;
 
public class loginServlet extends HttpServlet {
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
 
        // Put your code here
 
    }
 
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String name = new String(request.getParameter("user").getBytes(
                "ISO8859_1"), "GBK");
        String pwd = new String(request.getParameter("pwd").getBytes(
                "ISO8859_1"), "UTF-8");
        User user = new User();
        user.setUser(name);
        user.setPwd(pwd);
        Dao dao = new Dao();
        boolean isLogin;
        try {
            isLogin = dao.logoin(user);
 
            if (isLogin) {
                InetAddress inetAddress = InetAddress.getLocalHost();
                String m = inetAddress.getHostAddress();
                int n = request.getRemotePort();
                System.out.println(m+"*********"+ n);
                HttpSession session = request.getSession(); 
                session.setAttribute("address", m);
                session.setAttribute("port", n);
                response.sendRedirect("success.jsp");
            } else {
                response.sendRedirect("index.jsp");
            }
 
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
 
    public void init() throws ServletException {
    }
 
}

   



Java code
   
package com.servlet;
 
public class User {
    private String user;
    private String pwd;
    private String name;
 
    private int age;
 
    public String getUser() {
        return user;
    }
 
    public void setUser(String user) {
        this.user = user;
    }
 
    public String getPwd() {
        return pwd;
    }
 
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
}

   



Java code?
   
package com.util;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
public class GetConnection {
    //通过静态方法注册驱动,获得连接
 
    public static Connection getConnection(){
       String driver = "com.mysql.jdbc.Driver";
       String url = "jdbc:mysql://localhost/student";
       Connection con = null;
       try {
        Class.forName(driver);
        try {
         con = DriverManager.getConnection(url,"root","123456");
        } catch (SQLException e) {
         e.printStackTrace();
        }
       } catch (ClassNotFoundException e) {
        e.printStackTrace();
       }
       System.out.println("已获得数据库的连接");
       return con;
    }
    /*public static void main(String args[]){
       getConnection();
    }*/
    }

   



Java code?
  
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
import com.servlet.User;
import com.util.GetConnection;
 
public class Dao {
    private Connection conn;
    private PreparedStatement pstat;
    String sql = "";
 
    /**
     *
     * 用户登录
     */
    public boolean logoin(User user) throws SQLException {
        conn = GetConnection.getConnection();
        boolean i = false;
        sql = "select * from user where user=? and pwd=?";
 
        pstat = conn.prepareStatement(sql);
 
        pstat.setString(1, user.getUser());
        pstat.setString(2, user.getPwd());
 
        ResultSet rs1 = (ResultSet) pstat.executeQuery();
        if (rs1.next()) {
            i = true;
            rs1.close();
            pstat.close();
        } else {
            i = false;
            rs1.close();
            pstat.close();
        }
        conn.close();
        return i;
    }
 
    /**
     * 用户注册
     */
    public void addUser(User user) {
        conn = GetConnection.getConnection();
        sql = "insert into user values(?,?,?,?)";
        try {
            pstat = conn.prepareStatement(sql);
            pstat.setString(1, user.getUser());
            pstat.setString(2, user.getPwd());
            pstat.setString(3, user.getName());
 
            pstat.setInt(5, user.getAge());
            pstat.executeUpdate();
            pstat.close();
            conn.close();
 
        } catch (SQLException e) {
            e.printStackTrace();
        }
 
    }
}

   


注意事项:1.数据库用户密码;2.访问地址。

推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式