BE Study 6th

 HomeController was too basic. Let's take a look at harder one: CreatePostController

It must be a controller about creating a post.


@Controller

@Loggable

@Controller is an annotation that tells this is a controller and @Loggable is an annotation that enables logging of this class.


public class CreatePostController {

defining this class CreatePostController


    private static final Logger log = LoggerFactory.getLogger(CreatePostController.class);

Logger Declaration.


    private static final String MODEL_ATTRIBUTE_POST = "post";

    private final PostService postService;

Attributes of the class. Let's see how does it work.


    public CreatePostController(PostService postService) {

        this.postService = postService;

    }

Consturctor.


    @GetMapping("/posts/new")

Mapping for Get, url of /posts/new


    @AnyAuthenticatedUser

Guess this is an custom annotation. There is a file named AnyAuthenticatedUser.java and it looks like


@Target({ElementType.METHOD, ElementType.TYPE})

@Retention(RetentionPolicy.RUNTIME)

@Inherited

@Documented

@PreAuthorize("isAuthenticated()")

public @interface AnyAuthenticatedUser {}


    public String createPost(

            @Valid @ModelAttribute(MODEL_ATTRIBUTE_POST) CreatePostRequest request,

            BindingResult bindingResult,

            @CurrentUser User loginUser,

            RedirectAttributes redirectAttributes) {

method named createPost


        if (bindingResult.hasErrors()) {

            return "posts/add-post";

        }

checks if bindingResult has errors. if true, returns "posts/add-post.html" using template engine.


var createPostRequest = new CreatePostRequest(

                request.title(), request.url(), request.content(), request.categoryId(), loginUser.getId());

if not, create an instance of createPostRequest.

public record CreatePostRequest(

        @NotEmpty(message = "Title should not be blank") String title,

        String url,

        @NotEmpty(message = "Content should not be blank") String content,

        @NotNull(message = "CategoryId should not be blank") Long categoryId,

        Long createdUserId) {}

it looks like above. Then what's the 'record'? Record is java's function made to easily define a class. 'Record' classes are 'final'(it does not have setter()) and all of its headers are defined private final.

Thus, the above code is same as

public class CreatePostRequest

{

    @NotEmpty(message = "Title should not be blank")

    private final String title

    @NotEmpty(message = "Content should not be blank")

    private final String url

    private final String content

    @NotNull(message = "CategoryId should not be blank")

    private final Long categoryId

    private final Long createdUserId

    public CreatePostRequest(

        String title,

        String url,

        String content,

        Long categoryId,

        Long createdUserId)

    {

    this.title = title    

    this.url = url

    this.content = content

    this.categoryId = categoryId

    this.createdUserId = createdUserId

    }

    public String getTitle()

    {...}

    public String getUrl()

    ....

}



        Post post = postService.createPost(createPostRequest);

create an instance of post using the instance createPostRequest. According to PostService.java, 

    public Post createPost(CreatePostRequest createPostRequest) {

        log.info("Create post with title={}", createPostRequest.title());

        Category category = new Category(createPostRequest.categoryId());

        User user = new User(createPostRequest.createdUserId());

        Post post = new Post(

                null,

                createPostRequest.title(),

                createPostRequest.url(),

                createPostRequest.content(),

                category,

                user,

                Set.of(),

                dateTimeNow(),

                null);

        return postRepository.save(post);

    }

so, this code must be about making a post and saving to the DB via postRepository. According to JooqPostRepository.java

    public Post save(Post post) {

        PostsRecord postsRecord = this.dsl

                .insertInto(POSTS)

                .set(POSTS.TITLE, post.getTitle())

                .set(POSTS.URL, post.getUrl())

                .set(POSTS.CONTENT, post.getContent())

                .set(POSTS.CAT_ID, post.getCategory().getId())

                .set(POSTS.CREATED_BY, post.getCreatedBy().getId())

                .set(POSTS.CREATED_AT, post.getCreatedAt())

                .returning(POSTS.ID)

                .fetchSingle();

        return findById(postsRecord.getId()).orElseThrow();

    }



        log.info("Post saved successfully with id: {}", post.getId());

log it.


        redirectAttributes.addFlashAttribute("message", "Post saved successfully");

This is a function of the Spring. It is adding the given parameter is saved into the browser's session. After it is redirected, it is added to the redirected page's model's attribute and then removed.


        return "redirect:/c/" + post.getCategory().getSlug();

be redirected to "redirect:/c/" + post.getCategory().getSlug()

댓글

이 블로그의 인기 게시물

Interface of Java

Data Analytics Overview(OLTP vs OLAP)

Leetcode