第八天;
答题嘛,最重要的就是答案的正确与否了
思路:
1.把题号和答案通过ajax传到后台
2.拿到题号后去数据库查询答案,进行对比,进行错误次数记录;然后把数据传达前台
onepage.jsp
这个页面里面要添加一段ajax
//检验答案
function checkResult(sid){
var choiceval = "";
$("input[name='"+sid+"']").each(function() {
if($(this).attr("checked"))
{
choiceval=choiceval+$(this).val();
}
});
$.ajax({
type:"post",//请求方式
url:"answer/check.action",//请求路径
data:{//传参
subjectid:sid,
choice:choiceval
},
success:function(data){
$("#"+sid).html(data);
}
});
};
struts.xml
对应的配置文件也发生了变化,要添加一段action
<action name="check" class="subjectAction" method="check"/>
SubjectAction.java
一个个来
/**
* 答案检测
*
* @throws IOException
*/
@Autowired
ErrorsubjectService errorsubjectService;
String choice;
Long subjectid;
public String getChoice() {
return choice;
}
public void setChoice(String choice) {
this.choice = choice;
}
public Long getSubjectid() {
return subjectid;
}
public void setSubjectid(Long subjectid) {
this.subjectid = subjectid;
}
public void check() throws IOException {
PrintWriter out = ServletActionContext.getResponse().getWriter();
String outputstr = "";
boolean result = subjectService.check(subjectid, choice);
if (result) {
outputstr = "success";
} else {
errorsubjectService.errorsubjectSaveOrUpdate(subjectid);
outputstr = "error>>正确答案是:"
+ subjectService.findById(subjectid).getResulter();
}
// 强制刷新
out.write(outputstr);
out.flush();
out.close();
}
SubjectService.java
添加判断答案的代码
public Subject findById(Long subjectid){
return subjectDAO.findById(subjectid);
}
/**
* 答案校准
*
* @param subjectid
* @param choice
* @return
*/
public boolean check(Long subjectid, String choice) {
Subject sub = findById(subjectid);
if (sub.getResulter().equals(choice)) {
return true;
} else {
return false;
}
}
ErrorsubjectService.java
添加如下代码
Userinfo userinfo = (Userinfo) ServletActionContext.getRequest()
.getSession().getAttribute("userinfo");
public void errorsubjectSaveOrUpdate(Long subjectid) {
Errorsubject errorsubject = new Errorsubject();
errorsubject.setUserinfo(userinfo);
Subject sb = new Subject();
sb.setSubjectid(subjectid);
errorsubject.setSubject(sb);
long userid = userinfo.getUserid();
List<Errorsubject> list = errorsubjectDAO.findByUidSid(userid,subjectid);
errorsubject.setErrordate(new Date());
long degree = 1;
if(list.size() > 0){
Errorsubject es = (Errorsubject) list.get(0);
degree = es.getErrordegree();
degree = degree+1;
errorsubject.setErrordegree(degree++);
errorsubject.setErrorid(es.getErrorid());//区分更新与保存的重要信息
errorsubjectDAO.merge(errorsubject);//更新错误信息
}else{
errorsubject.setErrordegree(degree);
errorsubjectDAO.save(errorsubject);//保存错误信息
}
}
ErrorsubjectDAO.java
添加如下代码
public List<Errorsubject> findByUidSid(Long userid, Long subjectid) {
String queryString = "from Errorsubject as e where e.userinfo.userid='"+userid+"' and e.subject.subjectid = '"+subjectid+"'";
return getHibernateTemplate().find(queryString);
}