Java jQuery内置springMVC表单

Java jQuery内置springMVC表单,java,jquery,spring-mvc,Java,Jquery,Spring Mvc,我在使用SpringMVC和jQuery创建表单时遇到了麻烦 这是我的index.jsp: <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@taglib prefix="sec" uri="http://www.springframework.org/security/tags"%> <%@taglib pr

我在使用SpringMVC和jQuery创建表单时遇到了麻烦

这是我的index.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
    <title>Title Page</title>
    <link type="text/css" rel="stylesheet" href="../css/style.css"></link>
    <script type="text/javascript" src="../js/jquery-2.1.1.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $.ajax({
                dataType:'json',
                url:"http://localhost:8080/Elections/elections/hello",
                success: function(jsondata){
                        $.each(jsondata, function(key,value){
                            $('.notLoggedInResults').append("<p>" + value.name + " has " + value.voices + " voices</p> ");

                        });

                    }
                });
            });

    </script>
    <sec:authorize access="hasRole('ROLE_USER')">
        <script>
        $(document).ready(function(){
            $.ajax({
                dataType:'json',
                url:"http://localhost:8080/Elections/elections/hello",
                success: function(jsondata){
                        $.each(jsondata, function(key,value){

                            $('.loggedInForm #form').append("<form:radiobutton path='name' value=" + value.name + "></form:radiobutton>" + value.name);
                        });
                        $('.loggedInForm #form').append("<input type='submit' value='Vote!'</input>" );
                    }
                });
            $('.notLoggedInResults').css('display', 'none');
            $('.loggedInForm').css('display', 'block');

            $('.loggedInForm #form').css('border', '1px solid red');
            $('.loginSection a').css('display', 'none');
            });
        </script>

    </sec:authorize>
</head>
<body>
    <body>

    <div class="header">

    </div>
    <div class="mainSection">
        <div class="loginSection">
            <p>Login Section</p>
            <a href="login">Login</a>


        </div>
        <div class="resultSection">
            <div class="notLoggedInResults">

            </div>

            <div class="loggedInForm">
                <form:form id = "form" method="POST" commandName="object" action="process">



                </form:form>
            </div>


        </div>

        <div class="infoSection">
            <p>Info Section</p>
            <p>This is a demo Voting application</p>
        </div>



    </div>


    <div class="footer">

    </div>
</body>
</body>
</html>

标题页
$(文档).ready(函数(){
$.ajax({
数据类型:'json',
url:“http://localhost:8080/Elections/elections/hello",
成功:函数(jsondata){
$.each(jsondata,函数(键,值){
$('.notLoggedInResults')。追加(“”+value.name+”具有“+value.voices+”voices

”; }); } }); }); $(文档).ready(函数(){ $.ajax({ 数据类型:'json', url:“http://localhost:8080/Elections/elections/hello", 成功:函数(jsondata){ $.each(jsondata,函数(键,值){ $('.loggedInForm#form').append(“+value.name”); });
$('.loggedInForm#form')。append(假设有一个我想要显示的产品列表,我会这样做:

在下面的表单中,您可以看到,我正在检查ListProducts,这是我使用modelattribute在控制器中添加的一个属性。我将在控制器代码中演示如何操作。 JSP页面:

<h3>Product List</h3>
<c:if test="${!empty listProducts}">
    <table class="tg">
        <tr>
            <th width="80">Product ID</th>

            <th width="120">Product name</th>
            <th width="120">Product description</th>
       </tr>
<c:forEach items="${listProducts}" var="product">
            <tr>
                <td>${product.productid}</td>
                <td>${product.productname}</td>
                <td>${product.productdescription}</td>
       </tr>
 </table>
</c:if>
Servlet-context.xml:

如果您使用的是hibernate,那么您将使用绑定到会话工厂的Bean,或者跳过sesionfactory部分

   <beans:bean id="canvasDAO" class="com.journaldev.spring.dao.CanvasDAOImpl">
        <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
    </beans:bean>

    <beans:bean id="canvasService" class="com.journaldev.spring.service.CanvasServiceImpl">
        <beans:property name="canvasDAO" ref="canvasDAO"/>
    </beans:bean>

如您所见,我正在调用listProduct,它将返回一个列表,并将其显示在表单上…我的模型包含Productid、productname、productdescription。如果我错误地将productname更改为productXYZ,那么我将得到您看到的错误。
另外,您是否可以发布与您的服务相关的bean代码,该模型的DAO?

有两个可能的问题,您是否可以将声明了“name”参数的模型代码放在这里。如果您的模型中有此代码,您是否尝试使用model.addAttribute()?我没有足够的信息发布答案。另外,这不是一个JQuery问题,这是一个Spring MVC问题,当它找不到对'name'变量的引用时会发生。下面是模型:public class VotingObject{String name;public String getName(){return name;}public void setName(String name){this.name=name;}作为回答,我会告诉您我会对这种类型的错误做些什么,只是检查一下。它可能与您的表单页面不完全兼容,但会关闭。@Akshay我已将“model.addAttribute”映射到“/”和“/成功”"@Akshay问题是,我想用jQuery做这件事。用JSTL根本没有问题,但我想用脚本做这件事。我只需要了解问题出在哪里,为什么把普通html放在标记中起作用,而用jQuery做这件事不起作用。DAOBean和这一切有什么关系?我现在看到你的评论了,w您在model.addAttribute中添加了哪些内容?为什么不编辑您的问题以包含更多详细信息。
public class JDBCElectionsDAO implements ElectionsDAO {
    @Autowired
    private DataSource dataSource;

    public List<Candidate> getAllCandidates() {
        List<Candidate> candidateList =  new ArrayList<Candidate>();
        Connection conn = null;
        String sql = "Select * from Candidates";
        try {
            conn = dataSource.getConnection();
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery(sql);
            while(rs.next()){
                Candidate candidate = new Candidate();
                candidate.setName(rs.getString(2));
                candidate.setVoices(rs.getInt(3));
                candidateList.add(candidate);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return candidateList;
    }

    public void insertTheVote(String name) {
        // TODO Auto-generated method stub
        String sql = "update Candidates set voices = voices+1 where name= ?";
        Connection conn = null;
        try {
            conn=dataSource.getConnection();
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, name);
            stmt.execute();
            stmt.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally{
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    public int registerUser(Elector user) {
        // TODO Auto-generated method stub
        String sql = "Insert into users values(?,?,?)";
        Connection conn = null;
        try {
            conn=dataSource.getConnection();
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, user.getName());
            stmt.setString(2, user.getLogin());
            stmt.setString(3, user.getPassword());
            stmt.setBoolean(4, user.isVoted());
            stmt.close();
            return stmt.getUpdateCount();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


        return 0;
    }



    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }





}
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/elections" />
        <property name="username" value="root" />
        <property name="password" value="komato3" />
    </bean>

    <bean id ="electionDataSource" class="ua.macko.dao.impl.JDBCElectionsDAO" >
        <property name="dataSource" ref="dataSource"/>
    </bean>
<h3>Product List</h3>
<c:if test="${!empty listProducts}">
    <table class="tg">
        <tr>
            <th width="80">Product ID</th>

            <th width="120">Product name</th>
            <th width="120">Product description</th>
       </tr>
<c:forEach items="${listProducts}" var="product">
            <tr>
                <td>${product.productid}</td>
                <td>${product.productname}</td>
                <td>${product.productdescription}</td>
       </tr>
 </table>
</c:if>
 @RequestMapping(value="/product/show",method= RequestMethod.GET)
    public String listProducts(Model model){
        User user = userService.getCurrentlyAuthenticatedUser();
        model.addAttribute("product", new ProductBasic());
        model.addAttribute("listProducts",this.productBasicService.listProduct(user));
}
   <beans:bean id="canvasDAO" class="com.journaldev.spring.dao.CanvasDAOImpl">
        <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
    </beans:bean>

    <beans:bean id="canvasService" class="com.journaldev.spring.service.CanvasServiceImpl">
        <beans:property name="canvasDAO" ref="canvasDAO"/>
    </beans:bean>