一个简单的Java Web应用程序的源码示例。这个例子将展示如何创建一个基本的Web应用程序,它包含用户注册和登录功能。我们将使用Spring Boot来简化开发,并且通过Thymeleaf作为模板引擎来渲染HTML页面。此外,我们还会使用Spring Security来处理用户认证。
项目结构
src
├── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── demo
│ │ ├── DemoApplication.java
│ │ ├── controller
│ │ │ ├── HomeController.java
│ │ │ └── UserController.java
│ │ ├── model
│ │ │ └── User.java
│ │ ├── repository
│ │ │ └── UserRepository.java
│ │ ├── service
│ │ │ └── UserService.java
│ │ └── security
│ │ ├── SecurityConfig.java
│ │ └── UserDetailsServiceImpl.java
│ └── resources
│ ├── static
│ ├── templates
│ │ ├── login.html
│ │ ├── register.html
│ │ └── home.html
│ └── application.properties
└── test└── java└── com└── example└── demo└── DemoApplicationTests.java
代码示例
DemoApplication.java
package com.example.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}}
HomeController.java
package com.example.demo.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;@Controller
public class HomeController {@GetMapping("/")public String home() {return "home";}}
UserController.java
package com.example.demo.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;import com.example.demo.model.User;
import com.example.demo.service.UserService;@Controller
public class UserController {private final UserService userService;@Autowiredpublic UserController(UserService userService) {this.userService = userService;}@GetMapping("/register")public String showRegistrationForm(Model model) {model.addAttribute("user", new User());return "register";}@PostMapping("/register")public String registerUser(@RequestParam String username, @RequestParam String password) {userService.saveUser(new User(username, password));return "redirect:/login";}@GetMapping("/login")public String showLoginForm() {return "login";}}
User.java
package com.example.demo.model;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;@Entity
public class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String username;private String password;// Constructors, getters and setterspublic User() {}public User(String username, String password) {this.username = username;this.password = password;}// Getters and Setters
}
UserRepository.java
package com.example.demo.repository;import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.model.User;public interface UserRepository extends JpaRepository<User, Long> {User findByUsername(String username);
}
UserService.java
package com.example.demo.service;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;@Service
public class UserService {private final UserRepository userRepository;private final BCryptPasswordEncoder passwordEncoder;@Autowiredpublic UserService(UserRepository userRepository, BCryptPasswordEncoder passwordEncoder) {this.userRepository = userRepository;this.passwordEncoder = passwordEncoder;}public void saveUser(User user) {user.setPassword(passwordEncoder.encode(user.getPassword()));userRepository.save(user);}public User findByUsername(String username) {return userRepository.findByUsername(username);}}
SecurityConfig.java
package com.example.demo.security;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/register", "/login").permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login").defaultSuccessUrl("/home", true).permitAll().and().logout().permitAll();}@Beanpublic BCryptPasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}}
UserDetailsServiceImpl.java
package com.example.demo.security;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.example.demo.model.User;
import com.example.demo.service.UserService;@Service
public class UserDetailsServiceImpl implements UserDetailsService {private final UserService userService;@Autowiredpublic UserDetailsServiceImpl(UserService userService) {this.userService = userService;}@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {User user = userService.findByUsername(username);if (user == null) {throw new UsernameNotFoundException("User not found");}return org.springframework.security.core.userdetails.User.withUsername(user.getUsername()).password(user.getPassword()).roles("USER").build();}
}
application.properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.thymeleaf.cache=false
home.html
, login.html
, register.html
这些文件应该放在src/main/resources/templates/
目录下。你可以使用Thymeleaf语法来创建这些HTML页面。例如,login.html
可以像这样:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>Login</title>
</head>
<body><h1>Login</h1><form th:action="@{/login}" method="post"><div><label> User Name : <input type="text" name="username"/> </label></div><div><label> Password: <input type="password" name="password"/> </label></div><div><input type="submit" value="Sign In"/></div></form>
</body>
</html>
register.html
和home.html
也应相应地设计,以匹配你的应用逻辑。
运行项目
要运行这个项目,确保你已经安装了JDK和Maven。然后在命令行中进入项目的根目录并执行以下命令:
mvn spring-boot:run
这将会启动Spring Boot应用程序,并且你应该能够在浏览器中访问http://localhost:8080
来查看你的Web应用程序。
总结
上述代码是一个非常基础的Java Web应用程序示例,它实现了用户注册和登录的功能。你可以在此基础上扩展更多的功能,比如添加更多页面、实现用户角色管理、集成数据库等。