Обновить таблицу базы данных из формы JSP - PullRequest
0 голосов
/ 26 июня 2019

У меня есть представление jsp, где я отображаю набор параметров (флажки и тестовые поля), которые пользователь может изменить и сохранить изменения.Параметры хранятся в сущности с именем «PropertiesEnvironment», которая расширяет сущность «Environment».Я могу правильно отобразить параметры, но не могу понять, как сохранить изменения, как только пользователь внесет изменение.

Я пытался сделать это с сервлетами, но всегда получаю ошибку нулевого указателя.

Вот мой объект PropertiesEnvironment:

@Entity
public class PropertiesEnvironment extends Environment implements Serializable {
    private PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();

    public PropertiesEnvironment() {
    }

    private Long lastPurgeTimestamp;

    @Column
    public Long getLastPurgeTimestamp() {
        return lastPurgeTimestamp;
    }

    public void setLastPurgeTimestamp(Long lastPurgeTimestamp) {
        this.lastPurgeTimestamp = lastPurgeTimestamp;
    }

  @Column(length=500000)
  @Lob
  @Type(type = "serializable")
  public Map<String, Serializable> getProperties() {
        return propertiesConfiguration.getProperties();
    }
    public void setProperties(Map<String, Serializable> properties) {
        propertiesConfiguration.setProperties(properties);
    }
    public int getIntValue(String tag, String defaultValue) {
        return propertiesConfiguration.getIntValue(tag, defaultValue);
    }
    public int getIntValue(String tag) {
        return propertiesConfiguration.getIntValue(tag);
    }
    public boolean getBooleanValue(String property, String defaultValue) {
        return propertiesConfiguration.getBooleanValue(property, defaultValue);
    }
    public boolean getBooleanValue(String tag) {
        return propertiesConfiguration.getBooleanValue(tag);
    }
    public void setBooleanValue(String tag, boolean value) {
        propertiesConfiguration.setBooleanValue(tag, value);
    }
    public String getStringValue(String tag) {
        String v = propertiesConfiguration.getStringValue(tag);
        return v == null ? "" : v;
    }
    public String getStringValue(String tag, String value) {
        return propertiesConfiguration.getStringValue(tag, value == null ? "" : value);
    }
    public void setStringValue(String tag, String value) {
        propertiesConfiguration.setStringValue(tag, value);
    }
    public void setIntValue(String tag, int value) {
        propertiesConfiguration.setIntValue(tag, value);
    }

А это мой объект Environment

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@Table(name = "environment")
public class Environment implements Serializable, Cloneable {

    private static final long serialVersionUID = -6347094896871928639L;

    private long id;

    @ManyToOne
    private String code;

    private String name;

    private Set<String> terminals = new TreeSet<String>();

    @Id//(generate = GeneratorType.AUTO)
    @GeneratedValue
    public long getId() {
        return id;
    }

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

    @Column(length = 30)
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @Column(length = 50)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Мой контроллер:

    @Controller
public class PickingParametersController  {
    @Autowired
    private EnvironmentRepository environmentRepository;
    private PickingParametersRepository pickingParametersRepository;
    private EnvironmentPropertiesService environmentPropertiesService;

    public PickingParametersController(EnvironmentRepository environmentRepository , PickingParametersRepository pickingParametersRepository) {
        this.environmentRepository = environmentRepository;
        this.pickingParametersRepository = pickingParametersRepository;
    }

    @RequestMapping(value = {"/picking"}, method = RequestMethod.POST)
    public String select(HttpServletRequest request , Model model2) throws ServletException, IOException {
        String selected = request.getParameter("dropDownList");// get param from kendo dropdownlist

        List<PropertiesEnvironment> environmentList = pickingParametersRepository.findByCode(selected); // load params by id
        model2.addAttribute("properties",environmentList);
        return "picking";
    }
@RequestMapping(value = "success", method = RequestMethod.POST)
public String save(@ModelAttribute("propertiesEnvironment") PropertiesEnvironment propertiesEnvironment) {
    environmentPropertiesService.update(propertiesEnvironment);
    return "success";
}

    @RequestMapping(value = {"/picking"}, method = RequestMethod.GET)
    public String page(Model model) {
        List<PropertiesEnvironment> codeList = (List<PropertiesEnvironment>) environmentRepository.findAll();
        model.addAttribute("code",codeList);
        return "picking";
    }
}

Мой интерфейс репозитория

@Repository
public interface PickingParametersRepository extends CrudRepository<PropertiesEnvironment, String> {
    @Query("SELECT E.properties FROM Environment E WHERE E.code = :code")
    List<PropertiesEnvironment> findByCode (@Param("code") String code);

EnvironmentProperties Service

public interface EnvironmentPropertiesService {

public  PropertiesEnvironment update(PropertiesEnvironment propertiesEnvironment);

EnvironmentPropertiesServiceImpl

    @Transactional
@Service("environmentPropertiesService")
public class EnvironmentPropertiesServiceImpl implements EnvironmentPropertiesService{

    @Autowired
    private PickingParametersRepository pickingParametersRepository;

    @Override
    public PropertiesEnvironment update (PropertiesEnvironment propertiesEnvironment){
        return pickingParametersRepository.save(propertiesEnvironment);
    }

И, наконец, строки кода из моей страницы JSP:

<form method="post" modelAttribute="pickingparam" action="${pageContext.request.contextPath }/success">

                                             <c:forEach items="${properties}" var="p">

                                                 ID <input type="text" value="${p.id}"><br>
                                                 Channel <input type="text" value="${p.channel}"><br><br><br>
                                                 Total Lines Assignement    <input type="checkbox" name="totalLinesAssignment" value="1" id="id1"
                                                 <c:if test="${p.totalLinesAssignment == 'true'}">checked="checked"</c:if>/><br>
                                                 Total Lines Support    <input type="checkbox" name="totalLinesSupport" value="1" id="id10"
                                                 <c:if test="${p.totalLinesSupport == 'true'}">checked="checked"</c:if>/><br>
                                                 Total Pick Units Assignement   <input type="checkbox" name="totalPickUnitsAssignment" value="2" id="id2"
                                                 <c:if test="${p.totalPickUnitsAssignment == 'true'}">checked="checked"</c:if>/><br>
                                                 Total Pick Units Support   <input type="checkbox" name="totalPickUnitsSupport" value="3" id="id3"
                                                 <c:if test="${p.totalPickUnitsSupport == 'true'}">checked="checked"</c:if>/><br>
                                                 Inventory Pick Location Activity Type  <input type="text" value="${p.inventoryPickLocationActivityType}"><br>
                                                 Inventory Stock Location Activity Type  <input type="text" value="${p.inventoryStockLocationActivityType}"><br>
                                                 Inventory Last Digits EAN  <input type="text" value="${p.inventoryLastDigitsEAN}"><br>
                                                 Inventory Last Digits SSCC <input type="text" value="${p.inventoryLastDigitsSSCC}"><br>

                                            <input type="submit" value="Save"/>



                                            </c:forEach>

                                           </form>

Вот трассировка стека:

java.lang.NullPointerException: null at com.vocognition.ui.web.controller.PickingParametersController.save (PickingParametersController.java:62) ~ [classes /: na] at sun.reflect.NativeMethodAccessorImpl.invoke0 (собственный метод) ~ [na: 1.8.0_181] at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) ~ [na: 1.8.0_181] в sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) ~ [na: 1.8.0_181] в java.lang.reflect.Method.java:498) ~ [na: 1.8.0_181] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke (InvocableHandlerMethod.java:209) ~ [spring-web-5.0.8.RELEASE.jar: 5.0.8.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest (InvocableHandlerMethod.java:136) ~ [spring-web-5.0.8.RELEASE.jar: 5.0.8.RELEASE] в org.spring.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle (ServletInvocableHandlerMethod.java:102) ~ [spring-webmvc-5.0.8.RELEASE.jar: 5.0.8.RELEASE] в org.smvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod (RequestMappingHandlerAdapter.java:877) ~ [spring-webmvc-5.0.8.RELEASE.jar: 5.0.8.RELEASE] в org.springframework.wec.tod.m.m.RequestMappingHandlerAdapter.handleInternal (RequestMappingHandlerAdapter.java:783) ~ [spring-webmvc-5.0.8.RELEASE.jar: 5.0.8.RELEASE] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.ler.j.jpg (Аннотация: 87) ~ [spring-webmvc-5.0.8.RELEASE.jar: 5.0.8.RELEASE] на org.springframework.web.servlet.DispatcherServlet.doDispatch (DispatcherServlet.java:991) ~ [spring-webmvc-5.0.8.RELEASE.jar: 5.0.8.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService (DispatcherServlet.java:925) ~ [spring-webmvc-5.0.8.RELEASE.jar: 5.0.8.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest (FrameworkServlet.java:974) ~ [spring-webmvc-5.0.8.RELEASE.jar: 5.0.8.RELEASE] в org.springframework.web.servlet.Frameworker.doPost (FrameworkServlet.java:877) ~ [spring-webmvc-5.0.8.RELEASE.jar: 5.0.8.RELEASE] в javax.servlet.http.HttpServlet.service (HttpServlet.java:661) ~ [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.springframework.web.servlet.FrameworkServlet.сервис (FrameworkServlet.java:851) ~ [spring-webmvc-5.0.8.RELEASE.jar: 5.0.8.RELEASE] в javax.servlet.http.HttpServlet.service (HttpServlet.java:742) ~ [tomcat-embed-core-8.5.32.jar: 8.5.32] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:231) ~ [tomcat-embed-core-8.5.32.jar: 8.5.32]в org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:166) ~ [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.tomcat.websocket.server.WsFilter.doFilter (WsFilter.java:52) ~ [tomcat-embed-websocket-8.5.32.jar: 8.5.32]в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:193) ~ [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:166) ~ [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.springframework.web.filter.RequestContextFilter.doFilterInternal (RequestContextFilter.java:99) ~ [spring-web-5.0.8.RELEASE.jar: 5.0.8.RELEASE] в org.springframework.web.filter.OncePerRequestFilter.doFilter (OncePerRequestFilter.java:107) ~ [spring-web-5.0.8.RELEASE.jar: 5.0.8.RELEASE] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:193) ~ [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:166) ~ [tomcat-embed-core-8.5.32.jar: 8.5.32] at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal (HttpPutFormContentFilter.java:109) ~ [spring-web-5.0.8.RELEASE.jar: 5.0.8.RELEASE] в org.springframework.web.filter.OncePerRequestFilter.doFilter (OncePerRequestFilter.java:107) ~ [spring-web-5.0.8.RELEASE.jar: 5.0.8.RELEASE] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:193) ~ [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:166) ~ [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal (HiddenHttpMethodFilter.java:93) ~ [spring-web-5.0.8.RELEASE.jar: 5.0.8.RELEASE] в org.springframework.web.filter.OncePerRequestFilter.doFilter (OncePerRequestFilter.java:107) ~ [spring-web-5.0.8.RELEASE.jar: 5.0.8.RELEASE] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:193) ~ [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:166) ~ [tomcat-embed-core-8.5.32.jar: 8.5.32] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal (CharacterEncodingFilter.java:200) ~ [spring-web-5.0.8.RELEASE.jar: 5.0.8.RELEASE] в org.springframework.web.filter.OncePerRequestFilter.doFilter (OncePerRequestFilter.java:107) ~ [spring-web-5.0.8.RELEASE.jar: 5.0.8.RELEASE] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:193) ~ [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:166) ~ [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.catalina.core.StandardWrapperValve.invoke (StandardWrapperValve.java:198) ~ [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.catalina.core.StandardContextValve.invoke (StandardContextValve.java:96) [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.catalina.authenticator.AuthenticatorBase.invoke (AuthenticatorBase.java:493) [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.catalina.core.StandardHostValve.invoke (StandardHostValve.java:140) [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.java:81) [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.catalina.core.StandardEngineValve.invoke (StandardEngineValve.java:87) [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.catalina.connector.CoyoteAdapter.service (CoyoteAdapter.java:342) [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.coyote.http11.Http11Processor.service (Http11Processor.java:800) [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.coyote.AbstractProcessorLight.process (AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.coyote.AbstractProtocol $ ConnectionHandler.process (AbstractProtocol.java:800) [tomcat-embed-core-8.5.32.jar: 8.5.32]в org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun (NioEndpoint.java:1471) [tomcat-embed-core-8.5.32.jar: 8.5.32] в org.apache.tomcat.util.net.SocketProcessorBase.run (SocketProcessorBase.java:49) [tomcat-embed-core-8.5.32.jar: 8.5.32] в java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1149) [na: 1.8.0_181] в java.util.concurrent.ThreadPoolExecutor $ Worker.run (ThreadPoolExecutor.java:624) [na: 1.8.0_181] в org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run (TaskThread.java:) [tomcat-embed-core-8.5.32.jar: 8.5.32] на java.lang.Thread.run (Thread.java:748) [na: 1.8.0_181]

Любойидеи о том, как я могу сделать обновления базы данных, пожалуйста?Спасибо за любую помощь!

...