一个完整的社交网站系统需要涉及到用户登录、发布动态、关注、评论、私信等各方面。这里提供一个简单的实现示例,供参考。
前端使用Vue框架,以下是部分代码示例:
登录页:
首页:
{{ post.title }}
{{ post.content }}
后端使用Spring Boot框架,以下是部分代码示例:
登录Controller:
@RestController
@RequestMapping("/api")
public class LoginController {
@Autowired
private UserService userService;
@PostMapping("/login")
public String login(@RequestBody User user) {
if (userService.checkUser(user)) {
return "success";
} else {
return "failure";
}
}
}
UserService类:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public boolean checkUser(User user) {
User userInDb = userRepository.findByUsername(user.getUsername());
if (userInDb != null && userInDb.getPassword().equals(user.getPassword())) {
return true;
} else {
return false;
}
}
}
PostController类:
@RestController
@RequestMapping("/api")
public class PostController {
@Autowired
private PostService postService;
@GetMapping("/posts")
public List getPosts() {
return postService.getAllPosts();
}
@PostMapping("/posts")
public void addPost(@RequestBody Post post) {
postService.addPost(post);
}
}
PostService类:
@Service
public class PostService {
@Autowired
private PostRepository postRepository;
public List getAllPosts() {
return postRepository.findAll();
}
public void addPost(Post post) {
postRepository.save(post);
}
}
PostRepository类:
public interface PostRepository extends JpaRepository {
}
UserRepository类:
public interface UserRepository extends JpaRepository {
User findByUsername(String username);
}
Post类:
java
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private String content;
private LocalDateTime createTime;
// 省略getter和setter方法,以及构造方法等
}
User类:
java
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username;
private String password;
// 省略getter和setter方法,以及构造方法等
}
使用MySQL数据库,以下是部分代码示例:
创建数据库:
sql
CREATE DATABASE social;
创建用户表:
sql
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
创建动态表:
sql
CREATE TABLE `post` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
`content` text,
`create_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
以上是简单的实现示例,实际社交网站系统需要考虑更复杂的业务逻辑和安全性问题。完整的实现可参考相关开源项目,例如:https://github.com/b3log/symphony