如何找出寄存器的错误?

rryofs0p  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(308)

所以我使用thymeleaf、spring和mysql来开发一个在线商店程序。我真的很想知道为什么当我在register部分引入数据时,它不会在sql数据库中注册。
这是注册页面:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.w3.org/1999/xhtml" lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create Account</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
    <link rel="stylesheet" href="../static/registerStyle.css" ;>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar sticky-top navbar-dark bg-dark">
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo03"
            aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <a href="index.html" class="navbar-brand"><h2 style="font-style: italic">Online Store</h2></a>

    <div class="collapse navbar-collapse" id="navbarTogglerDemo03">
        <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
        </ul>

        <span style="color: white" sec:authorize="isAuthenticated()">
            | Logged as: <span  sec:authentication=" name"></span> |
            Roles: <span sec:authentication="principal.authorities"></span> |
            <a id="logout" class="btn btn-outline-light rounded-pill" th:href="@{/logout}">Logout</a>
        </span>

        <!-- Facebook -->
        <a href="https://www.facebook.com" style="color: white; margin-left: 16px" class="fa fa-facebook"></a>
        <!-- Instagram -->
        <a href="https://www.instagram.com" style="color:  white; margin-left: 16px" class="fa fa-instagram"></a>
        <!-- Twitter -->
        <a href="https://www.twitter.com" style="color: white; margin-left: 16px" class="fa fa-twitter"></a>

        <!-- Sign In -->
        <a id="login" class="nav-link btn btn-outline-light rounded-pill" href="login.html" style="margin-left: 16px" >Login</a>
        <!-- Create Account -->
        <a class="nav-link btn btn-outline-light rounded-pill" href="register.html" style="margin-left: 16px">Create
            Account</a>
        <!-- Cart -->
        <a href="#" style="margin-left: 26px; margin-right: 15px">
            <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-basket3-fill" fill="white"
                 xmlns="http://www.w3.org/2000/svg">
                <path fill-rule="evenodd"
                      d="M5.757 1.071a.5.5 0 0 1 .172.686L3.383 6h9.234L10.07 1.757a.5.5 0 1 1 .858-.514L13.783 6H15.5a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5H.5a.5.5 0 0 1-.5-.5v-1A.5.5 0 0 1 .5 6h1.717L5.07 1.243a.5.5 0 0 1 .686-.172z"/>
                <path d="M2.468 15.426L.943 9h14.114l-1.525 6.426a.75.75 0 0 1-.729.574H3.197a.75.75 0 0 1-.73-.574z"/>
            </svg>
        </a>
    </div>
</nav>
<div class="register">
    <div>
        <h1>User Registration </h1>
    </div>
<form  th:action="@{/user/register}" th:object="${userRegister}" method="post">
    <div>
        <label for="username"></label>
        <input type="text" th:field="${userRegister.username}" id="username" placeholder="User Name">
        <span th:if="${#fields.hasErrors('username')}" th:errors="${userRegister.username}"></span>
    </div>
    <div>
        <label for="email"></label>
        <input type="email" th:field="${userRegister.email}" id="email" placeholder="Email">
        <span th:if="${#fields.hasErrors('email')}" th:errors="${userRegister.email}"></span>
    </div>
    <div class="place">
        <label for="country"></label>
        <input type="text" th:field="${userRegister.address.country}" id="country" placeholder="Country">

        <label for="city"></label>
        <input type="text" th:field="${userRegister.address.city}" id="city" placeholder="City">
    </div>
    <div>
        <label for="street"></label>
        <input type="text" th:field="${userRegister.address.street}" id="street" placeholder="Street">

        <label for="zipcode"></label>
        <input type="text" th:field="${userRegister.address.zipCode}" id="zipcode" placeholder="Zip Code">
    </div>
    <div>
        <label for="password"></label>
        <input type="password" th:field="${userRegister.password}" id="password" placeholder="Password">
        <span th:if="${#fields.hasErrors('password')}" th:errors="${userRegister.password}"></span>
    </div>
    <div>
        <label for="confirmPassword"></label>
        <input type="password" th:field="${userRegister.confirmPassword}" id="confirmPassword" placeholder="Confirm Password">
        <span th:if="${#fields.hasErrors('confirmPassword')}" th:errors="${userRegister.confirmPassword}"></span>
    </div>
    <div>
        <input type="submit" value="Register">
    </div>
Already have an account? Log in <a href="login.html">here!</a>
</form>
</div>
</body>
</html>

这是安全配置:

package com.sda.onlinestore.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.annotation.Resource;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource(name = "userService")
    private UserDetailsService userDetailsService;
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(encoder());
    }
    @Bean
    public BCryptPasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }
    // roles admin allow to access /admin/**
    // roles user allow to access /user/**
    // custom 403 access denied handler
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/", "/home", "/about","/register","/user/register" ,"/css/**" , "/login").permitAll()
                .antMatchers("/viewUserAccounts").hasAnyRole("ADMIN")
                .antMatchers("/admin/**").hasAnyRole("ADMIN")
                .antMatchers("/user/**").hasAnyRole("USER")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .failureUrl("/login?error")
                    .defaultSuccessUrl("/index", true)
                .and()
                .logout()
                    .invalidateHttpSession(true)
                    .clearAuthentication(true)
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                    .logoutSuccessUrl("/index").permitAll();

    }
}

用户帐户存储库:

package com.sda.onlinestore.repository;

import com.sda.onlinestore.entity.UserAccount;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface UserAccountRepository extends JpaRepository<UserAccount, Long> {

    Optional<UserAccount> findUserAccountByUsername(String username);
}

用户MVC控制器:

package com.sda.onlinestore.mvcController;

import com.sda.onlinestore.dto.AddressDto;
import com.sda.onlinestore.dto.UserAccountDto;
import com.sda.onlinestore.entity.Role;
import com.sda.onlinestore.entity.UserAccount;
import com.sda.onlinestore.service.UserAccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Optional;

@Controller
public class UserAccountMVCController {

    private final UserAccountService userAccountService;

    @Autowired
    public UserAccountMVCController(UserAccountService userAccountService) {
        this.userAccountService = userAccountService;
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }
    @RequestMapping("/login-error")
    public String loginError(Model model) {
        model.addAttribute("loginError", true);
        return "login";
    }

    @GetMapping(path = "/register")
    public String showRegisterForm(Model model) {
        model.addAttribute("userRegister", new UserAccountDto());
        return "register";
    }

    @PostMapping(path = "/user/register")
    public String registerUser(@ModelAttribute("userRegister") @Valid UserAccountDto userAccountDto, BindingResult result) {
        Optional<UserAccount> optUserAccount = this.userAccountService.findUserAccountByUsername(userAccountDto.getUsername());
        if (optUserAccount.isPresent()) {
            result.rejectValue("username", null, "Username already exists.");
        }
        if (!userAccountDto.getPassword().equals(userAccountDto.getConfirmPassword())) {
            result.rejectValue("password", null, "Passwords are not matching!");
        }
        if (result.hasErrors()) {
            return "register";
        }
        userAccountService.addUserAccount(userAccountDto);
        return"index";
    }

    @GetMapping(path = "/viewUserAccounts")
    public String viewUserAccounts(Model model) {
        model.addAttribute("users", this.userAccountService.getUserAccounts());
        return "userAccount-list";
    }

    @GetMapping(path = "/userAccount/edit/{id}")
    public String showEditPage(@PathVariable("id") Long id, Model model) {
        model.addAttribute("userAccount", this.userAccountService.findUserAccountById(id));
        return "edit-userAccount";
    }

    @GetMapping(path = "/userAccount/delete/{id}")
    public String deleteUserAccountById(@PathVariable("id") Long id, Model model) {
        this.userAccountService.deleteUserAccountById(id);
        return "redirect:/viewUserAccounts";
    }

    @PostMapping(path = "/userAccount/update")
    public String editUserAccount(@ModelAttribute("userAccount") @Valid UserAccount userAccount, BindingResult result) {
        if (result.hasErrors()) {
            return "edit-userAccount";
        }
        this.userAccountService.saveUserAccount(userAccount);
        return "redirect:/viewUserAccounts";
    }

}

这个项目很大,我不知道你还需要什么。请帮帮我。

eqqqjvef

eqqqjvef1#

基本上,当我们将字段数据绑定到thymeleaf中的对象时,我们使用星号'',比如the:field=“{yourproperty}”。像这里一样,您希望将用户名绑定到userregister对象,那么对于每个字段,您必须这样做

<input type="text" th:field="*{username}" id="username" placeholder="User Name">

您不需要像userregistry.username那样编写它,因为它会自动将它绑定到对象。
让我知道这是否有效。

相关问题