Java ist eine einfache Webanwendung. Login und Registrierung

Guten Tag allerseits.


Dieser Artikel richtet sich an Anfänger in der Welt von Web und Java. Wir werden uns die Standardarchitektur fßr Webanwendungen ansehen und ein kleines Projekt von Grund auf neu erstellen.


Wir werden Spring (Huge Web Framework) verwenden, aber zumindest. Wenn Sie noch keine Erfahrung mit der Verwendung haben und sofort versuchen, alle Funktionen zu nutzen, gibt es kein grundlegendes Verständnis, da es eine Liste von Fallstricken gibt.


Was wird die Anwendung tun?


Ich mÜchte ein kurzes und gleichzeitig nßtzliches Beispiel präsentieren. Es ist minimal geladen und am Ende kÜnnen Sie es als Vorlage verwenden.


Als ich darßber nachdachte, was die Leute bei der Entwicklung einer Webanwendung häufig zu tun haben, wurde mir klar, dass die Implementierung von Login und Registrierung sehr aufschlussreich und nßtzlich sein wird.


Den Quellcode finden Sie hier .


Was wir verwenden werden


  • Lieblings-IDE (ich benutze IntelliJ IDEA)
  • nicht bewĂślkter Kopf
  • Maven (Projektbauer)
  • JDBC (die Verbindung zwischen Java und DBMS)

Projekterstellung


Erstellen Sie ein einfaches Maven-Projekt. Wir machen alles von Grund auf neu, ohne Archetypen hinzuzufĂźgen.
Die IDE sollte eine solche Struktur erzeugen.


Bild


Und was wir sehen.


  • Java - der Hauptort, an dem die "Magie" stattfinden wird
  • resources — . ( , , front )
  • test — . ( , )
  • pom.xml — Maven. , , "" .

, IDE, - Maven.


Bild


-


, .
, .


Bild


-, , "-".


.


  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 .


Bild


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);
    }

Wir sehen, dass unsere Methoden im Controller begonnen haben, Parameter zu akzeptieren. Dies sind die Parameter, die wir in unsere Formulare schreiben. Ihre Namen mĂźssen mit den eingegebenen Namen Ăźbereinstimmen.


Fazit


Ich hoffe, dieser Artikel konnte einige Ihrer Fragen beantworten und hat dazu beigetragen, Ihren Horizont zu erweitern.


Alles eine angenehme Entwicklung.


All Articles