好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java web实现简单注册功能

今天写了一个注册功能,没有用任何框架!发现不会写了,中间查了好几次百度。不过还是顺利的写完并且跑起来了。在这里记录一下。我认为有时候写这些代码还是对我们理解框架很有帮助的,因为框架也是按照这些,对基础进行封装后得到的。

首先是环境的搭建

1、环境的搭建:我用的jdk1.8 tomcat 7.0 eclipse neno 数据库用的是mysql。

2、创建一个动态的web工程(这个应该都会的,这里就不再截图说明了)

3、数据库的创建

我这里创了一个名为t_t_user 的表,里面的字段也很简单,就name password age 三个。

4、数据库创建好之后就开始写前端代码

前端写的很简单

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://HdhCmsTestw3.org/TR/html4/loose.dtd">

< html >

< head >

< meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" >

< title >首页</ title >

</ head >

< body >

  < p style = "color:red;" >${message}</ p >

 

  < form action = "${pageContext.request.contextPath }/login" method = "post" >

    姓名 < input   type = "text" name = "name" />< br >

    年龄 < input type = "text" name = "age" />< br >

    密码< input   type = "password" name = "password" />< br >

    < input type = "submit" value = "提交" >

  </ form >

</ body >

</ html >

5、前端代码写好后就可以写对应的,上传的请求的servlet,在这里我只判断了姓名不能为空,其他的就一样的写就好了。还有这里有个问题,就是我没有进行编码处理。在这里可能出现中文乱码的问题,可以直接在servlet中加入处理中文乱码的语句,或者是写个过滤器,这里我就不再赘述了。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

package com.proven.controller;

 

import java.io.IOException;

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 com.proven.service.UserService;

import com.proven.service.impl.UserServiceImpl;

 

/**

  * Servlet implementation class login

  */

@WebServlet ( "/login" )

public class login extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String name=request.getParameter( "name" );

        String password = request.getParameter( "password" );

        String ages = request.getParameter( "age" );

        int age = Integer.parseInt(ages);

        String message= "" ;

 

        if (name.equals( "" )){

            message= "用户名不能为空" ;

            request.setAttribute( "message" , message);

            request.getRequestDispatcher( "/index.jsp" ).forward(request, response);

        } else {

            UserService userService = new UserServiceImpl();

            int info = userService.register(name,password,age);

            if (info== 1 ){

                message= "注册成功" ;

            } else if (info == 0 ){

                message= "注册失败" ;

            } else if (info==- 2 ){

                message= "sql错误" ;

 

            }

 

            request.setAttribute( "message" , message);

            request.getRequestDispatcher( "/index.jsp" ).forward(request, response);

        }

 

    }

 

 

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request, response);

    }

 

}

6、service 层,处理逻辑,在我们写代码的时候,尽量的把逻辑处理写到service,最大的好处就是安全,毕竟写程序不只是实现功能那么简单。

接口:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

package com.proven.service;

/**

  * @author  曾炜龙  E-mail: 1501122784@qq测试数据

  * @date 创建时间:2017年6月26日 下午4:39:45 

  * @version 1.0 

  * @parameter  

  * @since  

  * @return  

  */

public interface UserService {

 

    int register(String name, String password, int age);

 

}

实现类:这里我忘记判断数据库中是否已经存在账号,判断的话很简单,就是通过账号去查数据库中是否有相同的数据,如果有了就返回给servlet:该账号已存在,如果没有的话就继续注册。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

package com.proven.service.impl;

 

import com.proven.dao.UserDao;

import com.proven.dao.impl.UserDaoImpl;

import com.proven.model.User;

import com.proven.service.UserService;

 

/**

  * @author  曾炜龙  E-mail: 1501122784@qq测试数据

  * @date 创建时间:2017年6月26日 下午4:40:01 

  * @version 1.0 

  * @parameter  

  * @since  

  * @return  

  */

public class UserServiceImpl implements UserService{

 

    @Override

    public int register(String name, String password, int age) {

        UserDao userDao = new UserDaoImpl();

 

        User user = new User();

 

        user.setName(name);

        user.setPassword(password);

        user.setAge(age);

        int info= userDao.register(user);

 

        return info;

    }

 

}

持久层:dao
接口:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

package com.proven.dao;

 

import com.proven.model.User;

 

public interface UserDao {

 

    int register(User user);

 

    /**

 

      * @param username

      * @return

      */

    //int findUserByName(String username);

 

    /**

 

      * @param user

      * @return

      */

    //int register(User user);

 

    /**

      * 登录方法

      * @param username

      * @param password

      * @return

      */

 

 

}

实现类:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

package com.proven.dao.impl;

 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import com.proven.dao.UserDao;

import com.proven.model.User;

 

 

public class UserDaoImpl implements UserDao {

 

    @Override

    public int register(User user) {

        PreparedStatement pstmt= null ;

        Connection conn = null ;

          try {   

                //加载MySql的驱动类   

                Class.forName( "com.mysql.jdbc.Driver" ) ;   

                } catch (ClassNotFoundException e){   

                System.out.println( "找不到驱动程序类 ,加载驱动失败!" );   

                e.printStackTrace() ;   

                }   

 

          String url = "jdbc:mysql://localhost:3306/nokuangjia" ;    

              String username = "root" ;   

              String password = "" ; 

 

              String sql = "insert into t_t_user values(null,?,?,?)" ;

              try {

                  conn = DriverManager.getConnection(url,username,password);

                  pstmt = conn.prepareStatement(sql) ;  

                  pstmt.setString( 1 ,user.getName() );

                  pstmt.setString( 2 , user.getPassword());

                  pstmt.setInt( 3 , user.getAge());

                  int info = pstmt.executeUpdate();

                  return info;

            } catch (SQLException e) {

                  System.out.println( "数据库连接失败!" );  

                e.printStackTrace();

                return - 2 ;

            } finally {

                try {

                    pstmt.close();

                } catch (SQLException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

                try {

                    conn.close();

                } catch (SQLException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

 

    }

/*

    public int findUserByName(String username) {

 

        QueryRunner qr = new QueryRunner(DBUtils.getDataSource());

        String sql = "select * from user where username = ?";

        try {

            User user = qr.query(sql, new BeanHandler<User>(User.class),

                    username);

            if (user == null) {

 

                return 1;

            } else {

 

                return -1;

            }

        } catch (SQLException e) {

            e.printStackTrace();

            return -2;

        }

    }

 

    public int register(User user) {

        return 0;

    }*/

 

/*  public int register(User user) {

        // 浣跨敤DBUtils灏唘ser瀵硅薄鍏ュ簱

        QueryRunner qr = new QueryRunner(DBUtils.getDataSource());

 

        String sql = "insert into t_t_user values(null,?,?,?)";

 

        try {

            return qr.update(sql, user.getName(), user.getPassword(),

                    user.getAge());

        } catch (SQLException e) {

            e.printStackTrace();

            return -2;

        }

 

    }

 

    */

 

}

在这里代码就全部写好。经过测试,运行良好!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://blog.csdn.net/qq_33096743/article/details/73744189

查看更多关于Java web实现简单注册功能的详细内容...

  阅读:14次