mardi 13 août 2019

Tomcat error in Spring Security (Spring + MySQL)

Why, when the admin wants to add a new admin, I get an error in the tomato. I kind of wrote the code correctly, you can see probably made a mistake. I want the admin to be able to add a new user and give him a username, password, role (admin or user). And also that he stored information in a database MySQL. Problem on page "AddUser.JSP"

enter image description here Tomcat Error enter image description here

AdminController

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private StudentService studentService;
    private UserService userService;

    @GetMapping("/allStudentsAdmin")
    public ModelAndView allStudentsForUser() {
        ModelAndView mv = new ModelAndView();
        List<Student> studentList = studentService.getAllStudents();
        mv.addObject("studentList", studentList);
        mv.setViewName("allStudentsAdmin");
        return mv;
    }

    @GetMapping(value = "/deleteStudent/{id}")
    public ModelAndView deleteUserById(@PathVariable Long id) {
        studentService.deleteStudentById(id);
        ModelAndView mv = new ModelAndView("redirect:/admin/allStudentsAdmin");
        return mv;
    }

    @GetMapping(value = "/editStudent/{id}")
    public ModelAndView displayEditUserForm(@PathVariable Long id) {
        ModelAndView mv = new ModelAndView("adminEditStudent");
        Student student = studentService.getStudentById(id);
        mv.addObject("headerMessage", "Редактирование студента");
        mv.addObject("student", student);
        return mv;
    }

    @PostMapping(value = "/editStudent")
    public String saveEditedUser(
            @RequestParam("id") Long id,
            @RequestParam("name") String name,
            @RequestParam("surname") String surname,
            @RequestParam("avatar") MultipartFile file) {
        try {
            studentService.updateStudent(name, surname, file, studentService.getStudentById(id));
        } catch (FileSystemException ex) {
            ex.printStackTrace();
        } catch (IOException e) {
            return "redirect:/errors";
        }

        return "redirect:/admin/allStudentsAdmin";
    }

    @GetMapping(value = "/addStudentAdmin")
    public ModelAndView displayNewUserForm() {
        ModelAndView mv = new ModelAndView("addStudentAdmin");
        mv.addObject("headerMessage", "Add Student Details");
        mv.addObject("student", new Student());
        return mv;
    }

    @PostMapping(value = "/addStudentAdmin")
    public String saveNewStudent(@RequestParam("name") @NonNull String name,
            @RequestParam("surname") @NonNull String surname,
            @RequestParam("avatar") MultipartFile file)
            throws IOException {

        Student student = new Student();
        student.setSurname(surname);
        student.setName(name);

        if (file != null && !file.isEmpty()) {
            student.setAvatar(studentService.saveAvatarImage(file).getName());
        }
        studentService.saveStudent(student);
        return "redirect:/admin/allStudentsAdmin";
    }

      @GetMapping(value = "/addUser")
    public ModelAndView displayAddUserForm() {
        ModelAndView mv = new ModelAndView("addUser");

        mv.addObject("user", new User());
        return mv;
    }

    @PostMapping(value = "/addUser")
    public String saveNewUser(@RequestParam("login") @NonNull String login,
            @RequestParam("password") @NonNull String password,
            @RequestParam("role") @NonNull String role)

            throws IOException {

        User user = new User();
        user.setPassword(password);
        user.setLogin(login);


        userService.saveUser(user);
        return "redirect:/admin/allStudentsAdmin";
    }

}

AddUser.JSP

 <body>

        <div class="add">
            <br>
            <br>
            <br>

            <br>
            <center>


                <form:form method="POST" action="${pageContext.request.contextPath}/admin/addUser" enctype="multipart/form-data">
                    <table>


                        <tr>
                            <td><label path="Login">Login</label></td>
                            <td><input type="text" name="login"/></td>
                        </tr>

                        <tr>
                            <td><label path="Password">Password</label></td>
                            <td><input type="text" name="password"/></td>
                        </tr>
                        <tr>
                            <td><select path="role" name="nubexSelect" size="3" multiple form="nubexForm">
        <option>Admin</option>
        <option>User</option>
        </select></td>



                            <td><input class="btn btn-primary" type="submit" value="Submit"></td>
                        </tr>

                    </table>
                </form:form>
            </center>
        </div>
    </body>

User.JAVA

@Entity
@Table(name = "user")
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String login;
    private String password;

    private String role;



    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    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;
    }

     public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }




    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", login='" + login + '\'' +
                ", password='" + password + '\'' +
                ", role='" + role + '\'' +
                '}';
    }
}

UserRepository.JAVA

@Repository
public interface UserRepository extends CrudRepository<User, Long>{



}

UserService.JAVA

public interface UserService {





    boolean saveUser(User user);



    User updateUser(String login, String password, String role, User targetUser) throws IOException;

}

UserServiceImpl.java

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Value("${storage.location}")

    private String storageLocation;

    private UserRepository repository;

    public UserServiceImpl() {

    }

    @Autowired
    public UserServiceImpl(UserRepository repository) {
        super();
        this.repository = repository;
    }





    @Override
    public boolean saveUser(User user) {
        try {
            repository.save(user);
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    @Override
    public User updateUser(String login, String password, String role, User targetUser)
            throws IOException {

        if (login != null && !login.equals(targetUser.getLogin())) {

            targetUser.setLogin(login);

        }

        if (password != null && !password.equals(targetUser.getPassword())) {

            targetUser.setPassword(password);

        }

         if (role != null && !role.equals(targetUser.getRole())) {

            targetUser.setRole(role);

        }



        return targetUser;

    }

SecurityConfig

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password(passwordEncoder().encode("1234")).roles("ADMIN")
                .and()
                .withUser("user").password(passwordEncoder().encode("user1234")).roles("USER")
                .and();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/**").permitAll()
                .and()
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/allStudents")
                .and()
                .logout()
                .and()
                .csrf().disable();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}




Aucun commentaire:

Enregistrer un commentaire