SpriingMVC Form中的jQuery

时间:2014-11-27 12:56:51

标签: java jquery spring-mvc

我在使用带有jQuery的SpringMVC创建表单时遇到了麻烦;

这是我的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>

我试图用无线电按钮填充表格。

如果我在html中插入标签就可以了。但是如果我像上面那样使用jQuery

我收到错误:

org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsps/index.jsp at line 38

35:                 success: function(jsondata){
36:                         $.each(jsondata, function(key,value){
37:                             
38:                             $('.loggedInForm #form').append("<form:radiobutton path='name' value=" + value.name + "></form:radiobutton>" + value.name);
39:                         });
40:                         $('.loggedInForm #form').append("<input type='submit' value='Vote!'</input>" );
41:                     }


Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:264)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
    org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)

root cause

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'name' available as request attribute
    org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:179)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:199)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:165)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:152)
    org.springframework.web.servlet.tags.form.AbstractCheckedElementTag.autogenerateId(AbstractCheckedElementTag.java:81)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:143)
    org.springframework.web.servlet.tags.form.AbstractSingleCheckedElementTag.writeTagContent(AbstractSingleCheckedElementTag.java:83)
    org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:103)
    org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
    org.apache.jsp.WEB_002dINF.jsps.index_jsp._jspx_meth_form_005fradiobutton_005f0(index_jsp.java:222)
    org.apache.jsp.WEB_002dINF.jsps.index_jsp._jspx_meth_sec_005fauthorize_005f0(index_jsp.java:183)
    org.apache.jsp.WEB_002dINF.jsps.index_jsp._jspService(index_jsp.java:100)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:264)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
    org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)

请帮助理解为什么它会搜索bean&#34; name&#34;而不是&#34;对象&#34;。

这是我的控制器:

@Controller
public class MainController {
    @Autowired
    private ApplicationContext context;
    @RequestMapping(value="hello")
    public @ResponseBody List<Candidate> resultList(){
        ElectionsDAO dao = context.getBean("electionDataSource", JDBCElectionsDAO.class);
        return dao.getAllCandidates();
    }

    @RequestMapping(value="get")
    public String getJson(){
        return "get";
    }

    @RequestMapping(value="register")
    public String register(){
        return "register";
    }

    @RequestMapping(value="/")
    public String mainPage(Model model){
        model.addAttribute("object", new VotingObject());
        return "index";
    }

    @RequestMapping(value="login")
    public String login(){
        return "login";
    }
    @RequestMapping(value="/success")
    public String successRedirect(Model model){
        model.addAttribute("object", new VotingObject());
        return "index";
    }

    @RequestMapping(value="/process", method=RequestMethod.POST)
    public String method(Model model, @ModelAttribute("object") VotingObject object, BindingResult result){
        System.out.println(object.getName());
        ElectionsDAO dao = context.getBean("electionDataSource", JDBCElectionsDAO.class);
        dao.insertTheVote(object.getName());

        return "redirect:/elections/";
    }
}

这是DAO Bean:

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;
    }





}

context.xml中

<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>

1 个答案:

答案 0 :(得分:0)

想象一下,我想要显示的产品列表,我会这样做:

在下面的表格中,您可以看到,我正在检查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>

控制器:

 @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));
}

Servlet-context.xml:

如果你正在使用休眠,那么你使用与会话工厂绑定的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?