首页 > 解决方案 > 带有弹簧的MVC中的正确结构

问题描述

我对正确的 mvc 模式有点困惑。

这是我的配置文件:在这个类中,我有所有的 Bean。

@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());
    }

这是我的界面UserRepo,和界面UserService。他们是一样的

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

}

我有实现这个接口的类

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

最后我有我的控制器在我的控制器中我@Autowired UsersRepo/它是一个接口/。而且我的代码有效,我可以执行所有 CRUD 操作。

但是,有人告诉我这不是正确的方法。我不能直接自动接线。@Autowired 的 UserRepo,在 Controller 类中。所以我在网上搜索信息,然后创建一个服务类。它是这样创建的服务:具有与我在 UserRepo 接口中编写的相同方法的相同接口。在我创建了实现该接口的类之后,称为 UserServiceImpl。

在 userServiceImpl 中,我转到 @Autowire UserRepo 界面,然后转到 Controller 内的 @Autowire userService 。

但是现在我的代码不起作用,我在所有控件的所有页面中都有 404 状态:`请求的资源 [/bookProject/] 不可用

描述 源服务器没有找到目标资源的当前表示,或者不愿意透露存在。`

我在控制台中没有错误,只有信息:

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

所以我无法理解 Autowire 某些 bean 是否错误,或者我当前的模式是否错误,或者我是否需要更改配置类中的某些内容,或者我是否没有很好地应用服务类。因为在我的代码运行良好之前。

这是我的控制器:@Controller public class UserController { @Autowired private UserService us; 列出用户;@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);

这是 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);
}

标签: javaspringspring-mvcmodel-view-controllerjavabeans

解决方案


我会说检查您针对控制器定义调用的路径。如果您更新代码以查看控制器,我认为它会有所帮助。

例子:

@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{
 
 }

推荐阅读