用JSP+Javabean+Servlet实现一个投票系统

来源:互联网 发布:怎么打理好淘宝店铺 编辑:程序博客网 时间:2024/05/12 08:17
 

//index   用于登陆等功能的实现

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<head>
<!-- Copyright 2005 Macromedia, Inc. All rights reserved. -->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>欢迎</title>
<link rel="stylesheet" href="3col_leftNav.css" type="text/css" />
<style type="text/css">
<!--
.STYLE1 {font-size: 18%}
.STYLE3 {
 font-size: large;
 font-weight: bold;
 color: #996600;
}
.STYLE4 {
 font-size: medium;
 font-weight: bold;
}
.STYLE5 {color: #00CC66}
-->
</style>
</head>
<body>
<form name="form1" method="post" action="login.jsp">
<hr>
 
  <div id="globalNav"> <a href="index.jsp">首页</a> |  | <a href="registration.jsp">注册</a> | |<a href="./http://www.jmu.edu.cn"> 集美大学</a> ||</div>
  <h2 id="pageName">集美大学</h2>

  <div class="STYLE1" id="breadCrumb" >
    <p>欢迎登陆到集美大学投票系统进行新校名的投票!新用户请注册再登陆,谢谢!</p>
    <hr>
  </div>
<div id="navBar">
  <div id="search">
   
      <label>用户名</label>
    <input name="userId" type="text" size="20" />
   
 
  </div>
  <div class="relatedLinks">
    <h3>密码 <br />
 <input name="password" type="password" size="20"/ >
 <input name="submit" type="submit" value="go" size="50" />
    </h3>
  </div>
 
  <div class="relatedLinks">
  
    <p>&nbsp;</p>
    <p class="STYLE4"><a href="registration.jsp" class="STYLE5">如果你是新用户请点击这里注册!</a></p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
  </div>
 
</div>
<!--end navBar div -->
<div id="headlines">
  <h3><%@ include file="CounterApp.jsp"%></h3>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p><a href="#">.</a> </p>
  <p>&nbsp;</p>
  <div id="advert"></div>
</div>
<!--end headlines -->
<div id="content">
  <div class="feature"> <img src="04.jpg" alt="" width="225" height="228" />
    <h3 class="STYLE4">集美大学简介</h3>
    <p>Jimei University, approved by the Ministry of Education, is a key   provincial multi-disciplined university which was combined into one from five   individual institutes and colleges in Jimei Schools Village, namely, Jimei   Navigation Institute, Xiamen Fisheries College, Fujian Physical Education   College, Jimei Finance and Economics Institute, and Jimei Teachers College in   October 1994. Secretary of CPC of JMU: Prof. Xiangzhong Zhang<br />
      President of JMU: Prof.   Jiande Gu<br />
      Add: Jimei Schools Village, Xiamen, 361021, Fujian Province, P. R.   China<br />
      Tel: 0086-592-6181097 Fax: 0086-592-6180120<br />
      
  </div>
  <div class="story">
    <h3>
      <!--end content -->
</h3>
  </div>
</div>
<div id="siteInfo"> <img src="20055291316679.jpg" width="65" height="21" /><span class="STYLE3">welcome</span> <span class="STYLE3">welcome</span> <span class="STYLE3">welcome</span> <span class="STYLE3">welcome</span> <span class="STYLE3">welcome</span> <span class="STYLE3">welcome</span> <span class="STYLE3">welcome</span> <span class="STYLE3">welcome</span> <span class="STYLE3">welcome</span></div>
<br />
</form>
</body>
</html>

//验证登陆界面

<%@ include file="include.inc"%>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<%
//获得请求的参数。
String id=request.getParameter("userId");
String psw=request.getParameter("password");
//连接数据库
Class.forName(CLASSFORNAME);
Connection con = DriverManager.getConnection(SERVANDDB,USER,PWD);
Statement statement=con.createStatement();
String isCorrect="select * from user_info where userId='" + id + "' and password='" + psw + "'";
ResultSet result=statement.executeQuery(isCorrect);
 session.setAttribute("isLog",new String("0"));

if(!result.next())
{
 
response.sendRedirect("index.jsp");//账号或密码错误,转入错误页面
result.close();
statement.close();
con.close();
}
 //如果查询后有记录,说明登录验证成功。
else
{
      //保存登录信息到session对象中。
   session.setAttribute("name",result.getString("name"));
   session.setAttribute("id",result.getString("userId")); 
   session.setAttribute("email",result.getString("email")); 
   session.setAttribute("fav",result.getString("fanvcategory")); 
   session.setAttribute("userType",new Integer(result.getInt("userType")));
   session.setAttribute("re","0");  
   System.out.println(session.getAttribute("userType"));
   session.setAttribute("isLog",new String("1"));
   int count=result.getInt("userLogCount");
   session.setAttribute("userLogCount",new Integer(count)); 
   count++;
   session.setAttribute("userLastLogTime",result.getString("userLastLogTime")); 
   java.util.Date time1=new java.util.Date();//获得系统当前时间
      String sqltime=new Timestamp(time1.getTime()).toString();//将当前时间转换成sql server可以识别的对象     
  //更新登录信息。
   statement.execute("update user_info set userLogCount="+count+",userLastLogTime='"+sqltime+"' where userId='" + id +"'");
   //关闭数据库连接相关的资源。
  statement.close();
  con.close();  
  //把页面派发到目的
  response.sendRedirect("tpiao.jsp"); 
}
%>

//投票界面

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<base href="<%=basePath%>">
<meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
   
<!-- Copyright 2005 Macromedia, Inc. All rights reserved. -->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>欢迎</title>
<link rel="stylesheet" href="3col_leftNav.css" type="text/css" />
<style type="text/css">
<!--
.STYLE1 {font-size: 18%}
.STYLE2 {color: #006699}
.STYLE5 {font-size: small}
.STYLE20 {font-size: 10px}
-->
</style>
</head>
<body>
 
<hr>
 
<div id="globalNav"> <a href="index.jsp">首页</a> |  | <a href="logout.jsp">注销</a> | |<a href="./http://www.jmu.edu.cn"> 集美大学</a> ||    </div>
  <h2 id="pageName">集美大学</h2>

<div class="STYLE1" id="breadCrumb" >
    <p><p align="center">HI!<%=session.getAttribute("name")%>,您是第<%=session.getAttribute("userLogCount")%>次登录,您上次登录的时间是:<%=session.getAttribute("userLastLogTime")%> !请选择可以振兴我校的一个新校名字!</p>
    <hr>
</div>
  <div id="navBar">
  <div id="search"></div>
  <div class="relatedLinks">
  <FORM name="addInfo" action="AddInfo" method=GET>
    <table width="121" height="343" border="0">
      <tr>
        <td width="37"><label>
          <input type="radio" name="Nname" value="a" />
        </label></td>
        <td width="68"><span class="STYLE5">中华儿女大学</span></td>
      </tr>
      <tr>
        <td><label>
          <input type="radio" name="Nname" value="b" />
        </label></td>
        <td><span class="STYLE5">厦门科技大学</span></td>
      </tr>
      <tr>
        <td><input type="radio" name="Nname" value="c" /></td>
        <td><span class="STYLE5">假日帝国大学</span></td>
      </tr>
      <tr>
        <td><input type="radio" name="Nname" value="d" /></td>
        <td><span class="STYLE5">中国嘉庚大学</span></td>
      </tr>
      <tr>
        <td height="23" colspan="2"><label>
          <INPUT type="Submit" name="button2" value="提交 method=get">
        </label></td>
      </tr>
    </table>
 </form>
  </div>
 
</div>
<!--end navBar div -->
<div id="headlines"><div class="relatedLinks">
  <FORM name="addInfo" action="AddInfo" method=post>
    <table width="121" height="343" border="0">
      <tr>
        <td width="37"><label>
          <input type="radio" name="Nname" value="a" />
        </label></td>
        <td width="68"><span class="STYLE5">中华儿女大学</span></td>
      </tr>
      <tr>
        <td><label>
          <input type="radio" name="Nname" value="b" />
        </label></td>
        <td><span class="STYLE5">厦门科技大学</span></td>
      </tr>
      <tr>
        <td><input type="radio" name="Nname" value="c" /></td>
        <td><span class="STYLE5">假日帝国大学</span></td>
      </tr>
      <tr>
        <td><input type="radio" name="Nname" value="d" /></td>
        <td><span class="STYLE5">中国嘉庚大学</span></td>
      </tr>
      <tr>
        <td height="23" colspan="2">          <label>
           <INPUT type="Submit" name="button2" value="提交method=post">
        </label>        </td>
      </tr>
    </table>
 </form>
  </div></div>
<!--end headlines -->
<div id="content">
  <div class="feature"> <img src="04.jpg" alt="" width="225" height="228" />
    <h3>集美大学简介</h3>
    <p>Jimei University, approved by the Ministry of Education, is a key   provincial multi-disciplined university which was combined into one from five   individual institutes and colleges in Jimei Schools Village, namely, Jimei   Navigation Institute, Xiamen Fisheries College, Fujian Physical Education   College, Jimei Finance and Economics Institute, and Jimei Teachers College in   October 1994. Secretary of CPC of JMU: Prof. Xiangzhong Zhang<br />
President of JMU: Prof.   Jiande Gu<br />
Add: Jimei Schools Village, Xiamen, 361021, Fujian Province, P. R.   China<br />
Tel: 0086-592-6181097 Fax: 0086-592-6180120<br />
Website:   www.jmu.edu.cn</p>
  </div>
  <div class="story">
    <h3>
      <!--end content -->
</h3>
  </div>
</div>
<div id="siteInfo"> <img src="20055291316679.jpg" width="65" height="21" /> <span class="STYLE2">  Copyright @ 2006 wen31.文. All rights reserved</span></div>
<br />

</body>
</html>
//注销界面

<%@ page language="java" contentType="text/html; charset=gb2312"%>
<HTML><HEAD><TITLE>CyberCreations</TITLE>
<META http-equiv=Content-Type content="text/html; charset=gb2312">
<META content="MSHTML 6.00.2600.0" name=GENERATOR>
<META content=FrontPage.Editor.Document name=ProgId>
<META content=b name="Microsoft Border">
<link href="Forum_admin.css" rel="stylesheet" type="text/css">
</HEAD>
<BODY bgcolor="#FFFFFF">
<center>
<%
session.invalidate();
response.sendRedirect("index.jsp");
%>
<br>
<br>
正在注销.......
</center>
</body>
</html>
//为了防止一个用户的多次投票 后出现的强行退出界面。具体实现方法在后面


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>error.html</title>
    <META HTTP-EQUIV="REFRESH" CONTENT="1; URL=index.jsp">  
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
   
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
   
  </head>
 
  <body>
     <script language="LiveScript">
    alert("你以提交过");
  </script>
 
  </body>
</html>
//Addinfo.java

package org.mylisky.servelet;

import java.beans.Statement;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class AddInfo extends HttpServlet {

    /**
     * Constructor of the object.
     */
    private Connection con;
    public void init() throws ServletException {
        String url = getInitParameter("url");
        String DBServer = getInitParameter("DBServer");
        String UserName = getInitParameter("UserName");
        String PassWord = getInitParameter("PassWord");
        System.out.println("url=" + url);

        try {
            Class.forName(url);
            con = DriverManager.getConnection(DBServer, UserName, PassWord);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }
    private String trans(String chi){
        String result = null;
        byte temp[];
        try{
            temp=chi.getBytes("iso-8859-1");
            result=new String(temp,"GB2312");
        }
        catch(UnsupportedEncodingException e){e.printStackTrace();}
        return result;
    }

  
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            request.setCharacterEncoding("GB2312");
       
       
        String Nname = (String)request.getParameter("Nname");
        String r = (String)request.getSession().getAttribute("re");
        if(r.equals("1")){response.sendRedirect("reError.html");}
       
        else{try{
            java.sql.Statement t = con.createStatement();
            ResultSet nt = t.executeQuery("select * from advice ");
            nt.next();
            int i = nt.getInt(Nname);
            int ni = i+1;
            java.sql.Statement s = con.createStatement();
            s.executeUpdate("update advice set "+Nname+"='"+ni+"'");
           
          }catch(SQLException e){e.printStackTrace();}
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/viewInfo");
        requestDispatcher.forward(request,response);}
      
       
        }
       
   

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
           doGet(request,response);
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occure
     */
   

}
//viewInfo.java

package org.mylisky.servelet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class viewInfo extends HttpServlet {

    Connection con;

    public void init() throws ServletException {
        String url = getInitParameter("url");
        String DBServer = getInitParameter("DBServer");
        String UserName = getInitParameter("UserName");
        String PassWord = getInitParameter("PassWord");
        System.out.println("url=" + url);

        try {
            Class.forName(url);
            con = DriverManager.getConnection(DBServer, UserName, PassWord);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("image/jpeg");
        String r = (String) request.getSession().getAttribute("re");
        System.out.print(r);
        if (r.equals("1")) {
            response.sendRedirect("reError.html");
        }
        request.getSession().setAttribute("re", "1");
        ServletOutputStream out = response.getOutputStream();
        BufferedImage image = new BufferedImage(800, 600,
                BufferedImage.TYPE_INT_RGB);
        int a = 0, b = 0, c = 0, d = 0, total = 0;
        final int size = 500;
        final int high = 50;
        try {
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("select * from advice");
            if (rs.next()) {
                a = rs.getInt("a");
                b = rs.getInt("b");
                c = rs.getInt("c");
                d = rs.getInt("d");
                total = a + b + c + d;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, 800, 600);
        graphics.setColor(Color.BLACK);
        graphics.setFont(new Font("华文彩云", Font.BOLD, 50));
        graphics.drawString("投票结果", 300, 40);

        graphics.setFont(new Font("隶书", Font.PLAIN, 20));
        graphics.drawLine(120, 100, 120, 470);
        graphics.drawLine(120, 470, 720, 470);
        graphics.drawString("投票人数", 0, 140);
        graphics.drawString("福建第一大学", 0, 210);
        graphics.drawString("厦门科技大学", 0, 280);
        graphics.drawString("厦门交通大学", 0, 350);
        graphics.drawString("集美嘉庚大学", 0, 420);

        graphics.fillRect(120, 120, size, high);
        graphics.drawString(String.valueOf(total), 630, 140);

        graphics.fillRect(120, 190, size * a / total, high);
        graphics.drawString(String.valueOf(a), (size * a / total) + 140, 210);

        graphics.fillRect(120, 260, size * b / total, high);
        graphics.drawString(String.valueOf(b), (size * b / total) + 140, 280);

        graphics.fillRect(120, 330, size * c / total, high);
        graphics.drawString(String.valueOf(c), (size * c / total) + 140, 350);

        graphics.fillRect(120, 400, size * d / total, high);
        graphics.drawString(String.valueOf(d), (size * d / total) + 140, 420);

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(image);
        out.close();

    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to
     * post.
     *
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request, response);
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException
     *             if an error occure
     */

}
//xml 的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 <servlet>
  <description>This is the description of my J2EE component</description>
  <display-name>This is the display name of my J2EE component</display-name>
  <servlet-name>AddInfo</servlet-name>
  <servlet-class>org.mylisky.servelet.AddInfo</servlet-class>
  <init-param>
   <param-name>url</param-name>
   <param-value>com.microsoft.jdbc.sqlserver.SQLServerDriver</param-value>
  </init-param>
  <init-param>
   <param-name>DBServer</param-name>
   <param-value>jdbc:sqlserver://127.0.0.1:1433;DatabaseName=jspdev</param-value>
  </init-param>
  <init-param>
   <param-name>UserName</param-name>
   <param-value>sa</param-value>
  </init-param>
  <init-param>
   <param-name>PassWord</param-name>
   <param-value>123</param-value>
  </init-param>
 </servlet>
 <servlet>
  <description>This is the description of my J2EE component</description>
  <display-name>This is the display name of my J2EE component</display-name>
  <servlet-name>viewInfo</servlet-name>
  <servlet-class>org.mylisky.servelet.viewInfo</servlet-class>
  <init-param>
   <param-name>url</param-name>
   <param-value>com.microsoft.jdbc.sqlserver.SQLServerDriver</param-value>
  </init-param>
  <init-param>
   <param-name>DBServer</param-name>
   <param-value>jdbc:sqlserver://127.0.0.1:1433;DatabaseName=jspdev</param-value>
  </init-param>
  <init-param>
   <param-name>UserName</param-name>
   <param-value>sa</param-value>
  </init-param>
  <init-param>
   <param-name>PassWord</param-name>
   <param-value>123</param-value>
  </init-param>
 </servlet>


 <servlet-mapping>
  <servlet-name>AddInfo</servlet-name>
  <url-pattern>/AddInfo</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
  <servlet-name>viewInfo</servlet-name>
  <url-pattern>/viewInfo</url-pattern>
 </servlet-mapping>

</web-app>