Home > Enterprise >  correct structure in MVC with spring
correct structure in MVC with spring

Time:10-01

I'm a little confused about correct mvc pattern.

This is my config file: In this class I've got all Beans.

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = " name.web.controller")
@PropertySource("classpath:NewLibrary.properties")
@EnableTransactionManagement

    @Bean
    public UserRepo getUserService() {
        return new UserImpl(getDataSource());
    }
    
    
    @Bean
    public BookRepo getBookService() {
        return new BookImpl(getDataSource());
    }

This is my interface UserRepo, and interface UserService. They are the same

public interface UserService {
public String getUser();
void add(UserModel u);
UserModel getById(int id);
UserModel getByName(String name);
UserModel getByCognome(String surname);
Optional<UserModel> findOne(int id);
public void insert(User u);
public String giveName();
List<UserModel>ByNome(String nome);
List<UserModel> ByPassAndUsername(String password, String username);

}

I've got my class that implemets this interface

@Repository
public class UserImpl extends AbstractDao<UserModel, Integer> implements UserRepo {
@PersistenceContext
private EntityManager em;
 @Autowired
public UserRepo userRepo;

private JdbcTemplate conn;
@Override
@Transactional
public void add(UserModel u) {
    em.persist(u);
}
public UserImpl(DataSource ds) {
    conn= new JdbcTemplate(ds);
}
@Override
public UserModel getById(int id) {
    return em.find(UserModel.class, id);
}
@Override
public UserModel getByName(String nome) {
    CriteriaBuilder queryBuilder= em.getCriteriaBuilder();
    CriteriaQuery<UserModel> query= 
queryBuilder.createQuery(UserModel.class);
    Root<UserModel> rec= query.from(UseriModel.class);
     
query.select(rec).where(queryBuilder.equal(rec.get("nome"), nome));
     
     UserModel ut=em.createQuery(query).getSingleResult();
     em.clear();
    
     return ut;
    
    //return em.find(UtentiModel.class, nome);
    
};

And finally I've got my Controller In my Controller I @Autowired UsersRepo/it's a inteface/. And my code works, I can do all CRUD operations.

But, was told to me that this is not the right way. I can't autowire directly. @Autowired of UserRepo, inside Controller class. So I search info on web, and I create a Service class. The Service it's made so: have the same interface with the same methods that I wrote inside UserRepo Inteface. After I create the class that implements that interface, called UserSeviceImpl.

In userServiceImpl I go to @Autowire UserRepo interface, and after I go to @Autowire userService inside the Controller.

But now my code doesn't work, Ive got 404 status in all pages in all Controlles: `The requested resource [/bookProject/] is not available

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.`

I've got no errors inside Console, just info:

INFO: Command line argument: -Dfile.encoding=UTF-8
set 30, 2021 5:41:10 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The Apache Tomcat Native library which allows using OpenSSL was not found on the java.library.path: [/usr/java/packages/lib:/usr/lib64:/lib64:/lib:/usr/lib]
set 30, 2021 5:41:10 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
set 30, 2021 5:41:10 PM org.apache.catalina.startup.Catalina load
INFO: Server initialization in [624] milliseconds
set 30, 2021 5:41:10 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Catalina]
set 30, 2021 5:41:10 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet engine: [Apache Tomcat/9.0.50]
set 30, 2021 5:41:12 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
set 30, 2021 5:41:12 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
set 30, 2021 5:41:12 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory [/home/viktoriya/Scrivania/apache-tomcat-9.0.50/webapps/ROOT]
 set 30, 2021 5:41:12 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deployment of web application directory [/home/viktoriya/Scrivania/apache-tomcat-9.0.50/webapps/ROOT] has finished in [13] ms
set 30, 2021 5:41:12 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
set 30, 2021 5:41:12 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in [2050] milliseconds

So I can not understand if I'm wrong to Autowire some bean, or if my current pattern is wrong, or if I need to change something in the config class, or if I have not applied the class of service well. Beacuse before my code was working well.

This is my controller: @Controller public class UserController { @Autowired private UserService us; List user; @GetMapping("/new") public ModelAndView new(Model model) {

UserModel users= new UserModel();
model.addAttribute("utenteForm", user);
return new ModelAndView("client", "utenteForm", new 
UtentiModel());
}
@PostMapping("/add")
public ModelAndView sumbit(@ModelAttribute("utenteForm") UserModel users)
{ us.ad(users);

And this is UserServiceImpl:

@Service
public class UserServiceImpl implements UserService{
private final static Logger log= 
Logger.getLogger(UserServiceImpl.class.getName());
@Autowired
private UserRepo userRepo;
@PersistenceContext
private EntityManager em;
@Override
public void add(UserModel u) {
    userRepo.add(u);
}
@Override
public UserModel getByName(String name) {
    
    return userRepo.getByName(name);
}

CodePudding user response:

I would say check your path that you are calling against the controller definition. I think it help if you update the code to see also the controller.

Example:

@RestController
@RequestMapping("/test")
public class TestRestController{

  @Autowired
  private TestService testService;
 .....
}

 @Service
public class TestServiceImpl implements TestService {

  @Autowired    
  private TestRepository testRepository;

}
@Repository
@Transactional
 public class TestRepositoryImpl implements TestRepository{
 
 }
  • Related