Здравствуйте. Разбираюсь с Spring Annotations. Сначала использовал обычные xml'ы - все у меня работает. А вот решил перевести в аннотации и тут не получается. Подскажите пожалуйста, где я не прав. есть страница, форма. На ней вопрос и ответы(радиоБуттоны). выбираю вариант ответа, сабмитю форму(отправка сделана с помощью ajax'a, метод POST) после этого в форму должен придти следующий вопрос, с своими вариантами ответа. Но этого не происходит. на странице остается тот-же вопрос, как будто не работает доставка данных к контроллеру. Без спрингАннотаций это работает. так как первый вопрос загружается, значить обмен с БД есть. Проблема наверное в контроллере: вот исходники: контроллер:| Код | package com.testapp.web;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView;
import com.testapp.dao.QuestionDAO; import com.testapp.entity.Answer; import com.testapp.entity.Question; import com.testapp.service.QuestionSize; import com.testapp.service.Score;
@Controller public class QuestionController { private QuestionDAO questionDAO; private Score score; private QuestionSize questionSize; @Autowired public void setQuestionDAO(QuestionDAO questionDAO){ this.questionDAO = questionDAO; } @Autowired public void setScore(Score score){ this.score = score; } @Autowired public void setQuestionSize(QuestionSize questionSize){ this.questionSize = questionSize; } @RequestMapping(value = "/test.htm", method = RequestMethod.GET) public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws Exception { if ((request.getParameter("answers") != null) && (questionSize.getQuestionSize() >= -1)){ byte answId = java.lang.Byte.parseByte(request.getParameter("answers")); for (Answer answ : questionDAO.listQuestion().get(questionSize.getQuestionSize()).getQuestionAnswers()){ if ((answ.getId() == answId) && (answ.getIsTrue() == 1)){ score.incScore(); } } questionSize.decQuestionSize(); } if (questionSize.getQuestionSize() == -1) return new ModelAndView("redirect:result.htm"); ModelMap modelMap = new ModelMap(); modelMap.addAttribute("questionList", questionDAO.listQuestion().get(questionSize.getQuestionSize())); modelMap.addAttribute("question", new Question()); modelMap.addAttribute("answerSet", questionDAO.listQuestion().get(questionSize.getQuestionSize()).getQuestionAnswers()); modelMap.addAttribute("answer", new Answer()); return new ModelAndView("test", modelMap); } @RequestMapping(value = "/result.htm", method = RequestMethod.GET) public ModelAndView result(HttpServletRequest request, HttpServletResponse response) throws Exception { return new ModelAndView("result", "score", Math.round(100*score.getScore()/questionSize.getQuestionSizeRes())); } @RequestMapping(value = "/restart.htm", method = RequestMethod.GET) public ModelAndView restart(HttpServletRequest request, HttpServletResponse response) throws Exception {
questionSize.setQuestionSize((byte)(questionDAO.listQuestion().size()-1)); score.setScore((byte)0); return new ModelAndView("redirect:test.htm"); } }
|
test.jsp| Код | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="css/style.css"> <script type="text/javascript" src="javascript/jquery.js"></script> <script type="text/javascript" src="javascript/func.js"></script> <title>Система проверки знаний</title> </head> <script type="text/javascript"> <!-- // return the value of the radio button that is checked // return an empty string if none are checked, or // there are no radio buttons function getCheckedValue(radioObj) { if(!radioObj) return ""; var radioLength = radioObj.length; if(radioLength == undefined) if(radioObj.checked) return radioObj.value; else return ""; for(var i = 0; i < radioLength; i++) { if(radioObj[i].checked) { return radioObj[i].value; } } return ""; } //--> $(document).ready(function(){ $('#myForm').live('submit', function(){ var idr = getCheckedValue(document.forms['testForm'].elements['answers']); $.ajax({ type: "POST", url: "test.htm", data: "answers="+idr, success: function(html){ $("#content").html(html); } }); return false; });
//setInterval('gg()',7000); });
</script> <body > <div id="content"> <div id="nifty"> <form:form id="myForm" name="testForm" commandName="quest"> <center> <table cellpadding=4 cellspacing=2 border=0> <tr> <td class="question" colspan="2">${questionList.question}</td> </tr> <c:forEach items="${answerSet}" var="answer" varStatus="status"> <tr > <td width="20"> <input type="radio" name="answers" value="${answer.id}" checked "></td> <td> <label>${answer.answer}</label> </td> </tr> </c:forEach> <tr> <td colspan="2" align=center><input type="submit" id="subm" value="Дальше"></td> </tr> </table> </center> </form:form> </div>
</div> </body> </html>
|
Работа с базой:CustomHibernateDaoSupport| Код | package com.testapp.dao;
import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public abstract class CustomHibernateDaoSupport extends HibernateDaoSupport { @Autowired public void anyMethodName(SessionFactory sessionFactory) { setSessionFactory(sessionFactory); } }
|
QuestionDAOImpl| Код | package com.testapp.dao;
import java.util.List;
import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Repository; import com.testapp.dao.CustomHibernateDaoSupport; import com.testapp.dao.QuestionDAO; import com.testapp.entity.Question;
@Repository public class QuestionDAOImpl extends CustomHibernateDaoSupport implements QuestionDAO{
@Override public void saveQuestion(Question question) {
getHibernateTemplate().saveOrUpdate(question); } @Override @SuppressWarnings("unchecked") public List<Question> listQuestion()throws DataAccessException { return getHibernateTemplate().find("from Question"); } }
|
dispatcher-servlet.xml| Код | <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/tx" 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-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- Auto scan the components --> <context:component-scan base-package="com.testapp" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
|
|