0

С помощью этого видео пытаюсь сделать аналогичную корзину покупок. На данном этапе пытаюсь получить информацию о товаре(тура) в корзине пользователя. Дошел до 35 минуты введите сюда описание ссылки

У меня есть Модель, которая соединяет Тур и Пользователя

@Entity 
@Table(name = "cart_items") public class CartItem {  
@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY)  
private int id;
     
@ManyToOne  @JoinColumn(name = "tour_id")  
private Tour tour;
     
@ManyToOne  @JoinColumn(name = "user_id")  
private User user;
@Column(name = "order_date")  private Date date=new Date(); 
//getters and setters 
}

Обычная модель Пользователя

package com.zaitsava.springboot_touristsite.entity;

import javax.persistence.*;
import java.util.Set;


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

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(name = "firstname")
    private String firstname;

    @Column(name = "lastname")
    private String lastname;

    @Column(name = "patronymic")
    private String patronymic;

    @Column(name = "email")
    private String email;

    @Column(name = "phone")
    private String phone;

    @Column(name = "password")
    private String password;

    @Column(name = "active")
    private int active;

    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name="user_role", joinColumns=@JoinColumn(name="user_id"),
            inverseJoinColumns=@JoinColumn(name="role_id"))
    private Set<Role> roles;
    //gettes and setters
}

Сервис

import com.zaitsava.springboot_touristsite.entity.CartItem;
import com.zaitsava.springboot_touristsite.entity.User;
import com.zaitsava.springboot_touristsite.repository.CartItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ShoppingCartService {
    @Autowired
    private CartItemRepository cartItemRepository;

    public List<CartItem> cartItemList(User user){
        return cartItemRepository.findByUser(user);
    };
}

и Репозиторий:

package com.zaitsava.springboot_touristsite.repository;

import com.zaitsava.springboot_touristsite.entity.CartItem;
import com.zaitsava.springboot_touristsite.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
public interface CartItemRepository extends JpaRepository<CartItem,Integer> {
    public List<CartItem> findByUser(User user);
}

Все хорошо добавляется и записывается в бд через Тест введите сюда описание изображения

Когда дошло дело до контроллера показа товара, начались проблемы. Из-за того, что в реализации автора расширяется класс User с разными методами, я не могу получить текущего пользователя в контроллере. Я пытался сделать

package com.zaitsava.springboot_touristsite.controller;

import com.zaitsava.springboot_touristsite.entity.CartItem;
import com.zaitsava.springboot_touristsite.entity.CurrentUser;
import com.zaitsava.springboot_touristsite.entity.User;
import com.zaitsava.springboot_touristsite.service.ShoppingCartService;
import com.zaitsava.springboot_touristsite.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;


import java.util.List;

@Controller
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService cartService;
    @Autowired
    private UserServiceImpl userService;

    @GetMapping("/cart")
    public String showCart(Model model,@CurrentUser User user){

        if(user==null) System.out.println("User is null");

        List<CartItem> cartItemList=cartService.cartItemList(user);
        model.addAttribute("cartItems",cartItemList);
        return "user/cart";
    }


}

Через аннотацию теккущего пользователя

package com.zaitsava.springboot_touristsite.entity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import java.lang.annotation.*;

@Target({ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AuthenticationPrincipal
public @interface CurrentUser {}

Однако я получаю пользователя null, даже если захожу через юзера с id 4. Также пытался через параметр

 public String showCart(Model model,Principal principal){
        Authentication authentication = (Authentication) principal;
        User user= (User) authentication.getPrincipal();
        //остальной код
}

но тогда мне выскакивает ошибка о неправильном преобразовании типа

Обновлено Добавлены настройки Spring Security

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private DataSource dataSource;

    private final String USERS_QUERY = "select email, password, active from user where email=?";
    private final String ROLES_QUERY = "select u.email, r.role from user u inner join user_role ur on (u.id = ur.user_id) inner join role r on (ur.role_id=r.role_id) where u.email=?";

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                .usersByUsernameQuery(USERS_QUERY)
                .authoritiesByUsernameQuery(ROLES_QUERY)
                .dataSource(dataSource)
                .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/user/cart").authenticated()
                .antMatchers("/login").permitAll()
                .antMatchers("/signup").permitAll()
                .antMatchers("favicon.ico").permitAll()
               /* .antMatchers("/admin/**").access("hasRole('ADMIN')")*/
                .antMatchers("/main/**").hasAuthority("ADMIN").anyRequest()
                .authenticated().and().csrf().disable()
                .formLogin().loginPage("/login").permitAll().failureUrl("/login?error=true")
                .defaultSuccessUrl("/")
                .usernameParameter("email")
                .passwordParameter("password")
                .and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/")
                .and().rememberMe()
                .tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(60 * 60)
                .and().exceptionHandling().accessDeniedPage("/access_denied");

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers("/images/**")
                .antMatchers("/fonts/**");
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
        db.setDataSource(dataSource);

        return db;
    }
}

User Controller:

package com.zaitsava.springboot_touristsite.controller;


import javax.validation.Valid;

import com.zaitsava.springboot_touristsite.entity.User;
import com.zaitsava.springboot_touristsite.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/signup")
    public ModelAndView signup() {
        ModelAndView model = new ModelAndView();
        User user = new User();
        model.addObject("user", user);
        model.setViewName("user/signup");
        return model;
    }

    @PostMapping("/signup")
    public ModelAndView createUser(@Valid User user, BindingResult bindingResult) {
        ModelAndView model = new ModelAndView();
        User userExists = userService.findUserByEmail(user.getEmail());

        if(userExists != null) {
            bindingResult.rejectValue("email", "error.user", "User with this email exists");
        }
        if(bindingResult.hasErrors()) {
            model.setViewName("user/signup");
        } else {
            userService.saveUser(user);
            model.addObject("msg", "User succesful register!");
            model.addObject("user", new User());
            model.setViewName("redirect:home/main");
        }

        return model;
    }



    @GetMapping("/home/main")
    public ModelAndView home() {
        ModelAndView model = new ModelAndView();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = userService.findUserByEmail(auth.getName());

        model.addObject("userName", "Hello,"+user.getFirstname() + " " + user.getLastname()+" "+user.getPatronymic());
        model.setViewName("redirect:/");
        return model;
    }

    @GetMapping("/access_denied")
    public ModelAndView accessDenied() {
        ModelAndView model = new ModelAndView();
        model.setViewName("errors/access_denied");
        return model;
    }
}

Не понимаю, что мне нужно сделать, чтобы нормально работал контроллер

1 ответ 1

0

Посмотрел контролллер User метод home(), и переделал так для showCart() в ShoppingCartController

@GetMapping("/cart")
public String showCart(Model model){
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    User user = userService.findUserByEmail(auth.getName());
    if(user==null) System.out.println("User is null");
    List<CartItem> cartItemList=cartService.cartItemList(user);
    model.addAttribute("cartItems",cartItemList);
    return "user/cart";
}

Теперь по ссылке /cart отображается связь с товаром для текущего пользователя

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.