How and when should I load the model from database for h:dataTable



  • I\'ve a data table as below:

    <h:dataTable value=\"#{bean.items}\" var=\"item\">
    
    

    I\'d like to populate it with a collection from the database obtained from a service method so that it is immediately presented when the page is opened during an initial (GET) request. When should I call the service method? And why?

    1. Call it before page is loaded. But how?
    2. Call it during page load. How?
    3. Call it in the getter method. But it is called multiple times.
    4. Something else?


  • Do it in bean's @PostConstruct method.

    @ManagedBean
    @RequestScoped
    public class Bean {
    
        private List<Item> items;
    
        @EJB
        private ItemService itemService;
    
        @PostConstruct
        public void init() {
            items = itemService.list();
        }
    
        public List<Item> getItems() {
            return items;
        }
    
    }
    
    

    And let the value reference the property (not method!).

    <h:dataTable value="#{bean.items}" var="item">
    
    

    In the @PostConstruct you have the advantage that it's executed after construction and dependency injection. So in case that you're using an EJB to do the DB interaction task, a @PostConstruct would definitely be the right place as injected dependencies would not be available inside a normal constructor yet. Moreover, when using a bean management framework which uses proxies, such as CDI @Named, the constructor may or may not be called the way you expect. It may be called multiple times during inspecting the class, generating the proxy, and/or creating the proxy.

    At least do not perform the DB interaction job in the getter, unless it's lazy loading and you really can't do anything else. Namely, it would be invoked during every iteration round. Calling the service method during every iteration round is plain inefficient and may end up in "weird" side effects during presentation and postbacks, such as old values from DB seemingly still sticking around in the model instead of new submitted values.

    If you rely on GET request parameters, then use <f:viewParam> and <f:viewAction> instead. If you want to preserve the model (the items property) across postbacks on the same view (e.g. CRUD table/dialog), then make the bean @ViewScoped.

    See also:

    • Why JSF calls getters multiple times
    • What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
    • How to choose the right bean scope?
    • JSF Controller, Service and DAO


最新内容

  • 问题

    I am new to spring security and try to add an authentication layer over my service. The service is working fine without @PreAuthorize ,however, when I use it and add the role @PreAuthorize(\"hasRole(\'ROLE_USER\')\") it showed me this error in postman, not even in console:

    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)\\n\\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)\\n\\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)\\n\\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\\n\\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039)\\n\\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)\\n\\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)\\n\\tat org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)\\n\\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:634)\\n\\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)\\n\\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:741)\\n\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\\n\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\\n\\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\\n\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\\n\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\\n\\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)\\n\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\\n\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\\n\\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)\\n\\tat org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)\\n\\tat org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)\\n\\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\\n\\tat org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)\\n\\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\\n\\tat org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)\\n\\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\\n\\tat org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)\\n\\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\\n\\tat org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)\\n\\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\\n\\tat org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)\\n\\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\\n\\tat com.foody.Foody.security.JwtAuthenticationFilter.doFilterInternal(JwtAuthenticationFilter.java:55)\\n\\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)\\n\\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\\n\\tat org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)\\n\\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\\n\\tat org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96)\\n\\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)\\n\\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\\n\\tat org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74)\\n\\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)\\n\\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\\n\\tat org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)\\n\\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\\n\\tat org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)\\n\\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)\\n\\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\\n\\tat org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)\\n\\tat org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)\\n\\tat org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)\\n\\tat org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)\\n\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\\n\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\\n\\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)\\n\\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)\\n\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\\n\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\\n\\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)\\n\\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)\\n\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\\n\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\\n\\tat org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)\\n\\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)\\n\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\\n\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\\n\\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)\\n\\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)\\n\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\\n\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\\n\\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)\\n\\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)\\n\\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)\\n\\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)\\n\\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\\n\\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\\n\\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)\\n\\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)\\n\\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)\\n\\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)\\n\\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)\\n\\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\\n\\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)\\n\\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)\\n\\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\\n\\tat java.lang.Thread.run(Thread.java:745)\\n\",\"path\":\"/api/package/list\"}

    Here is my Security Config file:

    @RequiredArgsConstructor @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity( securedEnabled = true, jsr250Enabled = true, prePostEnabled = true ) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired CustomUserDetailsService customUserDetailsService; @Autowired private JwtAuthenticationEntryPoint unauthorizedHandler; @Bean public JwtAuthenticationFilter jwtAuthenticationFilter() { return new JwtAuthenticationFilter(); } @Override public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder .userDetailsService(customUserDetailsService) .passwordEncoder(passwordEncoder()); } @Bean(BeanIds.AUTHENTICATION_MANAGER) @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http .cors() .and() .csrf() .disable() .exceptionHandling() .authenticationEntryPoint(unauthorizedHandler) .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers(\"/\", \"/favicon.ico\", \"/**/*.png\", \"/**/*.gif\", \"/**/*.svg\", \"/**/*.jpg\", \"/**/*.html\", \"/**/*.css\", \"/**/*.js\") .permitAll() .antMatchers(\"/api/auth/**\") .permitAll() .antMatchers(\"/api/user/checkUsernameAvailability\", \"/api/user/checkEmailAvailability\") .permitAll() .antMatchers(HttpMethod.GET, \"/api/package/**\", \"/api/users/**\") .permitAll() .anyRequest().authenticated(); // Add our custom JWT security filter http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } }

    PackageController:

    @RestController @RequestMapping(\"/api/package\") @Slf4j @AllArgsConstructor @CrossOrigin(\"*\") public class PackageController { private final PackageService packageService; @GetMapping(\"/list\") @PreAuthorize(\"hasRole(\'ROLE_USER\')\") public ResponseEntity<?> getAllPackages(){ return ResponseEntity.ok(packageService.getAllPackages()); } }

    I signed in using postman and copy the Bearer token to its field.

    The user is already signup and signed in using postman and existed in the database.

    I tried to change the role including/excluding ROLE_ prefix but the same result is displayed. I cannot figure out what I did incorrectly since I did many things and tried different scenarios but the same output is given

    回答1:

    2

    .antMatchers(HttpMethod.GET, "/api/package/**", "/api/users/**").permitAll() and using @PreAuthorize("hasRole('ROLE_USER')") for an endpoint GET /api/package/list is contradiction.

    If you want to secure GET /api/package/list then you can use .antMatchers(HttpMethod.GET,"/endpoint").hasRole("USER") and make sure you have stroed roles as ROLE_USER (instead of USER) in database as sometimes this cause an issue.

    Make sure you are passing a valid token in the header.

    share|improve this answer

    answered Sep 13 at 17:55

    Patel RomilPatel Romil 3,56955 gold badges1515 silver badges3232 bronze badges

    1

    Thanks, It worked for me. I didn't realize that there a conflict – user1446168 Sep 14 at 4:18

    add a comment |

    read more
  • 问题

    Am trying to create a language switcher for a Symfony 4 project (with Twig). Basically when clicking a link, the website\'s language will change.

    Configuration I have is this:

    config\\packages\\translation.yaml

    framework: default_locale: en translator: default_path: \'%kernel.project_dir%/translations\' fallbacks: - en

    This is the important lines I got in

    config\\packages\\services.yaml:

    parameters: locale: \'en\' # This parameter defines the codes of the locales (languages) enabled in the application app_locales: en|fr

    My Controller:

    <?php namespace App\\Controller; use Symfony\\Component\\HttpFoundation\\Request; use Symfony\\Component\\Routing\\Annotation\\Route; use Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController; use Symfony\\Component\\HttpFoundation\\JsonResponse; use Symfony\\Component\\HttpFoundation\\Response; use Symfony\\Component\\Translation\\TranslatorInterface; use Symfony\\Component\\Validator\\Constraints\\Json; // Class name really should match Controller name class ControllerBase extends AbstractController { /** * @Route(\"/{_locale}\", name=\"app_landing\", defaults={\"_locale\" = \"en\"}, requirements={\"_locale\" = \"en|fr\"}) */ public function index(Request $request) { $locale = $request->getLocale(); return $this->render(\'landing/index.html.twig\'); } }

    The actual language switcher is just two list elements contained in the template file. They look like this:

    <li><a href=\"{{ path(app.request.get(\'_route\'), app.request.get(\'_route_params\')|merge({\'_locale\': \'en\'})) }}\">English</a></li>

    <li><a href=\"{{ path(app.request.get(\'_route\'), app.request.get(\'_route_params\')|merge({\'_locale\': \'fr\'})) }}\">French</a></li>

    This works fine.

    Problem arises when clicking another link on the website. It doesn\'t contain the _locale and the site defaults back to en.

    I really would like the _locale to be added to each link automatically (including the index path \"/\").

    回答1:

    0

    After a while of experimenting, I found the answer.

    I tried to do the same thing in two different ways. In my case it was best to simply use the code in the template file and omit the {_locale} parameter in the controller.

    Like that all works fine.

    share|improve this answer

    answered Oct 2 at 14:15

    CharlesCharles 8777 bronze badges

    add a comment |

    read more
  • .antMatchers(HttpMethod.GET, "/api/package/**", "/api/users/**").permitAll() and using @PreAuthorize("hasRole('ROLE_USER')") for an endpoint GET /api/package/list is contradiction.

    If you want to secure GET /api/package/list then you can use .antMatchers(HttpMethod.GET,"/endpoint").hasRole("USER") and make sure you have stroed roles as ROLE_USER (instead of USER) in database as sometimes this cause an issue.

    Make sure you are passing a valid token in the header.

    read more

最新主题

推荐阅读

本站部分内容来自互联网,其发布内容言论不代表本站观点,如果其链接、内容的侵犯您的权益,烦请联系我们,我们将及时予以处理。
Powered by NodeBB | 备案号:宁ICP备15000671号