Receber Id de Select Option e enviar via Post – Java, Thymeleaf, Spring

Preciso criar uma tela de Vendas, que receba Produtos e Clientes para seleção, seleciono um cliente e um produto e faço o envio dos mesmo através de um Post para Vendas. Vendas Recebe o id de cliente e um id de produtos. Criei um select options que exibe o os clientes e os produtos para seleção, porém não estou conseguindo receber o id de ambos através do Post. Ao executar que os campos de id de cliente e produto estão nulos.

HTML

    <div class="panel panel-default">         <div class="panel-heading">             <h1 class="panel-title">Novo título</h1>         </div>         <div class="form-group">             <label for="status" class="col-sm-2 control-label">Status</label>             <div class="col-sm-2">                 <select class="form-control" name="status">                     <option th:each="cliente : $  {addCliente}" th:value="$  {cliente.id}"                         th:text="$  {cliente.nome}"></option>                 </select>             </div>         </div>         <div class="form-group">             <label for="status" class="col-sm-2 control-label">Status</label>             <div class="col-sm-2">                 <select class="form-control" name="status">                     <option th:each="produto : $  {addProduto}" th:value="$  {produto.id}"                         th:text="$  {produto.nome}"></option>                 </select>             </div>         </div>         <div class="form-group">             <div class="col-sm-offset-2 col-sm-10">                 <button type="submit" class="btn btn-primary">Salvar</button>             </div>         </div>     </div> 

VendasController

@Autowired private ClientesService clientesService; @Autowired private VendasRepository vendasRepo; @Autowired private ProdutosRepository produtosRepo;  @RequestMapping("/novo") public ModelAndView novo() {     ModelAndView mv = new ModelAndView("cadastrarVenda");     return mv; }  @RequestMapping(method = RequestMethod.POST) public ModelAndView salvar(Vendas vendas) {     vendasRepo.save(vendas);     ModelAndView mv = new ModelAndView("cadastrarVenda");     return mv; }  @ModelAttribute("addCliente") public List<Clientes> addCliente() {     return clientesService.listarTodos();  }  @ModelAttribute("addProduto") public List<Produtos> addProduto() {     return produtosRepo.findAll(); } 

}

The most effective method to Sell Spring Lobby Wellbeing Keto

Wonder Full Keto as they may anger the symptoms. Regardless, Wonder Full Keto BodyTone is free from any manufactured inventions and that is the reason anyone can use this improvement. In light of its beginning and end trademark foundation, Wonder Full Keto BodyTone is completely protected and it also improves various prosperity conditions by decreasing their ominous effects. Similarly, the Wonder Full Keto diet causes a…

The most effective method to Sell Spring Lobby Wellbeing Keto

Spring Hall Health Keto – Get Naturals Diet Pills,

http://slimtonepills.com/spring-hall-health-keto/

He changed the technique for creating Spring Hall Health Keto essentialness from various sources in the body. This grows the proportion of beta-hydroxybutyric destructive (BHB) in the blood and sanctions the body in the body, which changes over fat into imperativeness, and totally reduce…

Spring Hall Health Keto – Get Naturals Diet Pills,

Поиск в базе данных Spring MVC и JPA

Только осваиваю Spring и, вот такая задача – нужно осуществить поиск по разным параметрам. Причем параметры все не обязательные, т.е. могут присутствовать как несколько параметров сразу, так и только один из них. Опыта со Спрингом мало, поэтому, где ошибаюсь не знаю, но поиск не происходит. Есть html-форма:

<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title th:text="$  Поиск в базе данных Spring MVC и JPA">Title</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity ="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="../static/css/styles.css" th:href="@{/css/styles.css}"> </head> <body onload="checkFindFields();"> <div id="header_container"> <h1 class="header_content centered">Find Client</h1> </div> <div style="width: 300px; margin: 0 auto"> <form id="find_form" method="post" action="#" th:action="@{/clients/find}" th:object="$  {client}">     <p class="centered" style="width: 300px; margin: 20px">Find Client</p>     <table>         <tr>             <td style="width: 100px">ID: </td>             <td>                 <label for="id"></label>                 <input class="auth" style="margin: 5px" type="text" name="id" id="id" th:fileld="*{id}"/>             </td>         </tr>         <tr>             <td style="width: 100px">Name: </td>             <td>                 <label for="name"></label>                 <input class="auth" style="margin: 5px" type="text" name="name" id="name" th:field="*{firstName}"/>             </td>         </tr>         <tr>             <td style="width: 100px">Surname: </td>             <td>                 <label for="surname"></label>                 <input class="auth" style="margin: 5px" type="text" name="surname" id="surname" th:field="*{lastName}"/>             </td>         </tr>         <tr>             <td style="width: 100px">Email: </td>             <td>                 <label for="email"></label>                 <input class="auth" style="margin: 5px" type="text" name="email" id="email" th:field="*{email}"/>             </td>         </tr>         <tr>             <td style="width: 100px">Balance: </td>             <td>                 <label for="balance"></label>                 <input class="auth" style="margin: 5px" type="text" name="balance" id="balance" th:field="*{balance}"/>             </td>         </tr>         <tr>             <td style="width: 100px">Phones: </td>             <td>                 <label for="phones"></label>                 <input class="auth" style="margin: 5px" type="text" name="phones" id="phones"/>             </td>         </tr>         <tr>             <td style="width: 100px">Identity: </td>             <td>                 <label for="identity"></label>                 <input class="auth" style="margin: 5px" type="text" name="identity" id="identity"/>             </td>         </tr>     </table>     <table style="margin: 10px">         <tr>             <td><input style="width: 110px" type="submit" value="Find"/></td>             <td style="width: 80px"></td>             <td><input style="width: 110px" type="button" value="Cancel" onclick="openPage('/Client')"/></td>         </tr>     </table> </form> </div> <script type="text/javascript" language="JavaScript" src="../static/js/main.js" th:src="@{/js/main.js}"></script> </body> </html> 

Создал пользовательский интерфейс ClientRepositoryCustom:

public interface ClientRepositoryCustom { List<Client> findAnyClient(Long id, String firstName, String lastName, String email, Double balance);} 

Далее, класс, имплементирующий этот интерфейс:

@Repository public class ClientRepositoryCustomImpl implements ClientRepositoryCustom {  @PersistenceContext private EntityManager em;  public ClientRepositoryCustomImpl() { }  @Override public List<Client> findAnyClient(Long id, String firstName, String lastName, String email, Double balance) {     CriteriaBuilder cb = em.getCriteriaBuilder();     CriteriaQuery<Client> cq = cb.createQuery(Client.class);      Root<Client> clientRoot = cq.from(Client.class);     List<Predicate> predicates = new ArrayList<>();      if (id != null){         predicates.add(cb.equal(clientRoot.get("id"), id));     }     if (firstName != null){         predicates.add(cb.like(clientRoot.get("firstName"), firstName));     }     if (lastName != null){         predicates.add(cb.like(clientRoot.get("lastName"), lastName));     }     if (email != null){         predicates.add(cb.like(clientRoot.get("email"), email));     }     if (balance != null){         predicates.add(cb.equal(clientRoot.get("balance"), balance));     }     cq.where(predicates.toArray(new Predicate[0]));      return em.createQuery(cq).getResultList(); }} 

И, фрагмент контроллера:

@Controller public class ClientController {  @Autowired private ClientService clientService;  @Autowired private ClientRepositoryCustomImpl clientRepositoryCustom;   @RequestMapping(value = "/clients/find", method = RequestMethod.GET) public String getFindFormCommand(Model model){     model.addAttribute("title", "Find Client");     model.addAttribute("client", new Client());     return "FindFormView"; }  @RequestMapping(value = "/clients/find", method = RequestMethod.POST) public String findClient(@ModelAttribute Client client, Model model,                          @RequestParam(value = "id") Long id,                          @RequestParam(value = "firstName") String firstName,                          @RequestParam(value = "lastName") String lastName,                          @RequestParam(value = "email") String email,                          @RequestParam(value = "balance") Double balance){     model.addAttribute("title", "Find Client");      List<Client> clientList = clientRepositoryCustom.findAnyClient(id, firstName, lastName, email, balance);     model.addAttribute("clientList", clientList);      return "ViewCommand"; }} 

Укажите, что делаю не так? Где ошибки, – почему не работает поиск?

Как работает @Async в Spring

Хочу понять что происходит внутри анотации @Async. В частности использует ли Spring пул потоков? Как его можно конфигурировать?

И что является лучшей практикой для асинхронных вызовов: @Async или вручную запускать на своем пуле потоков.

Spring Security подменяет сессию

Я пытаюсь настроить Spring Security, и у меня есть одна проблема.

это мой SessionAuthenticationFilter:

public class SessionAuthenticationFilter extends OncePerRequestFilter {      @Override     protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)             throws ServletException, IOException {          HttpSession session = request.getSession();         User user = (User) session.getAttribute("user");          if (nonNull(user)) {             SimpleGrantedAuthority authority = new SimpleGrantedAuthority(user.getRole());             Authentication authentication = new UsernamePasswordAuthenticationToken(user.getName(), null, singletonList(authority));              SecurityContextHolder.getContext().setAuthentication(authentication);         }          filterChain.doFilter(request, response);     }  } 

Это мой SecurityConfig:

@Configuration @EnableWebSecurity @EnableJdbcHttpSession @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter {      @Bean     public SessionAuthenticationFilter sessionFilter() {         return new SessionAuthenticationFilter();     }      @Bean     public HttpSessionIdResolver httpSessionIdResolver() {         return HeaderHttpSessionIdResolver.xAuthToken();     }      @Override     protected void configure(HttpSecurity http) throws Exception {          http                 .csrf().disable()                 .formLogin().disable()                 .cors()                 .and()                 .httpBasic()                 .and()                 .sessionManagement()                 .sessionCreationPolicy(SessionCreationPolicy.STATELESS)                 .and()                 .addFilterBefore(sessionFilter(), SessionManagementFilter.class)                 .authorizeRequests()                 .antMatchers(                         "/login"                 )                 .permitAll()                 .anyRequest()                 .authenticated();     }  } 

Это мой IndexController:

@RestController public class IndexController {      @RequestMapping(value = "/index", method = RequestMethod.GET)     public ResponseEntity<?> index(HttpSession session) {          System.out.println(session.getId());          return new ResponseEntity<>(HttpStatus.OK);     }  } 

Внутри SessionAuthenticationFilter HttpSession корректный, но когда я пытаюсь получить эту сессию в контроллере, я получаю другую сессию. Почему? Я так понимаю, что это Spring Ыусгкшен. Как это исправить?

Error spring web thymeleaf

Hola me genera un error mi proyecto que no entiendo, antes funcionaba muy bien el hola mundo, pero al intentar implementar una lista extraida de postgre me causa error, y no entiendo el error. seguramente es un error tipico pero como estoy aprendiendo ps ni idea gracias por la ayuda, estan dos archivos mas que son clase persona contiene un idpersona y nombre y IPersonaRepo es una interfaz que hereda lo siguiente

extends JpaRepository<Persona, Integer> 

El controller

package com.javierito.controller;  import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam;  import com.javierito.model.Persona; import com.javierito.repository.IPersonaRepo; @Controller public class DemoController {  private IPersonaRepo repo;  @GetMapping("/saludos") public String saludos(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {     Persona persona= new Persona();     persona.setIdPersona(1);     persona.setNombre("javierito");     repo.save(persona);     model.addAttribute("name", name);     return "greeting";  } @GetMapping("/lista") public String greeting(Model model) {     //logica                                 model.addAttribute("personas", repo.findAll());     return "greeting"; } 

}

El html

    <!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Getting Started: Serving Web Content</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body>     <p th:text="'Hello, ' + $  {name} + '!'" />      <table>         <th:block th:each="per : $  {personas}">             <tr>                 <td th:text="$  {per.idPersona}"></td>                 <td th:text="$  {per.nombre}"></td>             </tr>         </th:block>     </table> </body> </html> 

Este es el mensaje de error que me da en el navegador

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed Jul 10 01:29:31 CLT 2019 There was an unexpected error (type=Internal Server Error, status=500). No message available java.lang.NullPointerException at com.javierito.controller.DemoController.saludos(DemoController.java:21) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ ConnectionHandler.process(AbstractProtocol.java:853) at org.apache.tomcat.util.net.NioEndpoint$ SocketProcessor.doRun(NioEndpoint.java:1587) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$ Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$ WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source)

What’s the best design for a Spring Websocket multi channel chat app

I did the following tutorial about creating a very basic chat app by using Java Spring Boot and Websockets:

https://www.callicoder.com/spring-boot-websocket-chat-example/

Below are some fragments of the code:

src\main\java\com\example\websocketdemo\config\WebSocketConfig.java

package com.example.websocketdemo.config;  import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.*;  @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {      @Override     public void registerStompEndpoints(StompEndpointRegistry registry) {         registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();     }      @Override     public void configureMessageBroker(MessageBrokerRegistry registry) {         registry.setApplicationDestinationPrefixes("/app");         registry.enableSimpleBroker("/topic");   // Enables a simple in-memory broker     } } 

src\main\java\com\example\websocketdemo\controller\ChatController.java

package com.example.websocketdemo.controller;  import com.example.websocketdemo.model.ChatMessage; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.Payload; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.stereotype.Controller;  @Controller public class ChatController {      @MessageMapping("/chat.sendMessage")     @SendTo("/topic/public")     public ChatMessage sendMessage(@Payload ChatMessage chatMessage) {         return chatMessage;     }      @MessageMapping("/chat.addUser")     @SendTo("/topic/public")     public ChatMessage addUser(@Payload ChatMessage chatMessage,                                SimpMessageHeaderAccessor headerAccessor) {         // Add username in web socket session         headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());         return chatMessage;     }  } 

src\main\resources\static\js\main.js (pseudo-code for simplicity)

var username;  function connect() {   username = getUsernameFromUI();   if (username) {       var socket = new SockJS('/ws');       stompClient = Stomp.over(socket);       stompClient.connect({}, onConnected, onError);   } }  function onConnected() {   stompClient.subscribe('/topic/public', onMessageReceived);   stompClient.send("/app/chat.addUser", {}, JSON.stringify({sender: username, type: 'JOIN'})); }  function sendMessage() {   var chatMessage = {     sender: username,     content: getMessageFromUI(),     type: 'CHAT'   };   stompClient.send("/app/chat.sendMessage", {}, JSON.stringify(chatMessage)); }  function onMessageReceived(payload) {     var message = JSON.parse(payload.body);     switch (true) {       case (message.type === 'JOIN'):         message.content = message.sender + ' joined!';         break;       case (message.type === 'LEAVE'):         message.content = message.sender + ' left!';         break;       default:         // nothing special here         break;     }     displayMessage(message); } 

Here there is a diagram related to the example above:

enter image description here

You can edit it through the following link (pencil icon on the bottom) (sorry the long url):

https://www.draw.io/?lightbox=1&highlight=0000ff&edit=_blank&layers=1&nav=1&title=Web%20Socket%20Diagram#R5Vpbd%2BI2EP41nNM8wLHlK49ASLPdbJvddC99FLbAaozlyiKB%2FfWVbMkXbHNpCCYNL1gjaSTP5ZvRWD1jslz%2FSmEcfCI%2BCntA89c947oHgG4MTf4nKJuM4tiSsKDYz0haQXjAP5Gcqagr7KNE0jISIyRkOK4SPRJFyGMVGqSUPFeHzUnoVwgxXKAa4cGDYZ36HfssyKiupRX0W4QXgVpZ12TPEqrBkpAE0CfPJZIx7RkTSgjLnpbrCQqF8KpyuWnpzTdGUcQOmfBl%2BPHh80%2F74xhN7%2Bcz5wYB%2Bq1vZ1yeYLiSL9wDdsj5jeeEs%2BW7ZhspCvufFVEd%2FSRV1IgP0O14XXTyp4X8T7nMqKI8xBRHCz7hO5olxHtEgvsojtVIvvFsyTYGUor5fgAlq8hH4u003v0cYIYeYuiJ3mdujJwWsGXIWzp%2FfEKUYa7WUYgXEacxEuc8RR9at4pVz5XFrRyRJWJ0w4fICZbSrzRw3ZQG%2FlyYi6WMIiiZijmUwofSRBc570KL%2FEEq8gilqpcoyQr53Kplk1AWkAWJYDgtqOOqNIsxd0RIKpXh34ixjXRRuGKkKmEuL7r5wRt9baAZivCXYDgwbEcRrtdyiay1KbfuEcVcBIhKYvYaYu%2B7lcNflayoh3bIxJXYAekCsR3jdLdZ2xSFkOGn6kZOrjm35o6fUJIIiALaLYz8ENEmx7iBwo9uvACyAfT9r0nzsJf4zyk8ZVj1FDC0ap6i2w2eomgnF%2FfwbOj39QMfPAkxStn%2BogYkMYzUkISRZZwNuSqBYnlIK1ZeJDLa%2B4ERWE3AqL0WMOqgC2A8IYrpKgXaB2Odohgwa36VoMhvM%2Fzf%2Fvjwe4vBXx0AY9xAWVXgFHEHhbN0gNBZTHDE0pe0xj3rmlOgtHWPa0BEm5oTLLHvp9oP4QyFY%2Bg9LlI7mJCQ0HRdY57%2BdrmKzEnlTopMsKz5HXba6lg8wBoakOB1sEolu3shjILXsOKjTnU6mc8Tkadt2UO%2Boxd4ot4KvT5%2B2sa7CkxyS8qD4j6U3MNLRc6dbLYmpEH2iClb8bg2oxW69bME5fy8Ii3AUO1yUHYaUNp6raCsG2%2FaNA7ZxKXp3AFd69y8oMC8PwobB0Zh3TpYNWeKzE5rZJ7cjv68ehfB1dwbXHXTOElwVVHu3NEVdJLn7ioA2FrXBQDlixdeAVDbfEkJoCEEXXAZQNSGui0D6PWyy4EZB3eaxx253a5kY3%2F%2BwQ%2Fi2OP%2F8WoWioejFulYya7pVpQM9IZaT1NVNM8%2FTx%2F7tJpUzg2KOSEDRR10DorDNwGKoH4kSFazxKN4ht5DylL6XtSSsvD4Wj3Jg9MkMKDC1D1XAqO3V2b3nQELuzgKL1vQ9qC42c2pLVdHZ6c2VTw6M6KuMfuh8JE%2FZ1jqmo5sF1AqGptS4zWB9NDvS6BTIDW0ml9R5CGxbt3gHS4gLSvO8tVsuBQ2Hc2SuMX1xAnyqIJJK9cDZt9NR9%2BmbeOd6%2FdZN84cshVBRJioArp%2Bmiix9aEHnCtMgKMS9z2Rg0TyzPQl8wj%2FP6X1l5XsdxOZzIYvfeeNTIbbaa6vDaxypp%2F3tWT5J4xDhvMmEnqjnt9JQP%2F%2Fg7TRIvlS%2FdGw3JcBs3TEvr7lYK8HxUa9slxTZhLAWDziZXrpbv8lBEW9E3q6JwlmmIjeGWGMLA9TYLrYKImzy4HCYqBqzPFauPtY7uc6YEzcKhwJ4YAbz4%2F0AeZqnmMOC3Tg8RU57kIG%2BZ%2BgJ%2Fw%2FgM%2FyyRAydTQNmEZf9PYd0A8F1EU4WvR14A5icf3tBOUzswK2%2Bf2zEtg6dh1rnde6VGHW7xCu0g%2Bemo8T6SUimO717ISJaprSYUQiYSNzHIZbpMP9uyn0VVH%2BBAqxtw7JlmvXFGI2BD9wfPDjzeK%2BaOa5xa1bY%2Fov

My Question Is:

What would be the best design for a similar app if now I have the following requirements (similar to a typical chat app, for example: IRC):

  • there are multiple public channels (with N users at the same time) simultaneously
  • there are multiple private channels (with only 2 users) simultaneously
  • of course, private messages can only be read by the 2 involved users

If possible, please provide some code and if you provide some diagram that’s an extra bonus.

Thanks!

Method Code Coverage not covering incase of calling flatMap() in Spring Reactor

First take a look inside the code

   WebClient client = WebClient.create("TEMP URL);          Mono<Employee> employeeMono = client.get()                 .uri("temp url")                 .accept(MediaType.APPLICATION_JSON)                 .retrieve()                 .bodyToMono(Employee.class);          return employeeMono.flatMap(this::employeeMapper);      public EmployeeDTO employeeMapper(Employee employee){     //     //     //     //     } 

I’m calling Code coverage in IntellijIDEA, all lines are covered but employeeMapper() unable in case of if I using Mono with FlatMap method.

I need to covered the employeeMapper(), please suggest me what should I need to do so that code inside the employeeMapper() also covered.

Please let me know in case you need more clarification.

Thanks in advance Yasir

Непонятный warning в Spring MVC

Есть простейшее приложение: шаблон FreeMarker и контроллер. Все работает, но при обновлении страницы в браузере в логе сервера (использую IntelliJ Idea) вываливаются предупреждения

[http-nio-8090-exec-14] WARN org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported] 

Причем всегда три раза, как на приведенном здесь шаблоне, так и на других.

Шаблон index.ftl

<!DOCTYPE html>      <html lang="ru">     <head>     <meta charset="UTF-8">             <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">             <title>Security</title>              <link href="/css/bootstrap.min.css" rel="stylesheet">             <link href="/css/common.css" rel="stylesheet">         </head>         <body>         <div class="container">             <ul class="nav nav-pills justify-content-end navbar">                 <li class="nav-item">                     <a class="nav-link active" href="/login">Sign In</a>                 </li>             </ul>             <header>                 <h2 class="m-5 font-weight-bold text-center">Welcome!</h2>             </header>               <footer>                 <p class="m-4 text-muted text-center">&copy; 2019</p>             </footer>     </div> <script src="/js/bootstrap.min.js"></script> </body> </html> 

Контроллер

@Controller  public class MainController {          @Autowired         private UserService userService;          @GetMapping("/")         public String view() {              List<User> userList = userService.getAll();              if (userList.isEmpty())                 return "first-time-enter";             else                 return "index";         }  } 

Как избавиться от этого варнинга?