简体   繁体   English

在Spring Hibernate中使用@ModelAttribute

[英]Using @ModelAttribute in spring hibernate

Getting error while using @ModelAttribute, tried many of the solutions but could not find any answers 使用@ModelAttribute时出错,尝试了许多解决方案,但找不到任何答案

My controller is 我的控制器是

@RequestMapping(value = "/user", params = "add", method = RequestMethod.POST)
public String postAddUser(
        @RequestParam("name") String name,
        @RequestParam("role") Role role,
        @RequestParam("email_address") String emailAddress
        ) {
    System.out.println("Inside postAddUser");
    User user = new User(name, role,emailAddress);
    user = userRepository.save(user);
    return "redirect:user?id=" + user.getId();
}

My view page is: 我的查看页面是:

<title>Add User</title>
</head>
<body>

    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="col-md-4">
                    <h2>Add User</h2>
                    <form action="user" method="post" role="form">


                        <div class="form-group ">
                            <label for="user">User Name:</label> 
                            <input type="text"
                                class="form-control" name="name" id="name"
                                placeholder="Enter User Name" required>
                        </div>


                        <div class="form-group">
                            <label for="email">Email Address:</label> <input type="email"
                                name="email_address" class="form-control" id="email"
                                placeholder="Enter email Address" required>
                        </div>

                        <div class="form-group">
                            <label for="role">Role:</label> 
                            <select name="role"
                                class="form-control" id="role" placeholder="Enter Role" required>
                                <option disabled selected></option>
                                <c:forEach var="role" items="${roles}">
                                    <option value="${role.value}">${role.name}</option>
                                </c:forEach>
                            </select>
                        </div>

                        <button type="submit" value="Submit" name="add"
                            class="btn btn-info active">Submit</button>
                        <a href="adminHome" class="btn btn-info" role="button">Back</a>

                    </form>


                </div>
                <div class="col-md-4">
                    <div class="col-md-4"></div>
                </div>
            </div>
        </div>
    </div>
</body>

User Bean 用户Bean

@Entity
@Table(name="USER")
public class User extends BaseEntity{

    @Column(name="NAME")
    private String name;

    @Column(name="ROLE")
    private Role role;

    @Column(name = "EMAIL_ADDRESS", nullable = false)
    private String emailAddress;

    public User(){}



    public User(String name, Role role, String emailAddress) {
        super();
        this.name = name;
        this.role = role;
        this.emailAddress = emailAddress;
    }



    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Role getRole() {
        return role;
    }
    public void setRole(Role role) {
        this.role = role;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }



}

I tried using @ModelAttribute in my controller but somehow value for email is null in when it comes to controller side. 我尝试在控制器中使用@ModelAttribute,但在控制器方面,电子邮件的值某种程度上为空。

Below is code for same after changing my code to fit @ModelAttribute. 下面是更改我的代码以适合@ModelAttribute后的相同代码。

Controller side. 控制器端。

@RequestMapping(value = "/user", params = "add", method = RequestMethod.POST)
    public String postAddUser(@ModelAttribute("user")User user) {
        System.out.println("Inside postAddUser");
        System.out.println(user.getId());
        System.out.println(user.getEmailAddress());
        System.out.println(user.getName());
        System.out.println(user.getRole());
        user = userRepository.save(user);
        return "redirect:user?id=" + user.getId();
    }

View page 查看页面

<title>Add User</title>
</head>
<body>

    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="col-md-4">
                    <h2>Add User</h2>
                    <form action="user" method="post" role="form">


                        <div class="form-group ">
                            <label for="user">User Name:</label> 
                            <input type="text"
                                class="form-control" name="name" id="name"
                                placeholder="Enter User Name" value="${user.name}" required>
                        </div>


                        <div class="form-group">
                            <label for="email">Email Address:</label> <input type="email"
                                name="email_address" class="form-control" id="email"
                                placeholder="Enter email Address" value="${user.emailAddress}" value="${role.value}" required>
                        </div>

                        <div class="form-group">
                            <label for="role">Role:</label> 
                            <select name="role"
                                class="form-control" id="role" placeholder="Enter Role" required>
                                <option disabled selected></option>
                                <c:forEach var="role" items="${roles}">
                                    <option value="${role.value}">${role.name}</option>
                                </c:forEach>
                            </select>
                        </div>

                        <button type="submit" value="Submit" name="add"
                            class="btn btn-info active">Submit</button>
                        <a href="adminHome" class="btn btn-info" role="button">Back</a>

                    </form>


                </div>
                <div class="col-md-4">
                    <div class="col-md-4"></div>
                </div>
            </div>
        </div>
    </div>
</body>

Below is the error I am getting 以下是我得到的错误

Inside postAddUser
0
null
Harding Berg
HEAD_OF_DEPARTMENT
Mar 10, 2016 2:49:33 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet spring threw exception
org.hsqldb.HsqlException: integrity constraint violation: NOT NULL check constraint; SYS_CT_10097 table: USER column: 
EMAIL_ADDRESS
    at org.hsqldb.error.Error.error(Unknown Source)
    at org.hsqldb.Table.enforceRowConstraints(Unknown Source)
    at org.hsqldb.Table.insertSingleRow(Unknown Source)
    at org.hsqldb.StatementDML.insertRowSet(Unknown Source)
    at org.hsqldb.StatementInsert.getResult(Unknown Source)
    at org.hsqldb.StatementDMQL.execute(Unknown Source)
    at org.hsqldb.Session.executeCompiledStatement(Unknown Source)
    at org.hsqldb.Session.execute(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(Unknown Source)
    at com.jolbox.bonecp.PreparedStatementHandle.executeUpdate(PreparedStatementHandle.java:203)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHa
ndler.java:122)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
    at com.sun.proxy.$Proxy58.executeUpdate(Unknown Source)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2870)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3381)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:203)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:183)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:167)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:320)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)
    at org.hibernate.ejb.event.EJB3MergeEventListener.saveWithGeneratedId(EJB3MergeEventListener.java:71)
    at org.hibernate.event.internal.DefaultMergeEventListener.saveTransientEntity(DefaultMergeEventListener.java:236)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:216)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:154)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:76)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:900)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:884)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:888)
    at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:879)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEnt
ityManagerCreator.java:365)
    at com.sun.proxy.$Proxy43.merge(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityMan
agerCreator.java:240)
    at com.sun.proxy.$Proxy43.merge(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:329)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMe
thodOn(RepositoryFactorySupport.java:368)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(Re
positoryFactorySupport.java:349)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationI
nterceptor.java:155)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at com.sun.proxy.$Proxy51.save(Unknown Source)
    at in.ac.jmi.controllers.AdminController.postAddUser(AdminController.java:87)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocab
leHandlerMethod.java:96)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMapp
ingHandlerAdapter.java:617)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHa
ndlerAdapter.java:578)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:8
0)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.j
ava:113)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:745)

You have problem with the bellow code : 您对以下代码有疑问:

<input type="email" name="email_address" class="form-control" id="email" placeholder="Enter email Address" value="${user.emailAddress} value="${role.value}" required>

You need to use the exact java object field name at your name attribute of input field to map it from view. 您需要在输入字段的name属性中使用确切的Java对象字段名称,以将其从视图映射。 So use emailAddress instead of email_address. 因此,请使用emailAddress而不是email_address。 I do not understand why you've used two value attributes! 我不明白您为什么要使用两个值属性! Remove value="${role.value}". 删除value =“ $ {role.value}”。

Your code should look like this : 您的代码应如下所示:

 <input type="email" name="emailAddress" class="form-control" id="email" placeholder="Enter email Address" value="${user.emailAddress} required>

As you are using spring you can also use spring tag library here. 当您使用spring时,您也可以在此处使用spring标签库。 If you use <form:input path="emailAddress"> it will automatically bind with user object field emailAddress and show the existing field value at form view. 如果使用<form:input path="emailAddress"> ,它将自动与用户对象字段emailAddress绑定,并在表单视图中显示现有字段值。

Try to use @RequestBody 尝试使用@RequestBody

@RequestMapping(value = "/user", params = "add", method = RequestMethod.POST)
    public String postAddUser@RequestBody User user) {

If you dont want the email adress to be null use the rignte name liek this 如果您不希望电子邮件地址为空,请使用rignte名称liek this

<input type="email" name="emailAddress" class="form-control" id="email" placeholder="Enter email Address" value="${user.emailAddress}" value="${role.value}" required>

I suggest you to use the 我建议您使用

<form:*> 

tag lib to generate your html 标记lib以生成您的html

About the @ModelAttribute : 关于@ModelAttribute:

You should also create a method @ModelAttribute("user") otherwise using it only on a parameter of method is useless. 您还应该创建一个方法@ModelAttribute(“ user”),否则仅在方法的参数上使用它是没有用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring MVC Hibernate使用以下方法添加两个ModelAttribute <form:hidden> - Spring MVC Hibernate add two ModelAttribute's using <form:hidden> 在Spring项目中使用@ModelAttribute时出现SpringInputGeneralFieldAttrProcessor错误 - Error SpringInputGeneralFieldAttrProcessor when using @ModelAttribute in Spring project 春季:在ModelAttribute内部使用GET参数 - Spring: Using GET parameters inside of a ModelAttribute Spring MVC表单使用modelAttribute提交 - Spring MVC form submit using modelAttribute 使用@ResourceMapping和@ModelAttribute在Spring Portlet Controller中访问RequestBody - Access RequestBody inside Spring Portlet Controller using @ResourceMapping and @ModelAttribute 在Spring框架上使用@ModelAttribute(“ myobject”)访问服务器上的JSON - Accessing JSON on server using @ModelAttribute(“myobject”) on spring framework Spring MVC @ModelAttribute 似乎是异步行为(使用 jpa)并且需要它是同步的 - Spring MVC @ModelAttribute seems to behave asynchronously (using jpa) and need it to be synchronous 为什么在 Spring MVC 3.0 中使用 @ModelAttribute 'update()' 不重定向到 'sox'? - Why does 'update()' not redirect to 'sox' using @ModelAttribute in Spring MVC 3.0? Spring MVC注释@ModelAttribute - Spring MVC annotation @ModelAttribute Spring MVC中的不同@ModelAttribute - Different @ModelAttribute in spring mvc
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM