mercredi 7 août 2019

Registration Account in my WebSite (Spring Security + HTML)

I created a project (website). Admin or user can enter the website through the username and password. Now when I go to the site through the admin, I can create a new account. Creating a new account, I can give him a username and password + role (admin or user). You can see, I wrote everything correctly, maybe something is missing.

AddUser.JSP

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
        <title>Home</title>

    </head> 
    <body>

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

            <br>
            <center>
                <h1>${headerMessage}</h1>

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

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

                        <tr>
                            <td><label path="Surname">Surname</label></td>
                            <td><input type="text" name="surname"/></td>
                        </tr>
                        <tr>
                            <td><select name="select" size="3" multiple>
                                    <option selected value="s1">Admin</option>
                                    <option value="s2">User</option>

   </select></td>
                            <td>
                                <input type="text" name="Role"/>
                            </td>

                        </tr>
                        <tr>
                            <td><input class="btn btn-primary" type="submit" value="Save"></td>
                        </tr>
                    </table>
                </form:form>
            </center>
        </div>
    </body>
</html>

AdminDecorator.JSP

</head>
<!DOCTYPE html>
<body>
  <div id="container">
    <div id="header">


    </div>
    <div id="nav">
        <ul>
            <li><a href="${pageContext.request.contextPath}/"><span>Главная</span></a></li>

            <li class="dropdown"><a href="${pageContext.request.contextPath}/allStudents"><span>Students</span></a>
                <ul>
                    <li><a href="${pageContext.request.contextPath}/allStudents"><span>Student List</span></a></li>
                    <sec:authorize access="hasRole('ADMIN') || hasRole('USER')">
                    <li><a href="${pageContext.request.contextPath}/addStudent"><span>Add Student</span></a></li>
                    </sec:authorize>
                    <sec:authorize access="hasRole('ADMIN')"> 
                    <li><a href="${pageContext.request.contextPath}/addUser"><span>Add User</span></a></li>
                    </sec:authorize>
                </ul>
            </li>
            <li><a><span>О нас </span></a></li> 
            <sec:authorize access="!isAuthenticated()"> 
            <li><a href="${pageContext.request.contextPath}/logout"><span>Выйти</span></a></li>
             </sec:authorize>
        </ul>
    </div>
</div>

        <sitemesh:write property='body'/>
    <jsp:include page="/WEB-INF/template/admintemplate.jsp"/>  
    </body>
</html>

AdminController.JAVA

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

    @Autowired
    private StudentService studentService;

    @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("addStudentAdmin");
        mv.addObject("headerMessage", "Add Student Details");
        mv.addObject("student", new Student());
        return mv;
    }

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

            throws IOException {

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


        studentService.saveStudent(student);
        return "redirect:/admin/allStudentsAdmin";
    }

}

User.JAVA

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

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String name;
    private String surname;

    private String role;



    public long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

     public String getRole() {
        return role;
    }

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




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

UserRepository

package adil.java.schoolmaven.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;


import adil.java.schoolmaven.entity.User;

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

UserService

package adil.java.schoolmaven.service;

import adil.java.schoolmaven.entity.User;

import java.io.IOException;


public interface UserService {





    boolean saveUser(User user);



    User updateUser(String name, String surname, String role, User targetUser) throws IOException;

}

UserServiceImpl

package adil.java.schoolmaven.service;

@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 updateStudent(String name, String surname, String role, User targetUser)
            throws IOException {

        if (name != null && !name.equals(targetUser.getName())) {

            targetUser.setName(name);

        }

        if (surname != null && !surname.equals(targetUser.getSurname())) {

            targetUser.setSurname(surname);

        }

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

            targetUser.setRole(role);

        }



        return targetUser;

    }



}




Aucun commentaire:

Enregistrer un commentaire