Java is a simple web application. Login and registration

Good day to all.


This article is intended for beginners in the world of Web and Java. We will look at the standard web application architecture and make a small project from scratch.


We will use Spring (Huge Web Framework), but at a minimum. If you do not have previous experience in using and immediately try to use all the functionality, then there will be no basic understanding, since there is a list of pitfalls.


What will the application do?


I want to present a short and at the same time useful example. It is minimally loaded and by the end you can use it as a template.


Thinking about what people often have to face when developing a web application, I realized that the implementation of login and registration will be quite revealing and useful.


You can find the source code here .


What we will use


  • favorite IDE (I use IntelliJ IDEA)
  • not clouded head
  • Maven (project builder)
  • JDBC (the link between Java and DBMS)

Project creation


Create a simple Maven project. We do everything from scratch, without adding any archetypes.
The IDE should generate such a structure.


image


And so what we see.


  • java - the main place where the "magic" will take place
  • resources — . ( , , front )
  • test — . ( , )
  • pom.xml — Maven. , , "" .

, IDE, - Maven.


image


-


, .
, .


image


-, , "-".


.


  1. Browser — . Frontend. Backend — , . .
  2. Controller — Frontend, . , , .
  3. Service — - . . .
  4. DAL(data access layer) — . , , , .
  5. Database — , .


- .


, H2.


, -. User.


create table DATABASE.USER
(
    ID INT auto_increment,
    NAME VARCHAR not null,
    SURNAME VARCHAR not null,
    LOGIN VARCHAR not null,
    PASSWORD VARCHAR not null,
    constraint USER_PK
        primary key (ID)
);

Spring


java.


java com.zuk( ), App main .


Spring. , @SpringBootApplication Spring, , . Spring .


//com.zuk.App
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

pom.xml.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.zuk</groupId>
    <artifactId>LoginAndRegistration</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>
    </dependencies>

</project>

, Spring .


image


Spring 8080. , http://localhost:8080.



, Spring , .


application.properties src.main.resources.


-.


spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:~/test

spring.datasource.username=sa
spring.datasource.password=

Spring, .


, .
, . , . Spring .
.


java.com.zuk.connection ConnectionManager, , .
properties, FileInputStream.


//ConnectionManager
FileInputStream fis;
Properties property = new Properties();

application.properties, properties.


//ConnectionManager
fis = new FileInputStream("src/main/resources/application.properties");
property.load(fis);

getConnection.


  //ConnectionManager
  public Connection getConnection() {
            Connection connection = null;
            try {
                connection = DriverManager.getConnection(property.getProperty("spring.datasource.url"),property.getProperty("spring.datasource.username"),property.getProperty("spring.datasource.password"));
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return connection;
        }

, App.


, .


conn2: url=jdbc:h2:~/test user=SA

, pom.


<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.200</version>
</dependency>

POJO (Plain Old Java Objects)


, , .


, , . , , , . , , . POJO.


, User.
.


java.com.zuk.entity, User.
, .


User.java
public class User {

    private int id;
    private String name;
    private String surname;
    private String login;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

DAL


, , DAL. , . DAO (data access object) — - .


java.com.zuk.dao UserDao ( ). findByLogin, save.


public interface UserDao {
    User findByLogin(String login);
    Boolean save(User user);
}

, java.com.zuk.dao.impl,
UserDaoImpl.
— , , (, ).


public class UserDaoImpl implements UserDao {
    @Override
    public User findByLogin(String login) {
        return null;
    }

    @Override
    public Boolean save(User user) {
        return null;
    }
}

findByLogin. SQL .


SELECT  * from DATABASE.User where LOGIN=login

User.


, null.


//UserDaoImpl
ConnectionManager cm = new ConnectionManager();
Connection con = cm.getConnection();

@Override
    public User findByLogin(String login) {
        User user = null;
        if (con != null) {
              //..  
        }
        return user;
     }

if , SQL , user.


//findByLogin
PreparedStatement pr = con.prepareStatement("SELECT * FROM DATABASE.User where LOGIN=?");
pr.setString(1 , login);
ResultSet resultSet = pr.executeQuery();//return sql result
if(resultSet.next()) {
       user = new User();
       user.setId(resultSet.getInt("ID"));
       user.setName(resultSet.getString("NAME"));
       user.setSurname(resultSet.getString("SURNAME"));
       user.setLogin(login);
       user.setPassword(resultSet.getString("PASSWORD"));
       return user;
}
 pr.close();
 con.close();

.


save .
.


save
//UserDaoImpl
@Override
    public Boolean save(User user) {
        ConnectionManager cm = new ConnectionManager();
        Connection con = cm.getConnection();
        if (con != null) {
            try {
                PreparedStatement pr = con.prepareStatement("insert into DATABASE.USER (NAME,SURNAME,LOGIN,PASSWORD) values (?,?,?,?)");
                pr.setString(1,user.getName());
                pr.setString(2,user.getSurname());
                pr.setString(3,user.getLogin());
                pr.setString(4, DigestUtils.md5DigestAsHex((user.getPassword()).getBytes()));
                pr.executeUpdate();
                pr.close();
                con.close();
                return true;
            } catch (SQLException e) {
                e.printStackTrace();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

Service


-. java.com.zuk.service, UserService : login, registration. UserServiceImpl java.com.zuk.service.impl, UserService.


public class UserServiceImpl implements UserService {
    @Override
    public String login(User user) {
        return null;
    }

    @Override
    public String registration(User user) {
        return null;
    }
}

login.
:


  1. "login" .
  2. 1 , .
  3. 2 , "life is beautiful"

//UserServiceImpl
UserDaoImpl userDao = new UserDaoImpl();
    @Override
    public String login(User user) {
        User findUser = userDao.findByLogin(user.getLogin());
        if(findUser!=null){
            if(DigestUtils.md5DigestAsHex((user.getPassword()).getBytes()).equals(findUser.getPassword())){
                return "life is beautiful"  + "your Id: " + findUser.getId();
            }
        }
        return "do not give up";
    }

.


registration
 @Override
    public String registration(User user) {
        User findUser = userDao.findByLogin(user.getLogin());
        if(findUser==null) {
            userDao.save(user);
            return "life is beautiful";
        }
        return "this login is not available";
    }

Controller


, - .
java.com.zuk.controller Controller. "" RestController, Spring , Rest Controller.
, @RequestMapping("/").


@RestController
public class Controller {
    @RequestMapping("/")
    String main() {
        return "Hello from Controller";
    }
}

, http://localhost:8080.
"Hello from Controller".


html . , .
resources, resources.static.


html
<!--loginFrom.html-->
<html>
<title>Login</title>
<body>
<form action="http://localhost:8080/login"  method="post">
    <input type="text" required name="login" placeholder="login" />
    <input type="password" required name="password" placeholder="password" />
    <button>login</button>
</form>
<a href="http://localhost:8080/registrationForm">don't have account</a>
</body>
</html>

<!--registrationForm.html-->
<html>
<title>Registration</title>
<body>
<form action="http://localhost:8080/registration"  method="post">
    <input type="text" required name="name" placeholder="name" />
    <input type="text" required name="surname" placeholder="surname" />
    <input type="text" required name="login" placeholder="login" />
    <input type="password" required name="password" placeholder="password" />
    <button>registration</button>
</form>
<a href="http://localhost:8080/loginForm">already have account</a>
</body>
</html>

, http://localhost:8080/loginForm, http://localhost:8080/registrationForm html .
, /loginForm, /registrationForm html. ModelAndView.


//Controller
 @RequestMapping("/loginForm")
    ModelAndView loginForm() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("loginForm.html");
        return modelAndView;
    }

    @RequestMapping("/registrationForm")
    ModelAndView registrationForm() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("registrationForm.html");
        return modelAndView;
    }

, action http://localhost:8080/login registration, .
service.


//Controller
UserServiceImpl userService = new UserServiceImpl();
//..
 @PostMapping("/login")
    String login(@RequestParam String login,@RequestParam String password) {
        User user = new User();
        user.setLogin(login);
        user.setPassword(password);
        return userService.login(user);
    }

    @PostMapping("/registration")
    String registration(@RequestParam String name,@RequestParam String surname, @RequestParam String login,@RequestParam String password) {
        User user = new User();
        user.setName(name);
        user.setSurname(surname);
        user.setLogin(login);
        user.setPassword(password);
        return userService.registration(user);
    }

We see that our methods in the Controller began to accept parameters. These are the parameters that we write in our forms. Their names must match the names input.


Conclusion


I hope this article was able to answer some of your questions, and helped expand your horizons.


All a pleasant development.


All Articles