JAVAWEB-DAY02

1 Crea un proyecto web y mejora la estructura del proyecto

2 Agregar dependencias del proyecto 

 <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.48</version>
    </dependency>

3 El requisito es iniciar sesión y registrarse

Obtenga la demanda, sql 1 de bajo nivel seleccione desde donde 2 inserte en los valores

Página de registro de inicio de sesión de 1 página

2 servlet

Servicio de 3 llamadas

4 llamar a dao

3.1 Página

<!DOCTYPE HTML>
<html>
<head>
    <title>Purple_loginform Website Template | Home :: w3layouts</title>
    <link href="../css/style.css" rel="stylesheet" type="text/css" media="all" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <!-- -->
    <script>var __links = document.querySelectorAll('a');function __linkClick(e) { parent.window.postMessage(this.href, '*');} ;for (var i = 0, l = __links.length; i < l; i++) {if ( __links[i].getAttribute('data-t') == '_blank' ) { __links[i].addEventListener('click', __linkClick, false);}}</script>
    <script src="../js/jquery.min.js"></script>
    <script>$(document).ready(function(c) {
        $('.alert-close').on('click', function(c){
            $('.message').fadeOut('slow', function(c){
                $('.message').remove();
            });
        });
    });
    </script>
</head>
<body>
<!-- contact-form -->
<div class="message warning">
    <div class="inset">
        <div class="login-head">
            <h1>小视频登录页面</h1>
            <div class="alert-close"> </div>
        </div>
        <form action="/day0001_war/Login" method="post">
            <li>
                <input type="text" class="text" name="Username" /><a href="#" class="icon user"></a>
            </li>
            <div class="clear"> </div>
            <li>
                <input type="password" name="Password" /> <a href="#" class="icon lock"></a>
            </li>
            <div class="clear"> </div>
            <div class="submit">
                <input type="submit"  value="登录" >
                <div class="clear"> </div>
            </div>
        </form>
    </div>
</div>
</div>
<div class="clear"> </div>
<!--- footer --->
<div class="footer">
    <p>Copyright &copy; 2014.</p>
</div>
<div style="display:none"><script src='http://v7.cnzz.com/stat.php?id=155540&web_id=155540' language='JavaScript' charset='gb2312'></script></div>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
    <title>Purple_loginform Website Template | Home :: w3layouts</title>
    <link href="../css/style.css" rel="stylesheet" type="text/css" media="all" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <!-- -->
    <script>var __links = document.querySelectorAll('a');function __linkClick(e) { parent.window.postMessage(this.href, '*');} ;for (var i = 0, l = __links.length; i < l; i++) {if ( __links[i].getAttribute('data-t') == '_blank' ) { __links[i].addEventListener('click', __linkClick, false);}}</script>
    <script src="../js/jquery.min.js"></script>
    <script>$(document).ready(function(c) {
        $('.alert-close').on('click', function(c){
            $('.message').fadeOut('slow', function(c){
                $('.message').remove();
            });
        });
    });
    </script>
</head>
<body>
<!-- contact-form -->
<div class="message warning">
    <div class="inset">
        <div class="login-head">
            <h1>小视频注册页面</h1>
            <div class="alert-close"> </div>
        </div>
        <form action="/day0001_war/Register" method="post">
            <li>
               <input type="text" class="text" name="Username"  value="用户名"/>
            </li>
            <div class="clear"> </div>
            <li>
             <input type="password" name="Password"value="密码" />
            </li>
            <li>
               <input type="password" name="Password"value="重复密码" />
            </li>
            <li>
               <input type="password" name="text" name="tel" value="手机号"/>
            </li>
            <div class="clear"> </div>

            <div class="submit" style="margin-left: 130px">
                <input type="submit"  value="确定注册" >
                <div class="clear"> </div>
            </div>

        </form>
    </div>
</div>
</div>
<div class="clear"> </div>

<div style="display:none"><script src='http://v7.cnzz.com/stat.php?id=155540&web_id=155540' language='JavaScript' charset='gb2312'></script></div>
</body>
</html>

3,2 Servlet

3.2.1 Iniciar sesión

package com._51doit.controller;

import com._51doit.pojo.User;
import com._51doit.service.UserService;
import com._51doit.service.UserServiceImpl;

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(name = "Login")
public class Login extends HttpServlet {
    UserService userService = new UserServiceImpl() ;
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 获取页面的请求数据
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            User u = userService.login(username, password);
            if(u!=null){
                // 登陆成功跳转到成功页面
                resp.sendRedirect("html/success.html");
            }else{
                // 失败  留在登录页面
                resp.sendRedirect("html/login.html");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

3.2.2 Registro

package com._51doit.controller;

import com._51doit.pojo.User;
import com._51doit.service.UserService;
import com._51doit.service.UserServiceImpl;

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;

public class Register extends HttpServlet {
    UserService userService = new UserServiceImpl() ;
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 接收页面的请求参数
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String tel = req.getParameter("tel");

            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setTel(tel);
            // 调用业务层完成注册
            userService.register(user);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

3.3 servicio 

3.3.1 Interfaz

package com._51doit.service;

import com._51doit.pojo.User;

/**
 * 业务类
 */
public interface UserService {
    public  void register(User user) throws  Exception;
    public  User login(String username , String password) throws  Exception;
}

3.3.2 Clase de implementación

package com._51doit.service;

import com._51doit.dao.UserDao;
import com._51doit.dao.UserDaoImpl;
import com._51doit.pojo.User;

public class UserServiceImpl  implements  UserService{
    UserDao userDao = new UserDaoImpl() ;
    @Override
    public void register(User user) throws Exception {
        // 调用dao层 插入数据
        userDao.addUser(user);
    }

    @Override
    public User login(String username, String password) throws Exception {
        User user =  userDao.getUserByUsernameAndPassword(username,password);
        return  user ;
    }
}

3.4 dao

3.4.1 Interfaz

public interface UserDao {
    public  void  addUser(User user) throws Exception;
    public  User  getUserByUsernameAndPassword(String username , String password) throws Exception;
}

3.4.2 Clase de implementación

public class UserDaoImpl implements  UserDao {
    static   Connection conn = null;
    static{
      try {
          Class.forName("com.mysql.jdbc.Driver");
          conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/doit18?characterEncoding=UTF-8",  "root", "root");
      } catch (Exception e) {
          e.printStackTrace();
      }
  }


    @Override
    public void addUser(User user) throws Exception {
        PreparedStatement ps = conn.prepareStatement("insert into tb_user (username , password , tel) values(?,?,?)");
        ps.setString(1,user.getUsername());
        ps.setString(2,user.getPassword());
        ps.setString(3,user.getTel());
        ps.execute();
    }

    @Override
    public User getUserByUsernameAndPassword(String username, String password) throws Exception {
        PreparedStatement ps = conn.prepareStatement("select * from tb_user where  username = ? and password = ?");
        ps.setString(1,username);
        ps.setString(2,password);
        ResultSet rs = ps.executeQuery();
        User user = null ;
        while(rs.next()){
            user = new User();
            int uid = rs.getInt("uid");
            int age = rs.getInt("age");
            String username2= rs.getString("username");
            String password2 = rs.getString("password");
            String gender = rs.getString("gender");
            String job = rs.getString("job");
            String tel = rs.getString("tel");
          user.set(uid,username2,password2,gender,job,age,tel);
        }
        return user;
    }
}

 

 

 

 

 

 

 

 

Supongo que te gusta

Origin blog.csdn.net/qq_37933018/article/details/109269977
Recomendado
Clasificación