I can’t save to the database in a Spring MVC project

Asked

Viewed 865 times

2

I will explain the project because I believe that most people usually create projects using XML, and I created the Spring MVC project by dispensing the files that configure the project as XML.

The problem of my project is that I created the connection to the database, I created the DAO methods, I created the JSP dialogs and I still can’t enter the records into the database.

Well, I’ll start explaining the project;

This is the class JPAConfiguration, he who makes the connection to the database dispensing the file persistence.xml:

@EnableTransactionManagement
public class JPAConfiguration {



      @Bean
       public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
          LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
          em.setDataSource(dataSource);
          em.setPackagesToScan(new String[] { "br.com.casadocodigo.loja.models" });

          JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
          em.setJpaVendorAdapter(vendorAdapter);
          em.setJpaProperties(additionalProperties());

          return em;
       }

       @Bean       
       public DataSource dataSource(Environment environment){
          DriverManagerDataSource dataSource = new DriverManagerDataSource();
          dataSource.setDriverClassName("com.mysql.jdbc.Driver");
          dataSource.setUrl("jdbc:mysql://localhost:3306/casadocodigo");
          dataSource.setUsername( "root" );
          dataSource.setPassword( "123" );
          return dataSource;
       }

       @Bean
       public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
          JpaTransactionManager transactionManager = new JpaTransactionManager();
          transactionManager.setEntityManagerFactory(emf);   
          return transactionManager;
       }

       @Bean
       public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
          return new PersistenceExceptionTranslationPostProcessor();
       }

      Properties additionalProperties() {
          Properties properties = new Properties();
          properties.setProperty("hibernate.hbm2ddl.auto", "update");
          properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
          properties.setProperty("hibernate.show_sql", "true");
          return properties;
       }

In this class above I believe I have no problem.

NOTE: I am following a book by Casadocodigo that teaches Spring MVC. This logic I took from the book because I’m beginner as Spring MVC programmer.

This is the class is ServletSpringMVC, it determines how the project mapping configuration will be.

public class ServletSpringMVC extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return new Class[]{AppWebConfiguration.class, JPAConfiguration.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        // TODO Auto-generated method stub
        return new String[]{"/"};
    }

This class below indicates where the JSP page mapping is;

@EnableWebMvc
@ComponentScan(basePackageClasses={HomeController.class, ProductDAO.class})
public class AppWebConfiguration extends WebMvcConfigurerAdapter{




    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

This is DAO class, very simple:

@Repository
public class ProductDAO {

    @PersistenceContext
    private EntityManager manager;


    public void save(Product product) {
        manager.persist(product);       
    }

}

This is my entity:

@Entity
public class Product {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;
    private String title;
    @Lob
    private String description;
    private int pages;

    public Long getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

}

All very simple!

Structure of my project:

estrutura do projeto

My page I’m trying to save the products:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cadastro de Produtos</title>
</head>
<body>

    <form method="post" action="/casadocodigo/produtos" >

        <div>
            <label for="title">Titulo</label> <input type="text" name="title"
                id="title" />
        </div>

        <div>
            <label for="description">Descrição</label>
            <textarea rows="10" cols="20" name="description" id="description"></textarea>

        </div>
        <div>
            <label for="pages">Número de Paginas</label>
            <input type="text" name="pages" id="pages"/>
        </div>
        <div>
            <input type="submit" value="Enviar"/>
        </div>
    </form>


</body>
</html>

This is my page:

Página renderizada

When I try to save, it gives error 404. Despite the error, I verify that even having generated the error, it managed to be saved, but even so I did not succeed.

OBS: It only generates an error in the page, but does not notify an error in the eclipse console.

Console

I believe I’ve done everything right, but I may have done something wrong, and I really need help finding out where I’m going wrong.

Someone can see something wrong in the code?

Here is my repository:

https://github.com/wladimirbandeira/casadocodigo/tree/master/lojacasadocodigo

Error:

Página com erro 404

///////////////////////////////////////////////////////////////////////////////

                        ATUALIZAÇÃO DA POSTAGEM

message displayed by log4j;

08:48:40 [localhost-startStop-1] ContextLoader - Root WebApplicationContext: initialization started
08:48:40 [localhost-startStop-1] StandardServletEnvironment - Adding [servletConfigInitParams] PropertySource with lowest search precedence
08:48:40 [localhost-startStop-1] StandardServletEnvironment - Adding [servletContextInitParams] PropertySource with lowest search precedence
08:48:40 [localhost-startStop-1] StandardServletEnvironment - Adding [jndiProperties] PropertySource with lowest search precedence
08:48:40 [localhost-startStop-1] StandardServletEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
08:48:40 [localhost-startStop-1] StandardServletEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
08:48:40 [localhost-startStop-1] StandardServletEnvironment - Initialized StandardServletEnvironment with PropertySources [servletConfigInitParams,servletContextInitParams,jndiProperties,systemProperties,systemEnvironment]
08:48:40 [localhost-startStop-1] StandardServletEnvironment - Replacing [servletContextInitParams] PropertySource with [servletContextInitParams]
08:48:40 [localhost-startStop-1] AnnotationConfigWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Wed Oct 21 08:48:40 BRST 2015]; root of context hierarchy
08:48:40 [localhost-startStop-1] AnnotationConfigWebApplicationContext - Registering annotated classes: [class br.com.casadocodigo.loja.conf.AppWebConfiguration,class br.com.casadocodigo.loja.conf.JPAConfiguration]
08:48:40 [localhost-startStop-1] AnnotationConfigWebApplicationContext - Bean factory for Root WebApplicationContext: org.springframework.beans.factory.support.DefaultListableBeanFactory@23e1c6ec: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,appWebConfiguration,JPAConfiguration]; root of factory hierarchy
08:48:41 [localhost-startStop-1] AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
08:48:41 [localhost-startStop-1] PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'JPAConfiguration' of type [class br.com.casadocodigo.loja.conf.JPAConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
08:48:41 [localhost-startStop-1] AnnotationConfigWebApplicationContext - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@64208072]
08:48:41 [localhost-startStop-1] AnnotationConfigWebApplicationContext - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@38b10fea]
08:48:45 [localhost-startStop-1] RequestMappingHandlerMapping - Looking for request mappings in application context: Root WebApplicationContext: startup date [Wed Oct 21 08:48:40 BRST 2015]; root of context hierarchy
08:48:45 [localhost-startStop-1] RequestMappingHandlerMapping - Mapped "{[/],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String br.com.casadocodigo.loja.controller.HomeController.index()
08:48:45 [localhost-startStop-1] RequestMappingHandlerMapping - Mapped "{[/produtos/form],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String br.com.casadocodigo.loja.controller.ProductsController.form()
08:48:45 [localhost-startStop-1] RequestMappingHandlerMapping - Mapped "{[/produtos/],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String br.com.casadocodigo.loja.controller.ProductsController.save(br.com.casadocodigo.loja.models.Product)
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Looking for URL mappings in application context: Root WebApplicationContext: startup date [Wed Oct 21 08:48:40 BRST 2015]; root of context hierarchy
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'org.springframework.context.annotation.internalRequiredAnnotationProcessor': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'org.springframework.context.annotation.internalCommonAnnotationProcessor': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'org.springframework.context.annotation.internalPersistenceAnnotationProcessor': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'appWebConfiguration': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'JPAConfiguration': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'homeController': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'productsController': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'productDAO': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'resourceHandlerMapping': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'requestMappingHandlerMapping': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'mvcContentNegotiationManager': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'viewControllerHandlerMapping': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'beanNameHandlerMapping': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'mvcResourceUrlProvider': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'httpRequestHandlerAdapter': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'defaultServletHandlerMapping': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'simpleControllerHandlerAdapter': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'requestMappingHandlerAdapter': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'mvcConversionService': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'mvcUriComponentsContributor': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'handlerExceptionResolver': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'mvcPathMatcher': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'mvcUrlPathHelper': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'mvcValidator': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'mvcViewResolver': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'internalResourceViewResolver': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'org.springframework.transaction.config.internalTransactionAdvisor': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'transactionAttributeSource': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'transactionInterceptor': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'dataSource': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'exceptionTranslation': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'transactionManager': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'entityManagerFactory': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'org.springframework.aop.config.internalAutoProxyCreator': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'environment': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'systemProperties': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'systemEnvironment': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'servletContext': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'contextParameters': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'contextAttributes': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'messageSource': no URL paths identified
08:48:45 [localhost-startStop-1] BeanNameUrlHandlerMapping - Rejected bean name 'applicationEventMulticaster': no URL paths identified
08:48:45 [localhost-startStop-1] RequestMappingHandlerAdapter - Looking for @ControllerAdvice: Root WebApplicationContext: startup date [Wed Oct 21 08:48:40 BRST 2015]; root of context hierarchy
08:48:46 [localhost-startStop-1] ExceptionHandlerExceptionResolver - Looking for exception mappings: Root WebApplicationContext: startup date [Wed Oct 21 08:48:40 BRST 2015]; root of context hierarchy
08:48:46 [localhost-startStop-1] AnnotationConfigWebApplicationContext - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@70bcac8]
08:48:46 [localhost-startStop-1] ResourceUrlProvider - Looking for resource handler mappings
08:48:46 [localhost-startStop-1] ResourceUrlProvider - No resource handling mappings found
08:48:46 [localhost-startStop-1] ContextLoader - Published root WebApplicationContext as ServletContext attribute with name [org.springframework.web.context.WebApplicationContext.ROOT]
08:48:46 [localhost-startStop-1] ContextLoader - Root WebApplicationContext: initialization completed in 5694 ms
08:48:46 [localhost-startStop-1] DispatcherServlet - Initializing servlet 'dispatcher'
08:48:46 [localhost-startStop-1] StandardServletEnvironment - Adding [servletConfigInitParams] PropertySource with lowest search precedence
08:48:46 [localhost-startStop-1] StandardServletEnvironment - Adding [servletContextInitParams] PropertySource with lowest search precedence
08:48:46 [localhost-startStop-1] StandardServletEnvironment - Adding [jndiProperties] PropertySource with lowest search precedence
08:48:46 [localhost-startStop-1] StandardServletEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
08:48:46 [localhost-startStop-1] StandardServletEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
08:48:46 [localhost-startStop-1] StandardServletEnvironment - Initialized StandardServletEnvironment with PropertySources [servletConfigInitParams,servletContextInitParams,jndiProperties,systemProperties,systemEnvironment]
out 21, 2015 8:48:46 AM org.apache.catalina.core.ApplicationContext log
INFORMAÇÕES: Initializing Spring FrameworkServlet 'dispatcher'
08:48:46 [localhost-startStop-1] DispatcherServlet - FrameworkServlet 'dispatcher': initialization started
08:48:46 [localhost-startStop-1] StandardServletEnvironment - Adding [servletConfigInitParams] PropertySource with lowest search precedence
08:48:46 [localhost-startStop-1] StandardServletEnvironment - Adding [servletContextInitParams] PropertySource with lowest search precedence
08:48:46 [localhost-startStop-1] StandardServletEnvironment - Adding [jndiProperties] PropertySource with lowest search precedence
08:48:46 [localhost-startStop-1] StandardServletEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
08:48:46 [localhost-startStop-1] StandardServletEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
08:48:46 [localhost-startStop-1] StandardServletEnvironment - Initialized StandardServletEnvironment with PropertySources [servletConfigInitParams,servletContextInitParams,jndiProperties,systemProperties,systemEnvironment]
08:48:46 [localhost-startStop-1] StandardServletEnvironment - Replacing [servletContextInitParams] PropertySource with [servletContextInitParams]
08:48:46 [localhost-startStop-1] StandardServletEnvironment - Replacing [servletConfigInitParams] PropertySource with [servletConfigInitParams]
08:48:46 [localhost-startStop-1] AnnotationConfigWebApplicationContext - Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Wed Oct 21 08:48:46 BRST 2015]; parent: Root WebApplicationContext
08:48:46 [localhost-startStop-1] AnnotationConfigWebApplicationContext - Bean factory for WebApplicationContext for namespace 'dispatcher-servlet': org.springframework.beans.factory.support.DefaultListableBeanFactory@785814ad: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@23e1c6ec
08:48:46 [localhost-startStop-1] AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
08:48:46 [localhost-startStop-1] AnnotationConfigWebApplicationContext - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@7a0438b6]
08:48:46 [localhost-startStop-1] AnnotationConfigWebApplicationContext - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@4241b627]
08:48:46 [localhost-startStop-1] AnnotationConfigWebApplicationContext - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@3557ec5]
08:48:46 [localhost-startStop-1] DispatcherServlet - Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided
08:48:46 [localhost-startStop-1] DispatcherServlet - Unable to locate LocaleResolver with name 'localeResolver': using default [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver@13cea2d1]
08:48:46 [localhost-startStop-1] DispatcherServlet - Unable to locate ThemeResolver with name 'themeResolver': using default [org.springframework.web.servlet.theme.FixedThemeResolver@11255868]
08:48:46 [localhost-startStop-1] DispatcherServlet - Unable to locate RequestToViewNameTranslator with name 'viewNameTranslator': using default [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator@368d22b8]
08:48:46 [localhost-startStop-1] DispatcherServlet - Unable to locate FlashMapManager with name 'flashMapManager': using default [org.springframework.web.servlet.support.SessionFlashMapManager@432020c8]
08:48:46 [localhost-startStop-1] ResourceUrlProvider - Looking for resource handler mappings
08:48:46 [localhost-startStop-1] ResourceUrlProvider - No resource handling mappings found
08:48:46 [localhost-startStop-1] DispatcherServlet - Published WebApplicationContext of servlet 'dispatcher' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher]
08:48:46 [localhost-startStop-1] DispatcherServlet - FrameworkServlet 'dispatcher': initialization completed in 46 ms
08:48:46 [localhost-startStop-1] DispatcherServlet - Servlet 'dispatcher' configured successfully
out 21, 2015 8:48:46 AM org.apache.coyote.AbstractProtocol start
INFORMAÇÕES: Starting ProtocolHandler ["http-bio-8080"]
out 21, 2015 8:48:46 AM org.apache.coyote.AbstractProtocol start
INFORMAÇÕES: Starting ProtocolHandler ["ajp-bio-8009"]
out 21, 2015 8:48:46 AM org.apache.catalina.startup.Catalina start
INFORMAÇÕES: Server startup in 11543 ms
08:49:06 [http-bio-8080-exec-3] DispatcherServlet - DispatcherServlet with name 'dispatcher' processing GET request for [/lojacasadocodigo/produtos/form]
08:49:06 [http-bio-8080-exec-3] RequestMappingHandlerMapping - Looking up handler method for path /produtos/form
08:49:06 [http-bio-8080-exec-3] RequestMappingHandlerMapping - Returning handler method [public java.lang.String br.com.casadocodigo.loja.controller.ProductsController.form()]
08:49:06 [http-bio-8080-exec-3] DispatcherServlet - Last-Modified value for [/lojacasadocodigo/produtos/form] is: -1
08:49:06 [http-bio-8080-exec-3] DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'products/form'; URL [/WEB-INF/views/products/form.jsp]] in DispatcherServlet with name 'dispatcher'
08:49:06 [http-bio-8080-exec-3] JstlView - Forwarding to resource [/WEB-INF/views/products/form.jsp] in InternalResourceView 'products/form'
08:49:06 [http-bio-8080-exec-3] DispatcherServlet - Successfully completed request

this was the configuration used;

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <!-- Appenders -->
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{HH:mm:ss} [%t] %c{1} - %m%n" />
        </layout>
    </appender>

    <logger name="org.springframework.samples">
        <level value="debug" />
    </logger>

    <logger name="org.springframework.core">
        <level value="info" />
    </logger>

    <logger name="org.springframework.beans">
        <level value="info" />
    </logger>

    <logger name="org.springframework.context">
        <level value="info" />
    </logger>

    <logger name="org.springframework.http">
        <level value="debug" />
    </logger>

    <logger name="org.springframework.web">
        <level value="debug" />
    </logger>

    <root>
        <priority value="warn" />
        <appender-ref ref="console" />
    </root>

</log4j:configuration>

What I need is to try to record things in the bank and I can’t.

could help me see if there is anything that indicates problems in entering the record in the bank?

2 answers

5


The first thing you should do is add a log configuration to display errors in the console or in a log file.

I saw in the pom.xml of your project that is using Log4j, so this means that it would be interesting to put a log4j.xml in the briefcase src/main/resources.

Without the error/exception someone could just try to guess the cause of the problem with few chances to hit.

However, looking quickly at some classes I noticed that you are returning products/ok in the listing, but there is no view called ok.jsp:

@Controller
@Transactional
public class ProductsController {

    @Autowired
    private ProductDAO productDAO;

    @RequestMapping("/produtos/")
    public String save(Product product){
        productDAO.save(product);
        return "products/ok";
    }

    @RequestMapping("/produtos/form")
    public String form(){
        return "products/form";
    }


}

A hint: in a real system, do not declare transactions in the controllers, much less in the whole class.

It is not the responsibility of the controllers to demarcate transactional blocks. Beyond what you end up putting transactions where you do not need, as in query methods or even access the bank.

  • can please take a look at my post as I just updated, I really need your help.

  • @wladyband By the log it seems not even going through the method save. Try to write down the method with @RequestMapping(value="produtos", method=RequestMethod.POST) and see if you can do anything else.

  • @wladyband Just to confirm. The problem now is that the information does not arrive in the database?

-2

Hi, 404 is because the ok page doesn’t exist. Just create... Regarding the Controller @Transactional Annotation, I don’t agree. The controller invokes multiple business points from your application, it works almost like a service, so it makes a lot of sense to demarcate the transaction there. Who controls the scope of a transaction is who uses the business classes...

  • 1

    In a very simple and layered system it even works, but if you want to do any sort of separation or reuse level or any rule bigger than just calling a "business" method, it doesn’t work. Who says the responsibility of demarcation is who you call the business rule? It may be at a higher level of the business rule, as in the Session Facade standard. They did not invent EJBS for nothing.

  • Just for the record, the Sessionfacade isolates the complexity of multiple rule calls, which is why he’s a Facade... It would make sense to leave the transaction there. If you do not leave the transaction demarcated in who controls the invocations, how will make it clear that they all participate in the same transaction?

  • 1

    I agree that a standard like Session Facade is correct for this, what I meant is that it is wrong to leave it in the controller or another layer of higher application that should not know anything about the bank. I think that in the end this is just a misunderstanding of terminology. In fact, the negative vote is not mine.

  • 1

    I’m coming back to this discussion because at the time, to be more exact in the month 10 of 2015 I was still trying to understand Spring MVC, so just to REGISTER, actually @utluiz is right that the@Transactional annotation should not be in the controller because it is delegating too much responsibility to a single class, and it is not good programming practice, with all due respect, without wanting to attack, because that is not my goal, I suggest that Alberto Souza update his book that is sold on the website of the House of Code.

  • Opa thanks for the comment. I respect everyone’s opinion, but mine has not yet changed. The controller remains a trigger point for your domain layer and I see no problem leaving @Transactional there. If the (a) programmer(a) decides to architect his code using the Controller just to call a service that will isolate the other invocations, then I think it might make sense to move the Annotation. About the book, I appreciate the suggestion, but I’ll keep it the way it is :).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.