Java Spring - 从jsp表单

时间:2016-06-30 18:23:19

标签: java spring jsp model-view-controller

我对Maven Web应用程序有一个非常讨厌且令人沮丧的问题,让我退了一段时间。 显然,从我以前的谷歌搜索,这是一个常见的Spring MVC错误,但我无法找到我需要的解决方案到目前为止在互联网上提供的解决方案。请注意,我是Spring的初学者和一般的MVC概念。

我有一个网络应用程序,应该管理建筑物管理(居民,租金计算等)。我使用Spring MVC,Hibernate,Java 1.8,Tomcat 8服务器容器和SQL Server 2014。 首先,这是我的POJO为建筑居民,一种称为居民:

@Entity
@Table (name = "INHABITANT")
public class Inhabitant {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "ID")
    private long id;

    @Column(name = "FIRSTNAME")
    private String firstName;

    @Column(name = "LASTNAME")
    private String lastName;

    @Column(name = "APARTAMENT_NUMBER")
    private String apartamentNumber;

    @Column(name = "APARTAMENT_OWNER")
    private String apartamentOwner;

    @Column(name = "TELEPHONE_NUMBER")
    private String telephoneNumber;

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

    public long getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getApartamentNumber() {
        return apartamentNumber;
    }

    public void setApartamentNumber(String apartamentNumber) {
        this.apartamentNumber = apartamentNumber;
    }

    public String getApartamentOwner() {
        return apartamentOwner;
    }

    public void setApartamentOwner(String apartamentOwner) {
        this.apartamentOwner = apartamentOwner;
    }

    public String getTelephoneNumber() {
        return telephoneNumber;
    }

    public void setTelephoneNumber(String telephoneNumber) {
        this.telephoneNumber = telephoneNumber;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

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

这是我的dispatcher-servlet.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans     
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="laura.bachelordegree.controller" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

这是我的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"> <!-- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 
        version="3.1" -->
    <display-name>BuildingAdministration</display-name>
    <welcome-file-list>
        <welcome-file>login/index.jsp</welcome-file>
    </welcome-file-list>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
</web-app>

这是我的jsp注册表单,应该映射到Inhabitant对象:

<!DOCTYPE html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@page session="false" %>
<html>
<head>
    <meta charset="utf-8" />
    <title>Registration</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="stylesheet" type="text/css" href="login/bootstrap/css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="login/font-awesome/css/font-awesome.min.css" />

    <script type="text/javascript" src="login/js/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="login/bootstrap/js/bootstrap.min.js"></script>
</head>
<body> 

<!-- Registration form - START -->
<div class="container">
    <div class="row">
       <%--  <form role="form"> --%>
        <form:form method="post" modelAttribute="inhabitant" role="form" action="BuildingAdministration/src/main/webapp/login/result">
            <div class="col-lg-6">
                <div class="well well-sm"><strong><span class="glyphicon glyphicon-asterisk"></span>Required Field</strong></div>
               <div class="form-group">
                    <label for="InputFirstName">Enter First Name</label>
                    <div class="input-group">
                        <form:input path="firstName" type="text" cssClass="form-control" id="InputFirstName" />
                        <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
                    </div>
                </div> 
                <div class="form-group">
                    <label for="InputLastName">Enter Last Name</label>
                    <div class="input-group">
                        <form:input path="lastName" type="text" cssClass="form-control" id="InputLastName" />
                        <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
                    </div>
                </div>
                <div class="form-group">
                    <label for="InputApartmentNumber">Enter Apartment Number</label>
                    <div class="input-group">
                        <form:input path="apartmentNumber" type="text" cssClass="form-control" id="InputApartmentNumber" />
                        <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
                    </div>
                </div>
                <div class="form-group">
                    <label for="InputApartmentOwner">Enter Apartment Owner</label>
                    <div class="input-group">
                        <form:input path="apartmentOwner" type="text" cssClass="form-control" id="InputApartmentOwner" />
                        <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
                    </div>
                </div>
                <div class="form-group">
                    <label for="InputTelephoneNumber">Enter Telephone Number</label>
                    <div class="input-group">
                        <form:input path="telephoneNumber" type="text" cssClass="form-control" id="InputTelephoneNumber" />
                        <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
                    </div>
                </div>
                <div class="form-group">
                    <label for="InputEmail">Enter Email</label>
                    <div class="input-group">
                        <form:input path="emailAddress" type="email" cssClass="form-control" id="InputEmailFirst" />
                        <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
                    </div>
                </div>
                <div class="form-group">
                    <label for="InputEmail">Confirm Email</label>
                    <div class="input-group">
                        <form:input path="emailAddress" type="email" cssClass="form-control" id="InputEmailSecond" />
                        <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
                    </div>
                </div>
                <input type="submit" name="submit" id="submit" value="Submit" class="btn btn-info pull-right">
            </div>
          </form:form>
        <%-- </form> --%>
        <div class="col-lg-5 col-md-push-1">
            <div class="col-md-12">
                <div class="alert alert-success">
                    <strong><span class="glyphicon glyphicon-ok"></span> Success! Message sent.</strong>
                </div>
                <div class="alert alert-danger">
                    <span class="glyphicon glyphicon-remove"></span><strong> Error! Please check all page inputs.</strong>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Registration form - END -->

</body>
</html>

最后,控制器类应该有效地将来自jsp表单的数据映射到java实体,Inhabitant:

@RequestMapping(value = "/index", method = RequestMethod.GET)
public String loadInhabitant(@ModelAttribute("inhabitant")Inhabitant inhabitant, 
           ModelMap model) {
      model.addAttribute("firstName", inhabitant.getFirstName());
      model.addAttribute("lastName", inhabitant.getLastName());
      model.addAttribute("apartmentNumber", inhabitant.getApartamentNumber());
      model.addAttribute("apartmentOwner", inhabitant.getApartamentOwner());
      model.addAttribute("apartmentNumber", inhabitant.getApartamentNumber());
      model.addAttribute("telephoneNumber", inhabitant.getTelephoneNumber());
      model.addAttribute("emailAddress", inhabitant.getEmailAddress());
    return "result";
}

现在,这是我每次尝试在服务器上运行应用程序时出现的错误:

message java.lang.IllegalStateException:BindingResult和bean名称'inhabitant'的普通目标对象都不可用作请求属性

说明服务器遇到内部错误,导致无法完成此请求。

  

异常org.apache.jasper.JasperException:   java.lang.IllegalStateException:既不是BindingResult也不是普通的   bean名称'居民'的目标对象可根据要求提供   属性     org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:555)     org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:471)     org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)     org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)     javax.servlet.http.HttpServlet.service(HttpServlet.java:729)     org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

     

root cause java.lang.IllegalStateException:既不是BindingResult也不是   bean名称'居民'的普通目标对象可根据要求提供   属性     org.springframework.web.servlet.support.BindStatus。(BindStatus.java:144)     org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)     org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)     org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:154)     org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:117)     org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:422)     org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:142)     org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)     org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)     org.apache.jsp.login.index_jsp._jspx_meth_form_005finput_005f0(index_jsp.java:322)     org.apache.jsp.login.index_jsp._jspx_meth_form_005fform_005f0(index_jsp.java:216)     org.apache.jsp.login.index_jsp._jspService(index_jsp.java:148)     org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)     javax.servlet.http.HttpServlet.service(HttpServlet.java:729)     org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)     org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)     org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)     javax.servlet.http.HttpServlet.service(HttpServlet.java:729)     org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

我尝试过一千件事,但我无法让它发挥作用。那么,拜托,有人可以指出我做错了什么吗?如何根据jsp表单中的信息正确构建java对象?

提前致谢!

2 个答案:

答案 0 :(得分:1)

  

您似乎需要了解有关spring mvc的更多信息。

您正在将表单请求映射到视图。您必须将表单请求映射到控制器方法而不是视图,您的表单应如下所示:

<form:form action="${pageContext.request.contextPath}/inhabitant/create" method="post" modelAttribute="inhabitant" >
   ....
   // have a look at spring form validation 
   // have a look at spring form elements eg. how error messages are displayed
</form:form>

在控制器中需要两种方法来创建和保存居民,一种用于显示表单,另一种用于将表单数据保存到数据库中。现在您的控制器应如下所示:

@Controller
@RequestMapping(value="/inhabitant")
public class PostController {

@Autowired
private InhabitantService inhabitantService;

//Method that displays the form page
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String createForm(Model model ) {

    model.addAttribute("inhabitant", new Inhabitant()); // identifier should be same as modelattribute in your form "inhabitant"
    return "formpage"; // your form page name

}

// Method which will have the submitted data
// Validation is also done in this method
@RequestMapping(value="/create", method=RequestMethod.POST)
public String saveForm( @ModelAttribute("inhabitant") @Valid Inhabitant inhabitant, //@valid is used for validation use it If you are doing validation
        BindingResult result // use only if you are doing validation)
{
       // use only If you are doing validation
       // If validation fails users must return to the same form view
       if (result.hasErrors()){
           return "formpage";
       }

       //and save the submitted form data
       inahabitantService.saveInhabitant(inhabitant);
enter code here
       return "success"; // success.jsp is a success page that you will see after creating a inhabitant
}

请勿使用&#39; / login&#39;作为web.xml中的url patern 就是不要这样做。

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/login</url-pattern> //Just Use '/' instead of '/login'
</servlet-mapping>

我怀疑你是否正确配置了hibernate 发布你的hibernateConfiguration.xml文件和persistence.xml文件。

你必须学习并理解这些:只是慢慢来。

  • Spring Model Controller View以及它是如何工作的
  • Spring Form元素,Spring Form Validation
  • hibernate中的Jpa / hibernate基础/关联
  • Jsp / Apache Tiles中的Jsp taglibs / JSP

答案 1 :(得分:-1)

不要那样做

  model.addAttribute("firstName", inhabitant.getFirstName());
  model.addAttribute("lastName", inhabitant.getLastName());
  model.addAttribute("apartmentNumber", inhabitant.getApartamentNumber());
  model.addAttribute("apartmentOwner", inhabitant.getApartamentOwner());
  model.addAttribute("apartmentNumber", inhabitant.getApartamentNumber());
  model.addAttribute("telephoneNumber", inhabitant.getTelephoneNumber());
  model.addAttribute("emailAddress", inhabitant.getEmailAddress());

改为

model.addAttribute("inhabitant", inhabitant);