如何把from表单的注册信息提交到controller中并存入数据库,给出具体代码演示
时间: 2023-06-02 18:04:09 浏览: 57
很高兴为您解答,以下是您所需的代码演示,假设您使用的是Spring MVC框架:
1.前端页面HTML代码:
<form action="/register" method="POST">
<div>
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required>
</div>
<div>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required>
</div>
<button type="submit">注册</button>
</form>
2.Controller处理器方法代码:
@Controller
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/register")
public String register(@ModelAttribute User user) {
userService.save(user);
return "redirect:/login";
}
}
3.Service业务逻辑代码:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public void save(User user) {
userRepository.save(user);
}
}
4.User实体类代码:
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String username;
@Column(nullable = false)
private String password;
// 省略getter和setter方法
}
通过以上代码演示,当用户在前端页面填写注册信息并提交时,会进入Controller的register方法进行处理,然后将用户信息存入数据库中。同时,如果用户没有填写必填字段,则会给予提示。