祝大家有美好的一天。
本文面向Web和Java领域的初学者。我们将研究标准的Web应用程序体系结构,并从头开始做一个小项目。
我们将使用Spring(大型Web框架),但至少要使用。如果您没有使用过的经验,而是立即尝试使用所有功能,那么将没有基本的了解,因为这里有一系列陷阱。
该应用程序将做什么?
我想提供一个简短且同时有用的示例。它的负载最少,到最后,您可以将其用作模板。
考虑到人们在开发Web应用程序时经常要面对的事情,我意识到登录和注册的实现将非常具有启发性和实用性。
您可以在此处找到源代码。
我们将使用什么
- 最喜欢的IDE(我使用IntelliJ IDEA)
- 不乌云密布的头
- Maven(项目构建者)
- JDBC(Java和DBMS之间的链接)
项目创建
创建一个简单的Maven项目。我们从头开始做所有事情,而无需添加任何原型。
IDE应该生成这样的结构。
![图片](https://habrastorage.org/getpro/habr/post_images/581/a94/6fb/581a946fb4f449443895d6cd5b8fd389.png)
因此,我们所看到的。
- java-发生“魔术”的主要位置
- resources — . ( , , front )
- test — . ( , )
- pom.xml — Maven. , , "" .
, IDE, - Maven.
![图片](https://habrastorage.org/getpro/habr/post_images/e66/5bc/d15/e665bcd1551e2aeee1f2f12cdbf86f8e.png)
-
, .
, .
![图片](https://habrastorage.org/webt/9x/_7/vl/9x_7vlwwr3sprbz9lmuiwf1udpw.png)
-, , "-".
.
- Browser — . Frontend. Backend — , . .
- Controller — Frontend, . , , .
- Service — - . . .
- DAL(data access layer) — . , , , .
- 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 .
@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 .
![图片](https://habrastorage.org/getpro/habr/post_images/27d/b58/179/27db58179bd607b6fd873b8f7b87641e.png)
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.
FileInputStream fis;
Properties property = new Properties();
application.properties, properties.
fis = new FileInputStream("src/main/resources/application.properties");
property.load(fis);
getConnection.
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.javapublic 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.
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.
PreparedStatement pr = con.prepareStatement("SELECT * FROM DATABASE.User where LOGIN=?");
pr.setString(1 , login);
ResultSet resultSet = pr.executeQuery();
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
@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.
:
- "login" .
- 1 , .
- 2 , "life is beautiful"
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
<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>
<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.
@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.
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);
}
我们看到控制器中的方法开始接受参数。这些是我们在表单中编写的参数。它们的名称必须与输入的名称匹配。
结论
我希望本文能够回答您的一些问题,并帮助您扩大视野。
一切都令人愉快。