图片 42

试验系统,本人做的3个记名页面

Posted by

先上效果图吧. 本人菜鸟入门, 请勿喷.

考试系统 (0607)

SpringMVC中的异常处理集锦,springmvc异常处理

1 描述 
在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的、不可预知的异常需要处理。每个过程都单独处理异常,系统的代码耦合度高,工作量大且不好统一,维护的工作量也很大。 
那么,能不能将所有类型的异常处理从各处理过程解耦出来,这样既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护?答案是肯定的。下面将介绍使用Spring
MVC统一处理异常的解决和实现过程。 
2 分析 
Spring MVC处理异常有3种方式: 
(1)使用Spring
MVC提供的简单异常处理器SimpleMappingExceptionResolver; 
(2)实现Spring的异常处理SimpleMappingExceptionResolver自定义自己的异常处理器; 

(3)实现HandlerExceptionResolver 接口自定义异常处理器 
(4)使用注解@ExceptionHandler实现异常处理; 

3 实战

一:使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver

图片 1

源码介绍:

1.lib包(jar包)和web.xml配置

图片 2

图片 3

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name></display-name>
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

View Code

2.index.jsp(测试页面入口)和 error.jsp(有错误则会跳到此页面)和 hello.jsp(没错误则会跳到此页面)

图片 4

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>异常处理器测试</title>
</head>
<body>
    <form action="frist.do" method="post">
        <input type="submit" value="测试" />
    </form>
</body>
</html>

View Code
图片 5

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>这是错误页面</title>
  </head>
  <body>
       这是错误页面  ${ex.message }
  </body>
</html>

View Code
图片 6

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>成功欢迎页面</title>
  </head>
  <body>
       你竟然没报错<br/>
  </body>
</html>

View Code

3.MyController,java(定义自己的处理器)

图片 7

package cn.zhang.controller;
//定义自己的处理器
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class MyController{

    @RequestMapping(value="/frist.do",produces="text/html;charset=utf-8",method=RequestMethod.POST)
    public String frist(){
        //制造一个异常
        int i=5/0;
        System.out.println(i);
        return "forward:/hello.jsp";
    }
}

View Code

4.applicationContext.xml(Spring的配置文件)

图片 8

<?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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 使用注解方式完成映射 -->
    <context:component-scan base-package="cn.zhang.controller"></context:component-scan>
    <!-- mvc的注解驱动 -->
    <mvc:annotation-driven />
    <!-- 注册系统异常处理器 -->
    <bean
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="defaultErrorView" value="error.jsp"></property>
        <property name="exceptionAttribute" value="ex"></property>
    </bean>

</beans>

View Code

测试展示:

图片 9

点击测试,由于我们在自己的处理器制造了一个异常,所以它会跳到错误页面

图片 10

二:实现Spring的异常处理接口SimpleMappingExceptionResolver自定义自己的异常处理器

图片 11

源码介绍:

1.lib包和web.xml一样(不做解释)

2.error包中是指定错误页面

  ageerrors.jsp

图片 12

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>年龄错误页面</title>
</head>
<body>年龄错误   ${ex.message }
</body>
</html>

View Code

  nameerrors.jsp

图片 13

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>名字错误页面</title>
  </head>
  <body>
   名字错误
   ${ex.message }
  </body>
</html>

View Code

3.MyController.java

图片 14

package cn.zhang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.zhang.exception.AgeException;
import cn.zhang.exception.NameException;
import cn.zhang.exception.UserException;

//定义自己的处理器

@Controller
public class MyController{

    @RequestMapping(value="/frist.do")
    public String frist(Model model,String name,int age) throws UserException{
        if (name.equals("admin")) {
            throw new NameException("用户名错误");    
        }
        if (age>50) {
            throw new AgeException("年龄过大");
        }
        return "forward:/hello.jsp";
    }
}

View Code

4.exception包下,指定我们的异常类

 UserException.java

图片 15

package cn.zhang.exception;
//定义UserException继承Exception
public class UserException extends Exception {

    private static final long serialVersionUID = 1L;

    public UserException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public UserException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

}

View Code

 AgeException.java

图片 16

package cn.zhang.exception;
//继承UserException父类
public class AgeException extends UserException {

    private static final long serialVersionUID = 1L;

    public AgeException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public AgeException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }



}

View Code

 NameException.java

图片 17

package cn.zhang.exception;
//继承UserException父类
public class NameException extends UserException {

    private static final long serialVersionUID = 1L;

    public NameException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public NameException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

}

View Code

5.applicationContext.xml(Spring的配置文件)

图片 18

<?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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 使用注解方式完成映射 -->
    <context:component-scan base-package="cn.zhang.controller"></context:component-scan>
    <!-- mvc的注解驱动 -->
    <mvc:annotation-driven />
    <!-- 实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器 -->
    <bean
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="defaultErrorView" value="error.jsp"></property>
        <property name="exceptionAttribute" value="ex"></property>
        <!-- 指定错误到指定页面 -->
        <property name="exceptionMappings">
            <props>
                <prop key="cn.zhang.exception.AgeException">error/ageerrors.jsp</prop>
                <prop key="cn.zhang.exception.NameException">error/nameerrors.jsp</prop>
            </props>
        </property>

    </bean>

</beans>

View Code

结果展示:

图片 19

图片 20

 三:实现HandlerExceptionResolver 接口自定义异常处理器 

 要修改的代码:

 1.MyHandlerExceptionResolver.java–定义自己的异常处理器(实现HandlerExceptionResolver接口)

图片 21

package cn.zhang.resolvers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import cn.zhang.exception.AgeException;
import cn.zhang.exception.NameException;
/**
 * 定义自己的异常处理器(实现HandlerExceptionResolver接口)
 * @author zhangzong
 *
 */
public class MyHandlerExceptionResolver implements HandlerExceptionResolver{

    public ModelAndView resolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex) {

        ModelAndView  mv=new ModelAndView();
        mv.addObject("ex",ex);

        mv.setViewName("/errors.jsp");


        if(ex instanceof NameException){
            mv.setViewName("/error/nameerrors.jsp");
        }

        if(ex instanceof AgeException){
            mv.setViewName("/error/ageerrors.jsp");
        }

        return mv;
    }

}

View Code

 2.applicationContext.xml

图片 22

<?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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 使用注解方式完成映射 -->
    <context:component-scan base-package="cn.zhang.controller"></context:component-scan>
    <!-- mvc的注解驱动 -->
    <mvc:annotation-driven />
    <!-- 注册自定义异常处理器 -->
     <bean class="cn.zhang.resolvers.MyHandlerExceptionResolver"/>
</beans>

View Code

 其他的相同,不作解释

 四:使用注解@ExceptionHandler实现异常处理

 图片 23

源码介绍:

1.其他配置相同(不做解释)

2.MyController.java–继承我们自己定义的注解异常处理器MyHandlerExceptionResolver

图片 24

package cn.zhang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.zhang.exception.AgeException;
import cn.zhang.exception.NameException;
import cn.zhang.exception.UserException;
import cn.zhang.resolvers.MyHandlerExceptionResolver;

//定义自己的处理器
//继承我们自己定义的注解异常处理器MyHandlerExceptionResolver
@Controller
public class MyController extends MyHandlerExceptionResolver{

    @RequestMapping(value="/frist.do")
    public String frist(Model model,String name,int age) throws UserException{
        if (name.equals("admin")) {
            throw new NameException("用户名错误");    
        }
        if (age>50) {
            throw new AgeException("年龄过大");
        }
        return "forward:/hello.jsp";
    }
}

View Code

3.MyHandlerExceptionResolver.java–定义自己的异常处理器(使用注解)

图片 25

package cn.zhang.resolvers;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import cn.zhang.exception.AgeException;
import cn.zhang.exception.NameException;
/**
 * 定义自己的异常处理器(使用注解)
 * @author zhangzong
 *
 */
@Controller
public class MyHandlerExceptionResolver{

    @ExceptionHandler
    public ModelAndView resolveException(Exception ex) {

        ModelAndView  mv=new ModelAndView();
        mv.addObject("ex",ex);

        mv.setViewName("/errors.jsp");


        if(ex instanceof NameException){
            mv.setViewName("/error/nameerrors.jsp");
        }

        if(ex instanceof AgeException){
            mv.setViewName("/error/ageerrors.jsp");
        }

        return mv;
    }

}

View Code

4.applicationContext.xml

图片 26

<?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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 使用注解方式完成映射 -->
    <context:component-scan base-package="cn.zhang.controller"></context:component-scan>
    <!-- mvc的注解驱动 -->
    <mvc:annotation-driven />

    <!-- 注册自定义异常处理器 -->
     <bean class="cn.zhang.resolvers.MyHandlerExceptionResolver"/>
</beans>

View Code

效果和上相同,这里不做展示

 

1
描述
在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控…

图片 27

做一个类似于驾校考试的系统,可以选择要考试试题类型,选好后进入考试页面

首先样式:

使用的数据库表格:timu(题目)表,xuanxiang(选项)表,shiti(试题)表,shititimu(试题题目)表,yhks(用户考试)表, yhkstm(用户考试题目)表

图片 28图片 29

实现的界面:

  1 1 body{
  2   2     margin: 0;
  3   3     padding: 0;
  4   4     width: 100%;
  5   5     height: 100%;
  6   6 }
  7   7 
  8   8 .headers{
  9   9     width: 100%;
 10  10     height: 100px;
 11  11 }
 12  12 .siv-ng{
 13  13     width: 100%;
 14  14     height: 30px;
 15  15     border: 1px solid #ccc;
 16  16     background: #ccc;
 17  17 }
 18  18 
 19  19 .contents{
 20  20     width: 100%;
 21  21     height: 400px;
 22  22     position: relative;
 23  23 }
 24  24 .login{
 25  25     width: 400px;
 26  26     height: 400px;
 27  27     background: #A9B0A4;
 28  28     margin: 0 auto;
 29  29     border-radius: 5px;
 30  30     opacity: 0.8;
 31  31 }
 32  32 
 33  33 .login-img-top{
 34  34     height: 40px;
 35  35 }
 36  36 .login h1{
 37  37     text-align: center;
 38  38 }
 39  39 .form-text{
 40  40     width: 350px;
 41  41     height: 45px;
 42  42     border: 1px solid #ccc;
 43  43     background: white;
 44  44     margin: 0 auto;
 45  45     border-radius: 5px;
 46  46     margin-top: 20px;
 47  47     position: relative;
 48  48 }
 49  49 
 50  50 .login-img{
 51  51     width: 50px;
 52  52     height: 45px;
 53  53     float: left;
 54  54     margin-left: 8px;
 55  55 }
 56  56 
 57  57 .input-in{
 58  58     width: 290px;
 59  59     height: 45px;
 60  60     line-height: 45px;
 61  61     float: left;
 62  62     border: 0px;
 63  63     letter-spacing: 1px;
 64  64     font-size: 18px;
 65  65     color:gray;
 66  66 }
 67  67 
 68  68 .bt-login-div{
 69  69     width: 100%;
 70  70     height: 50px;
 71  71     margin-top: 20px; 
 72  72 }
 73  73 
 74  74 
 75  75 .submit{
 76  76     width: 100px;
 77  77     height: 40px;
 78  78     margin: 0 auto;
 79  79     text-align: center;
 80  80     line-height: 40px;
 81  81     border: 1px solid #ccc;
 82  82     border-radius: 5px;
 83  83     background: #0099FF;
 84  84     color: white;
 85  85 }
 86  86 
 87  87 .submit:hover{
 88  88     border: 1px solid #77DDC9;
 89  89     background: #0099FF;
 90  90     opacity: 0.9;
 91  91     cursor: hand;
 92  92 }
 93  93 
 94  94 
 95  95 .fogot{
 96  96     width: 100px;
 97  97     height: 40px;
 98  98     margin: 0 auto;
 99  99     text-align: center;
100 100 }
101 101 .fogot a{
102 102     color: white;
103 103     text-decoration-style: none;
104 104     text-decoration: #ccc;
105 105 }

1、选择试题

图片 30

View Code

2. 点击确定后再次确认开始考试

图片 31

 

3.进入考试界面开始考试

图片 32

然后,页面代码

4.完成后点击交卷,显示分数

图片 33

 

图片 34图片 35

代码部分:

 1 <html>
 2 <meta charset="utf-8" />
 3 <title>登陆</title>
 4 
 5 <head>
 6     <link href="css/login.css" rel="stylesheet" type="text/css" />
 7 </head>
 8 
 9 <body>
10     <div class="headers">
11         <div class="siv-ng">
12 
13         </div>
14     </div>
15     <div class="contents">
16         <div class="login">
17             <div class="login-img-top">
18 
19             </div>
20             <h1>
21                 XXXX后台管理系统V1.0
22             </h1>
23             <div>
24                 <form method="post">
25                     <div class="form-text">
26                         <div class="login-img">
27                             <img src="images/user-icon.png" width="40" height="40" style="margin-top:2px;">
28                         </div>
29                         <input class="input-in" value="" type="text" class="username">
30                     </div>
31                     <div class="form-text">
32                         <div class="login-img">
33                             <img src="images/lock-icon.png" width="40" height="40"  style="margin-top:2px;">
34                         </div>
35                         <input class="input-in" value="" type="password" class="password">
36                     </div>
37                     <div class="bt-login-div">
38                         <div class="submit">
39                             登陆
40                         </div>
41                     </div>
42                     <div class="bt-login-div">
43                             <div class="fogot">
44                                 <a href="#">忘记密码?</a>
45                             </div>
46                         </div>
47                 </form>
48             </div>
49         </div>
50     </div>
51     <div class="footer">
52 
53     </div>
54 </body>
55 
56 </html>

1.  选择考试

View Code

  1.1 选择考试名称后台:xuanzekaoshi.php

图片 36图片 37

 1 <?php
 2 session_start();
 3 include("../init.inc.php");
 4 include("../../DBDA.class.php");
 5 $db=new DBDA();
 6 
 7 //自定义一个用户,保存在session里
 8 $_SESSION["uid"]="lisi";
 9 
10 
11 $sql="select * from shiti";
12 $attr=$db->Query($sql);
13 
14 
15 $smarty->assign("ks",$attr);
16 $smarty->display("xuanzekaoshi.html");

View Code

只是做个记录而已. 这个页面,断断续续的,大概做了1个小时这样吧. 

     1.2 选择考试名称前端显示:xuanzekaoshi.html

图片 38图片 39

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>选择考试</title>
 6 <script src="../../jquery-1.11.2.min.js"></script>
 7 </head>
 8 
 9 <body>
10 <h1>选择考试名称</h1>
11 <div>请选择要考试的试题:</div>
12 <br />
13 <form action="kaoshichuli.php" method="post">
14 <select name="xzks" id="xzks">
15 <{foreach $ks as $v}>
16 <option value="<{$v[0]}>"><{$v[3]}></option>
17 <{/foreach}>
18 </select>
19 <br />
20 <br />
21 
22 <!--选择好要考的试题后显示出试题的详情 -->
23 <div id="xx"></div>
24 <br />
25 
26 <!--点击确定开始时再确认一下,若确定则开始考试 -->
27 <input type="submit" value="确定开始" id="qdks"  onclick="return confirm('确定开始考试吗?考试开始后,到时间自动交卷,请注意好时间!')"/>
28 </form>
29 </body>
30 
31 <script type="text/javascript">
32 
33 //选择好要考的试题后显示出试题的详情
34 $(document).ready(function(e) {
35     
36     showxq();
37     $("#xzks").change(function(){
38         
39         showxq();
40         
41         })
42     function showxq()
43     {
44         var code=$("#xzks").val();
45         $.ajax({
46             url:"xianshixq.php",
47             data:{code:code},
48             type:"POST",
49             dataType:"TEXT",
50             success: function(data){
51                 if(!data.trim()=="")
52                 {
53                     var lie=data.split("^");
54                     var mf=lie[4]*lie[5];
55                     var str="本次考试为"+lie[3]+"考试,考试时间为"+lie[1]+"分钟,共计"+lie[4]+"道题,每题"+lie[5]+"分,满分为"+mf+"分。";
56                     $("#xx").html(str);
57                 }
58             }
59             
60         });
61         
62     }    
63 });
64 
65 
66 </script>
67 </html>

View Code

 

  1.3 显示试题详情:xianshixq.php

图片 40图片 41

 1 <?php
 2 //显示试题详情
 3 include("../../DBDA.class.php");
 4 $db=new DBDA();
 5 
 6 $code=$_POST["code"];
 7 
 8 $sql="select * from shiti where code='{$code}'";
 9 $str=$db->StrQuery($sql);
10 
11 echo $str;

View Code

  图片 42

 

2.  考试页面

  2.1 考试页面后台:kaoshi.php

图片 43图片 44

 1 <?php
 2 //考试界面
 3 session_start();
 4 include("../init.inc.php");
 5 include("../../DBDA.class.php");
 6 $db=new DBDA();
 7 
 8 $xzks=$_SESSION["xzks"];//试题代号
 9 
10 $uid=$_SESSION["uid"];//用户名
11 
12 $adjs=$_SESSION["djs"];//倒计时
13 $smarty->assign("djs",$adjs);
14 
15 //从users表查用户信息
16 $suid="select * from users where username='{$uid}'";
17 $auid=$db->Query($suid);
18 $smarty->assign("uid",$auid);
19 
20 //从shiti表查考试的详情
21 $sql="select * from shiti where code='{$xzks}'";
22 $asql=$db->Query($sql);
23 $smarty->assign("xzks",$asql);
24 
25 //具体的题目,显示第一道题
26 $stm="select * from shititimu where shunxu=1";
27 $atm=$db->Query($stm);
28 $smarty->assign("dyt",$atm);
29 
30 //查题目名称
31 $stmmc="select name from timu where code='{$atm[0][2]}'";
32 $aname=$db->StrQuery($stmmc);
33 $smarty->assign("tmmc",$aname);
34 
35 //查选项信息
36 $soption="select * from xuanxiang where timu='{$atm[0][2]}'";
37 $aoption=$db->Query($soption);
38 $smarty->assign("option",$aoption);
39 
40 //做试题列表,从shititimu查找题目的相关信息,其中shiti=xzks
41 $sall="select * from shititimu where shiti='{$xzks}'";
42 $aall=$db->Query($sall);
43 $smarty->assign("list",$aall);
44 
45 $smarty->display("kaoshi.html");

View Code

  2.2 考试页面前端显示:kaoshi.html

图片 45图片 46

  1 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  2 <title>考试页面</title>
  3 <script src="../../jquery-1.11.2.min.js"></script>
  4 <style>
  5 *{margin:0px auto; padding:0px}
  6 #xinxi{
  7     width:70%;
  8     height:100px;
  9     background-color:#0080C0;}
 10 #shijuan{
 11     width:1000px;
 12     height:300px;
 13     font-size:30px;
 14     margin-left:200px;
 15     }
 16 #list{
 17     width:75%;
 18     height:100px;
 19     background-color:#0080C0;}
 20 #left{
 21     width:70%;
 22     height:100px;    
 23     float:left;
 24     }
 25 #right{    
 26     width:25%;
 27     height:100px;
 28     color:#FFF;    
 29     font-size:24px;
 30     float:left;
 31     margin-top:10px;
 32     margin-left:30px;
 33     }
 34 .xq{
 35     font-size:20px;
 36     color:#FFF;
 37     margin:10px 0px 5px 10px;}
 38 .tmlist{
 39     width:40px;
 40     height:40px;
 41     background-color:#CF6;
 42     margin:10px 0px 0px 10px;
 43     float:left;
 44     font-size:20px;
 45     font-weight:bold;
 46     color:#0080FF;
 47     text-align:center;
 48     line-height:40px;
 49     vertical-align:middle;}
 50 .jiaojuan{
 51     width:70px;
 52     height:70px;
 53     font-size:24px;
 54     font-weight:bolder;
 55     color:#00F;
 56     text-align:center;
 57     line-height:70px;
 58     vertical-align:middle;
 59     float:right;
 60     margin-right:50px;
 61     margin-top:20px;
 62     }
 63     
 64 </style>
 65 </head>
 66 
 67 <body><br />
 68 <center><h1>考试页面</h1></center><br />
 69 <!--part1 考试信息介绍 -->
 70 <div id="xinxi">
 71     <!--详细信息 -->
 72     <div id="left">
 73         <div class="xq">姓名:<{$uid[0][2]}></div>
 74         <div  class="xq">
 75         考试名称为:<{$xzks[0][3]}>&nbsp;&nbsp;所属科目为:<{$xzks[0][2]}>
 76         考试时间为:<{$xzks[0][1]}>分钟&nbsp;&nbsp;共计为:<{$xzks[0][4]}>道题&nbsp;&nbsp;每题为:<{$xzks[0][5]}>分
 77         </div>
 78     
 79     </div>
 80     <!--倒计时 -->
 81     <div id="right">
 82         <div >距离考试结束还有:</div>
 83 
 84         <div style="font-size:35px; margin-left:20px; margin-top:10px;" >
 85         <{$djs[0]}>&nbsp;:
 86         <{$djs[1]}>
 87         </div>
 88     </div>
 89 
 90 </div><br />
 91 
 92 <!--part2 试题界面 -->
 93 <div id="shijuan">
 94     <div id="bt">
 95        <div> <{$dyt[0][3]}>、<{$tmmc}></div>
 96     </div>
 97     
 98     <div id="option">
 99     <{foreach $option as $v}>
100     <div>&nbsp;&nbsp;&nbsp;<input type="checkbox" class="xx" value="<{$v[2]}>" />&nbsp;<{$v[2]}>:<{$v[1]}></div>   
101     <{/foreach}>
102     </div>
103     
104      <!-- 点击确定跳向下一题 -->
105    <div id="btn">
106    <input type="button" id="sure" bs="<{$dyt[0][2]}>" shunxu="<{$dyt[0][3]}>" value="确定" style="margin-left:50px; width:50px; height:30px; font-size:15px; margin-top:10px;">
107    </div>
108 
109 </div>
110 <!--part3 试题列表 -->
111 <div id="list">
112     <div>
113         <{foreach $list as $v}>
114         <div class="tmlist" tmdh="<{$v[2]}>"><{$v[3]}></div>  
115         <{/foreach}>
116     </div>
117 
118     <div>
119         <input type="button" value="交卷" class="jiaojuan" />
120     </div>
121 </div>
122 </body>
123 <script type="text/javascript">
124 
125 //1.倒计时处理
126 window.setInterval("dao()",1000);
127 function dao()
128 {
129         $.ajax({
130             url:"daojishi.php",
131             dataType:"TEXT",
132             success: function(data){
133                 var sj=data.trim().split("|");
134                 $("#fen").html(sj[0]);
135                 $("#miao").html(sj[1]);
136             }
137         });
138 }
139         
140 //2.点击确定跳向下一题
141 $("#sure").click(function(){
142         
143     tianjia();
144 })    
145     
146         
147 function tianjia()
148 {
149         //向数据库yhkstm表添加一条信息
150         //code,kaoshi(ksid),timu(题目代号tmdh),zqda(不添加),yhda,shunxu
151         var tmdh=$("#sure").attr("bs");
152         //查yhda(用户答案)
153         var xx=$(".xx");
154         var str="";
155         for(var i=0;i<xx.length;i++)
156         {
157             //判断哪项选中
158             if(xx.eq(i).prop("checked"))
159             {
160                 //取出所有的选中的复选框的value
161                 str=str+xx.eq(i).val()+",";
162             }
163         }
164         //去掉最后多余的 ","
165         str=str.substr(0,str.length-1);//用户答案
166         var shunxu=$("#sure").attr("shunxu");
167         
168         $.ajax({
169             async:false,
170             url:"dati.php",
171             data:{tmdh:tmdh,daan:str,shunxu:shunxu},
172             type:"POST",
173             dataType:"JSON",
174             success: function(data){
175                 
176                 //标题
177                 var bt=data.shunxu+"、"+data.tmmc;
178                 $("#bt").html(bt);
179                 
180                 //选项
181                 var str="";
182                 for(var i=0;i<data.xuanxiang.length;i++)
183                 {
184                     str=str+"<div>&nbsp;&nbsp;&nbsp;<input type='checkbox' class='xx' value='"+data.xuanxiang[i][2]+"'>&nbsp;"+data.xuanxiang[i][2]+":"+data.xuanxiang[i][1]+"</div>";                    
185                 }                
186                 $("#option").html(str);
187                 
188                 //确定按钮                
189                 var btn="<input type='button' id='sure' bs='"+data.tmdh+"' shunxu='"+data.shunxu+"' value='确定' style='margin-left:50px; width:50px; height:30px; font-size:15px; margin-top:10px;'>";
190                 
191                 $("#btn").html(btn);
192                 }
193             
194             });    
195         $("#sure").click(function(){
196     
197                 tianjia();
198             })    
199             
200 }
201 
202 
203 //3. 题目列表
204             
205     //给选项加点击事件
206     $(".tmlist").click(function(){
207         
208         var tmdh=$(this).attr("tmdh");
209         var shunxu=$(this).text();
210         $.ajax({
211             async:false,
212             url:"tmlist.php",
213             data:{tmdh:tmdh,shunxu:shunxu},
214             type:"POST",
215             dataType:"JSON",
216             success: function(data){
217                 
218                 //标题
219                 var bt=data.shunxu+"、"+data.tmmc;
220                 $("#bt").html(bt);
221                 
222                 //选项
223                 var str="";
224                 for(var i=0;i<data.xuanxiang.length;i++)
225                 {
226                     str=str+"<div>&nbsp;&nbsp;&nbsp;<input type='checkbox' class='xx' value='"+data.xuanxiang[i][2]+"'>&nbsp;"+data.xuanxiang[i][2]+":"+data.xuanxiang[i][1]+"</div>";                    
227                 }                
228                 $("#option").html(str);
229                 
230                 //确定按钮                
231                 var btn="<input type='button' id='sure' bs='"+data.tmdh+"' shunxu='"+data.shunxu+"' value='确定' style='margin-left:50px; width:50px; height:30px; font-size:15px; margin-top:10px;'>";
232                 
233                 $("#btn").html(btn);
234                 }
235             
236             });    
237         
238         $("#sure").click(function(){
239     
240                 tianjia();
241             })    
242     
243         })
244         
245 //4.点击交卷        
246 $(".jiaojuan").click(function(){
247     $.ajax({
248         url:"jiaojuan.php",
249         dataType:"TEXT",
250         success: function(data){
251             
252             var str="考试结束!您的总分为:"+data;
253             alert(str);
254             }
255         });
256     
257     })
258         
259         
260         
261         
262 </script>
263 </html>

View Code

  2.3 考试页面处理:kaoshivhuli.php

  作用:1.将选好的试题先存到session中  
2.计算倒计时时,从数据库中查找考试时间
 3.选完答案点击确定,往yhks表添加信息

图片 47图片 48

 1 <?php
 2 //考试页面:
 3 session_start();
 4 //将选好的试题先存到session中
 5 $xzks=$_POST["xzks"];
 6 $_SESSION["xzks"]=$xzks;
 7 
 8 include("../../DBDA.class.php");
 9 $db = new DBDA();
10 //倒计时,从数据库中查找考试时间
11 $sql="select shijian from shiti where code='{$xzks}'";
12 
13 $sj=$db->StrQuery($sql);
14 
15 if(empty($_SESSION["djs"]))
16 {
17     $_SESSION["djs"]=array($sj,00);
18     }
19     
20 //点击确定,往yhks表添加信息    :code,shiti,user,fenshu,shijian
21 $user=$_SESSION["uid"];
22 $time=date("Y-m-d H:i:s");
23 $sks="insert into yhks values('','{$xzks}','{$user}',0,'{$time}')";    
24 $db->Query($sks,1);
25 //取这条数据的主键值备用
26 $id=$db->conn->insert_id;
27 $_SESSION["ksid"]=$id;
28 
29 
30 header("location:kaoshi.php");

View Code

  2.4 倒计时处理页面:daojishi.php

图片 49图片 50

 1 <?php
 2 session_start();
 3 
 4 $attr = $_SESSION["djs"];
 5 
 6 $fen = $attr[0];
 7 $miao = $attr[1];
 8 
 9 if($miao>0)
10 {
11     $miao--;
12 }
13 else if($miao==0)
14 {
15     $miao = 59;
16     $fen--;
17 }
18 
19 $attr[0] = $fen;
20 $attr[1] = $miao;
21 
22 $_SESSION["djs"] = $attr;
23 
24 echo "{$fen}|{$miao}";
25 
26 if($fen==0 && $miao==0)
27 {
28     echo "交卷";
29 }

View Code

  2.5 答题后,点击确定跳向下一题的ajax处理页面:dati.php

图片 51图片 52

 1 <?php
 2 //向数据库yhkstm表添加一条数据
 3 //code,kaoshi(ksid),timu(题目代号tmdh),zqda(不添加),yhda,shunxu
 4 session_start();
 5 
 6 include("../../DBDA.class.php");
 7 $db=new DBDA();
 8 
 9 $ksid=$_SESSION["ksid"];
10 $tmdh=$_POST["tmdh"];
11 $yhda=$_POST["daan"];
12 $shunxu=$_POST["shunxu"];
13 
14 //判断用户是否是第一次点击确定
15 //是第一次就添加数据,不是第一次就修改答案
16 $spd="select count(*) from yhkstm where kaoshi='{$ksid}' and shunxu='{shunxu}'";
17 if($db->StrQuery($spd)==1)//说明数据已经存在
18 {
19     $sxg="update yhkstm set yhda='{$yhda}' wnere kaoshi='{$ksid}' and shunxu='{shunxu}'";
20     $db->Query($sxg,1);
21 }
22 else
23 {
24     //向数据库yhkstm表添加数据
25     $stj="insert into yhkstm values('','{$ksid}','{$tmdh}','','{$yhda}','{$shunxu}')";
26     $db->Query($stj,1);
27 }
28 
29 //点击确定跳向下一题
30 
31 //根据yhkatm表中的ksid 在yhks表中找到试题shiti一栏
32 $sstid = "select shiti from yhks where code = '{$ksid}'";
33 $stid = $db->StrQuery($sstid);
34 //根据shiti,和顺序找下一个题目xyt(下一题)
35 $shunxu++;
36 
37 $sxyt = "select * from shititimu where shiti = '{$stid}' and shunxu='{$shunxu}'";
38 $axyt = $db->Query($sxyt);
39 
40 //查题目名称
41 $stmmc = "select name from timu where code = '{$axyt[0][2]}'";
42 $tmmc = $db->StrQuery($stmmc); 
43 
44 //查选项
45 $sxx = "select * from xuanxiang where timu='{$axyt[0][2]}'";
46 $axx = $db->Query($sxx);
47 
48 $attr = array("shunxu"=>$axyt[0][3],"tmdh"=>$axyt[0][2],"tmmc"=>$tmmc,"xuanxiang"=>$axx);
49 
50 echo json_encode($attr);

View Code

  2.6 题目列表中,点击题目按钮出现相应题目的ajax处理页面:tmlist.php

图片 53图片 54

 1 <?php
 2 //题目列表,给选项加点击事件处理页面
 3 session_start();
 4 
 5 include("../../DBDA.class.php");
 6 $db = new DBDA();
 7 
 8 $tmdh = $_POST["tmdh"];
 9 $shunxu = $_POST["shunxu"];
10 $ksid = $_SESSION["ksid"];
11 
12 
13 //点击确定跳向下一题
14 
15 //根据yhkatm表中的ksid 在yhks表中找到试题shiti一栏
16 $sstid = "select shiti from yhks where code = '{$ksid}'";
17 $stid = $db->StrQuery($sstid);
18 //根据shiti,和顺序找下一个题目xyt(下一题)
19 $shunxu++;
20 
21 $sxyt = "select * from shititimu where shiti = '{$stid}' and shunxu='{$shunxu}'";
22 $axyt = $db->Query($sxyt);
23 
24 //查题目名称
25 $stmmc = "select name from timu where code = '{$axyt[0][2]}'";
26 $tmmc = $db->StrQuery($stmmc); 
27 
28 //查选项
29 $sxx = "select * from xuanxiang where timu='{$axyt[0][2]}'";
30 $axx = $db->Query($sxx);
31 
32 $attr = array("shunxu"=>$axyt[0][3],"tmdh"=>$axyt[0][2],"tmmc"=>$tmmc,"xuanxiang"=>$axx);
33 
34 echo json_encode($attr);

View Code

  2.7 点击交卷并显示总分处理页面:jiaojuan.php

图片 55图片 56

 1 <?php
 2 //交卷处理页面
 3 session_start();
 4 
 5 include("../../DBDA.class.php");
 6 $db=new DBDA();
 7 
 8 $ksid=$_SESSION["ksid"];
 9 $uid=$_SESSION["uid"];
10 
11 $sks="select * from yhks where code='{$ksid}'";
12 $aks=$db->Query($sks);
13 
14 $sfz="select fenzhi from shiti where code='{$aks[0][1]}'";
15 $fz=$db->StrQuery($sfz);//每道题的分值
16 
17 $zf=0; //总分
18 
19 $sda="select * from yhkstm where kaoshi='{$ksid}'";
20 $ada=$db->Query($sda);
21 foreach($ada as $v)
22 {
23     $v[2];//题目代号
24     $v[4];//用户题目答案
25     $szq="select daan from timu where code='{$v[2]}'";
26     $zqda=$db->StrQuery($szq);
27     
28     if($zqda==$v[4])
29     {
30         $zf=$zf+$fz;
31         }
32     
33     }
34     
35 $sxg="update yhks set fenshu='{$zf}' where code='{$ksid}'";
36 $db->Query($sxg,1);
37 
38 echo $zf;

View Code

 

相关文章

Leave a Reply

电子邮件地址不会被公开。 必填项已用*标注