JavaEE实验2报告_昆明理工大学

时间:2024.4.5

昆明理工大学信息工程与自动化学院学生实验报告

20## 2013   学年  学期

课程名称:JAVA EE技术    开课实验室:信自楼444       2012 年  11 月 19  日

一、实验目的

通过上机,熟练掌握servlet编程、过滤器、监听器的编程。

二、内容及要求

1、上机内容:

l  编写index.jsp,里面包含注册、显示数据清单、写入图片、显示图片的连接。

l  当用户选择注册时,首先进行客户端ip地址是否是黑名单的检测,如果不是则转到注册页面;

l  在显示所有的数据清单的页面中增加一个链接,仿照例题编写输出为EXCEL的servlet,点击时链接时执行它。

l  实现给数据表中的photo列写入图片,图片文件直接放在服务器上。

l  实现按输入的编号显示对应的图片。

l  实现登录,在登录界面中生成验证码(验证码不出现数字4)。

l  登录成功则转到main.jsp,显示网站的在线用户人数、当前用户、点击率、在线用户列表。

l  通过过滤器实现登录过滤检查,不允许用户直接请求main等其他页面;通过=过滤器给所有的页面底部加上“昆明理工大学计算机系”+班级+学号+姓名

l  用监听器实现实现网站所有网页的访问次数累计,在线用户数统计、在现用户列表更新。

三、步骤及具体实施

1、简要描述程序的开发流程、文件部署截图、及各种配置;

2、程序代码

package javaee.filter;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

public class FootFilter implements Filter{

    private String footer=null;

    public void destroy() {

       

       

    }

    public void doFilter(ServletRequest request, ServletResponse response,

            FilterChain chain) throws IOException, ServletException {

        //响应对象进行封装;

        FootResponseWrapper wrapper=new FootResponseWrapper((HttpServletResponse)response);

        //调用链中的下一个对象;

        chain.doFilter(request, wrapper);

        //响应对象处理要放在doFilter方法之后;

        CharArrayWriter outbuffer=new CharArrayWriter();

        String outstring=wrapper.toString();

        //取得</body>标记的位置,准备插入Foot文本;

        int position=outstring.indexOf("</body>")-1;

        outbuffer.write(outstring.substring(0,position));

        //插入初始参数中的foot文本;

        outbuffer.write("<hr/>"+footer+"<hr/></body></html>");

        response.setContentType("text/html");

        PrintWriter out=response.getWriter();

        out.write(outbuffer.toString());

        out.flush();

        out.close();

    }

    public void init(FilterConfig config) throws ServletException {

        footer=config.getInitParameter("footer");

       

    }

}

package javaee.filter;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

//import javax.servlet.http.Http.HttpServletResponseWrapper;

import javax.servlet.http.HttpServletResponseWrapper;

public class FootResponseWrapper extends HttpServletResponseWrapper{

        private CharArrayWriter buffer=null;

       

    public FootResponseWrapper(HttpServletResponse response) {

        super(response);

        buffer=new CharArrayWriter();

    }

    //取得字符数组输出流的字符输出流;

        public PrintWriter getWriter()

        {

            return new PrintWriter(buffer);

        }

        //重写toString方法,取得字符数组输出流;

        public String toString()

        {

            return buffer.toString();

        }

}

package javaee.filter;

import java.io.IOException;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.*;

import javax.servlet.http.*;

public class LoginCheckFilter implements Filter{

     FilterConfig config=null;

    private String webroot=null;

    public void init(FilterConfig config) throws ServletException

    {

        this.config=config;//将传入的Config赋予给这个类;

        ServletContext ctx=config.getServletContext();

        webroot=ctx.getContextPath();

    }

   

    public void destroy() {

        System.out.println("登录检查过滤器销毁");

    }

    public void doFilter(ServletRequest req, ServletResponse res,

            FilterChain chain) throws IOException, ServletException

    {

        HttpServletRequest request=(HttpServletRequest)req;

        HttpServletResponse response=(HttpServletResponse)res;

        HttpSession session=request.getSession(false);

        String uri=request.getRequestURI();//直接取得当前发出请求的地址;

        request.setCharacterEncoding("utf-8");

        //对登录页面和登录处理Servlet、错误页面直接放过;

    if(uri!=null&&(uri.equals(webroot+"/login.jsp")||uri.equals(webroot+"/loginAction.java")||uri.equals(webroot+"/errorinfo.jsp")))

        {

            chain.doFilter(req,res);

        }

        else

        {

            //检查session和session中账号是否存在,选择阻断或通过;

            if(session==null)

            {

                response.sendRedirect(webroot+"/errorinfo.jsp");

            }

            else

            {

                String userId=(String)session.getAttribute("userid");

                if(userId==null)

                {

                    response.sendRedirect(webroot+"/errorinfo.jsp");

                }

                else

                {

                    chain.doFilter(req, res);

                }

            }

        }

       

    }

   

}

package javaee.servlet;

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.ServletConfig;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

public class ChangePassword extends HttpServlet {

     Connection cn=null;

    private String driverName=null;

    private String url=null;

    private String pass=null;

    private String user=null;

    /**

     *

     */

    private static final long serialVersionUID = 1L;

    /**

     * Constructor of the object.

     */

    public ChangePassword() {

        super();

    }

    /**

     * Destruction of the servlet. <br>

     */

    public void destroy() {

        super.destroy();

        try

        {

            cn.close();

        }catch(Exception e)

        {

            System.out.println("关闭数据库连接错误:"+e.getMessage());

        }

       

    }

    /**

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

        doPost(request,response);

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

        out.println("<HTML>");

        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");

        out.println("  <BODY>");

        out.print("    This is ");

        out.print(this.getClass());

        out.println(", using the GET method");

        out.println("  </BODY>");

        out.println("</HTML>");

        out.flush();

        out.close();

    }

   

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException

    {

        String password=request.getParameter("password");

        String newpassword=request.getParameter("newpassword");

        String renewpassword=request.getParameter("renewpassword");

        int i=0;

        if(newpassword.equalsIgnoreCase(renewpassword))

        {

        if(password!=null&&password.trim().length()>0&&newpassword!=null&&newpassword.trim().length()>0&&

                renewpassword!=null&&renewpassword.trim().length()>0)

        {

            HttpSession session=request.getSession(true);

            String userid=(String)session.getAttribute("userid");

            String sql="select password from USERINFO where password=? and userid=?";

            try

            {

                PreparedStatement ps=cn.prepareStatement(sql);

                ps.setString(1, password);

                ps.setString(2, userid);

                ResultSet rs=ps.executeQuery();

                if(rs.next())

                {

                    String sql1="update USERINFO set password=? where userid=?";

                    try

                    {

                        PreparedStatement ps1=cn.prepareStatement(sql1);

                        ps1.setString(1, newpassword);

                        ps1.setString(2, userid);

                        i=ps1.executeUpdate();

                        System.out.println("i:"+i);

                        ps1.close();

                    }catch(Exception e)

                    {

                        System.out.println("修改密码错误:"+e.getMessage());

                        response.sendRedirect("ChangePassword.jsp");

                    }

                    if(i!=0) response.sendRedirect("main.jsp");

               

                }

                else  response.sendRedirect("ChangePassword.jsp");

                ps.close();

                rs.close();

            }catch(Exception e)

            {

                System.out.println("修改密码错误:"+e.getMessage());

                response.sendRedirect("ChangePassword.jsp");

            }

        }

        else

        {

            response.sendRedirect("ChangePassword.jsp");

        }

    }else

    {

        response.sendRedirect("ChangePassword.jsp");

    }

    }

    /**

     * Initialization of the servlet. <br>

     *

     * @throws ServletException if an error occurs

     */

    public void init(ServletConfig config) throws ServletException {

        super.init(config);

        //driverName=config.getInitParameter("driverName");

        //url=config.getInitParameter("url");

        ServletContext ctx=config.getServletContext();

        driverName=ctx.getInitParameter("driverName");

        url=ctx.getInitParameter("url");

        user=ctx.getInitParameter("user");

        pass=ctx.getInitParameter("pass");

        try

        {

            Class.forName(driverName);

            cn=DriverManager.getConnection(url, user, pass);

        }catch(Exception e)

        {

            System.out.println("取得数据库连接错误:"+e.getMessage());

        }

    }

}

package javaee.servlet;

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.image.BufferedImage;

import java.io.IOException;

import java.util.Random;

import javax.servlet.ServletConfig;

import javax.servlet.ServletException;

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 CheckCodeGet extends HttpServlet {

    private static final long serialVersionUID=1L;

    private final int TYPE_NUMBER=0;

    private final int TYPE_LETTER=1;

    private final int TYPE_MULTIPLE=2;

    private int width;

    private int height;

    private int count;

    private int type;

    private String validate_code;

    private Random random;

    private Font font;

    private int line;

    /**

     * Constructor of the object.

     */

    public CheckCodeGet() {

        super();

    }

    /**

     * 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.setHeader("Pragma","No_cache");

        response.setHeader("Cache_Control","no_cache");

        response.setDateHeader("Expires",0);

        response.setContentType("image/jpeg");

        String reqCount=request.getParameter("count");

        String reqWidth=request.getParameter("width");

        String reqHeight=request.getParameter("height");

        String reqType=request.getParameter("type");

        if(reqCount!=null&&reqCount!=" ")

            this.count=Integer.parseInt(reqCount);

        if(reqWidth!=null&&reqWidth!=" ")

            this.count=Integer.parseInt(reqWidth);

        if(reqHeight!=null&&reqHeight!=" ")

            this.count=Integer.parseInt(reqHeight);

        if(reqType!=null&&reqType!=" ")

            this.count=Integer.parseInt(reqType);

        font=new Font("Courier New",Font.BOLD,width/count);

           

        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        Graphics g=image.getGraphics();

        g.setColor(getRandColor(200,250));

        g.fillRect(0, 0, width, height);

        //g.setColor(getRandColor(160,200));

       

        for(int i=0;i<line;i++)

        {

            g.setColor(getRandColor(160,200));

            int x=random.nextInt(width);

            int y=random.nextInt(height);

            int x1=random.nextInt(12);

            int y1=random.nextInt(12);

            g.drawLine(x,y,x+x1,y+y1);

        }

        g.setFont(font);

        validate_code=getValidateCode(count,type);

        request.getSession().setAttribute("validate_code", validate_code);

        //验证码作为字符串写在session上;

        //HttpSession session=request.getSession()创建session;

        //public void setAtribute(String name,Objict value)将数据对象存入会话对象,以name/vlaue形式存入;

        for(int i=0;i<count;i++){

        g.setColor(getRandColor(20,130));

    int x=(int)(width/count)*i;

    int y=(int)((height+font.getSize())/2)-5;

    g.drawString(String.valueOf(validate_code.charAt(i)),x,y);

        }

        g.dispose();

        JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(response.getOutputStream());

        encoder.encode(image);

    }

    /**

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

     */

    public void init(ServletConfig config) throws ServletException {

        // Put your code here

        super.init(config);

        width=150;

        height=50;

        count=4;

        type=TYPE_NUMBER;

        random=new Random();

        line=200;

    }

   

   

    private Color getRandColor(int from,int to)

    {

        Random random=new Random();

        if(from>255)

            from=255;

        if(to>255)

            to=255;

        int rang=Math.abs(to-from);

        int r=from+random.nextInt(rang);

        int g=from+random.nextInt(rang);

        int b=from+random.nextInt(rang);

        return new Color(r,g,b);

    }

    //

    private String getValidateCode(int size,int type)

    {

        StringBuffer validate_code=new StringBuffer();

        for(int i=0;i<size;i++)

        {

            validate_code.append(getOneChar(type));

        }

        return validate_code.toString();

    }

    //

    private String getOneChar(int type)

    {

        String result=null;

        switch(type)

        {

        case TYPE_NUMBER:

            do{

        result=String.valueOf(random.nextInt(10));

        }

            while(result.equals("4"));

        break;

        case TYPE_LETTER:

            do{

            result=String.valueOf((char) (random.nextInt(26)+65));

            }

            while(result.equals("4"));

            break;

        case TYPE_MULTIPLE:

            if(random.nextBoolean())

            {

                do{

                result=String.valueOf(random.nextInt(10));

                }

                while(result.equals("4"));

            }

            else

            {

                result=String.valueOf((char) (random.nextInt(26)+65));

            }

            break;

            default:

                result=null;

                break;

        }

        if(result==null)

        {

            throw new NullPointerException("huoquyanzhengmacuowu");

        }

        return result;

    }

   

   

   

}

package javaee.servlet;

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.util.ArrayList;

import java.util.List;

import javax.servlet.ServletConfig;

import javax.servlet.ServletContext;

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 LoginAction extends HttpServlet {

    private static final long serialVersionUID = 1L;

    String driverName=null;

    String url=null;

    String user=null;

    String pass=null;

    Connection cn=null;

   

    /**

     * Constructor of the object.

     */

    public LoginAction() {

        super();

    }

    /**

     * Destruction of the servlet. <br>

     */

    public void destroy() {

        super.destroy();

        try

        {

            cn.close();

        }catch(Exception e)

        {

            System.out.println("取得数据库关闭错误:"+e.getMessage());

        }

    }

    /**

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

        doPost(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 {

        request.setCharacterEncoding("utf-8");

        response.setContentType("text/html");

        response.setCharacterEncoding("utf-8");

        String userid=request.getParameter("userid");

        String password=request.getParameter("password");

        String checkcode=request.getParameter("checkcode");

        HttpSession session1=request.getSession(true);

        //如果没有session则自动创建,有则引用,取得会话对象;

       

        if(userid!=null&&password!=null&&userid.trim().length()>0&&password.trim().length()>0)

        {

            boolean check=false;

            String checkCodeInSession=(String)session1.getAttribute("validate_code");

            if(checkcode.equalsIgnoreCase(checkCodeInSession))

            {

                try

                {

                    String sql="select * from USERINFO where  userid=? and password=?";

                   

                    PreparedStatement ps=cn.prepareStatement(sql);

                    ps.setString(1, userid);

                    ps.setString(2, password);

                    ResultSet rs=ps.executeQuery();

                    if(rs.next())

                    {

                        check=true;

                    }

                    rs.close();

                    ps.close();

                }catch(Exception e)

                {

                    System.out.println("Sql statement error: "+e.getMessage());

                    //response.sendRedirect("login.jsp");

                }//catch

            }//里if

            if(check)

            {

                HttpSession session=request.getSession(true);

                session.setAttribute("userid", userid);//将会话对象保存到会话对象;

                ServletContext application=this.getServletContext();//取得web上下文对象;

                Integer onlinenum=(Integer)application.getAttribute("onlinenum");

                if(onlinenum==null)

                {

                    application.setAttribute("onlinenum", new Integer(1));

                }else

                {

                    application.setAttribute("onlinenum", ++onlinenum);

                }

                List userList=(List)application.getAttribute("userList");

                if(userList==null)

                {

                    userList=new ArrayList();

                }//userList==null

                userList.add(userid);

                application.setAttribute("userList", userList);

                response.sendRedirect("main.jsp");

            }//3 if check

            else response.sendRedirect("login.jsp");

        }//if

        else

        {

            response.sendRedirect("login.jsp");

        }

    }

    /**

     * Initialization of the servlet. <br>

     *

     * @throws ServletException if an error occurs

     */

    public void init(ServletConfig config) throws ServletException {

        super.init(config);

        ServletContext ctx=config.getServletContext();

        driverName=ctx.getInitParameter("driverName");

        url=ctx.getInitParameter("url");

        user=ctx.getInitParameter("user");

        pass=ctx.getInitParameter("pass");

        try

        {

            Class.forName(driverName);

            cn=DriverManager.getConnection(url, user, pass);

        }catch(Exception e)

        {

            System.out.println("取得数据库连接错误:"+e.getMessage());

        }

    }

}

package javaee.servlet;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.util.ArrayList;

import java.util.List;

import javax.servlet.http.HttpSession;

public class LogoutAction extends HttpServlet {

   

    private static final long serialVersionUID = 1L;

   

    public LogoutAction() {

        super();

    }

   

    public void destroy() {

        super.destroy(); // Just puts "destroy" string in log

        // Put your code here

    }

   

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        HttpSession session=request.getSession(false);

        if(session!=null)

        {

            String userid=(String)session.getAttribute("userid");

            //取得web上下文对象;

            ServletContext application=this.getServletContext();

            //取得在线人数;

            Integer onlinenum=(Integer)application.getAttribute("onlinenum");

            if(onlinenum!=null)

            {

                //减少在线用户个数;

                application.setAttribute("onlinenum", --onlinenum);

            }

            //取得用户在线列表;

            List userList=(List)application.getAttribute("userList");

            if(userList!=null)

            {

                //从用户列表中删除注销的用户;

                userList.remove(userid);

            }

            //销毁会话对象;

            session.invalidate();

        }

        response.sendRedirect("login.jsp");

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        doGet(request,response);

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

        out.println("<HTML>");

        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");

        out.println("  <BODY>");

        out.print("    This is ");

        out.print(this.getClass());

        out.println(", using the POST method");

        out.println("  </BODY>");

        out.println("</HTML>");

        out.flush();

        out.close();

    }

   

    public void init() throws ServletException {

        // Put your code here

    }

}

package javaee.servlet;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletContext;

import javax.servlet.ServletConfig;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import com.jspsmart.upload.SmartUpload;

import java.io.File;

import java.io.FileInputStream;

public class RegisterAction extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private Connection cn=null;

    private String driverName=null;

    private String url=null;

    private String user=null;

    private String pass=null;

    ServletContext s1;

    public RegisterAction() {

        super();

    }

    /**

     * Destruction of the servlet. <br>

     */

    public void destroy() {

        super.destroy();

        try

        {

            cn.close();

        }catch(Exception e)

        {

            System.out.println("取得数据库关闭错误:"+e.getMessage());

        }

    }

    /**

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

        doPost(request,response);

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

        out.println("<HTML>");

        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");

        out.println("  <BODY>");

        out.print("    This is ");

        out.print(this.getClass());

        out.println(", using the GET method");

        out.println("  </BODY>");

        out.println("</HTML>");

        out.flush();

        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 {

        //PrintWriter out = response.getWriter();

        SmartUpload mySmartUpload=new SmartUpload();

        String photoName=null;

        //String photoDriectory=null;

        try{

           

         //上传初始化

        mySmartUpload.initialize(this.getServletConfig(), request, response);

        //设定每个上传文件的最大长度

        mySmartUpload.setMaxFileSize(1*1024*1024);

        //设定总上传数据的长度

        mySmartUpload.setTotalMaxFileSize(1*1024*1024);

        //设定允许上传的文件的类型,只允许上传java,doc,txt文件

        // mySmartUpload.setAllowedFilesList("java,doc,txt");

        //设定禁止上传的文件的类型,禁止上传带有exe,bat文件

        mySmartUpload.setDeniedFilesList("exe,bat");

        //上传文件到服务器

         mySmartUpload.upload();

        //将上传到服务器的文件全部保存到指定目录

        mySmartUpload.save("/upload");

        //取得表单上传的图片

        mySmartUpload.getRequest().getParameter("photo");

        //上传的是多个文件,这里去了第一个;

        com.jspsmart.upload.File file=mySmartUpload.getFiles().getFile(0);

       

         //判断用户是否选择了文件

         if(!file.isMissing())

         {

            photoName=file.getFileName();//取得从表单上传图片的图片名;

             //System.out.println("photoName:"+photoName);

         //photoName=file.getFilePathName();//取得从表单上传图片的图片名;

         //System.out.println("photoName:"+photoName);

         //另存到以Web应用程序的根目录为文件根目录的目录下

         //(声明一下:在Myeclipse中,该目录位于工程下的.metadata/.me_tcat/webapps/该工程目录/upload/)

         

         //file.saveAs("/upload/"+file.getFileName(),mySmartUpload.SAVE_VIRTUAL);

         //另存到操作系统的根目录为文件根目录的目录下

         //file.saveAs("/upload/"+file.getFileName(),mySmartUpload.SAVE_PHYSICAL);

         }//if

         }catch(Exception e)

         {

         System.out.println("上传图片错误:"+e.getMessage());

         }//catch

       

        String userid=mySmartUpload.getRequest().getParameter("userid");

        String password=mySmartUpload.getRequest().getParameter("password");

        String sex=mySmartUpload.getRequest().getParameter("sex");

        String repassword=mySmartUpload.getRequest().getParameter("repassword");

        String selfdescription=mySmartUpload.getRequest().getParameter("selfdescription");

        //判断登录帐号为空,则自动跳转到注册页面

        System.out.println("selfdescription:"+selfdescription);

                if(userid==null||userid.trim().length()==0)

                {

                    response.sendRedirect("register.jsp");

                }

                //如果登录密码为空,自动跳转到注册页面

                if(password==null||password.trim().length()==0)

                {

                    response.sendRedirect("register.jsp");

                }

                if(!password.equals(repassword))

                {

                    response.sendRedirect("register.jsp");

                }

        String directory=s1.getRealPath("/upload/");//取得服务器中图片的路径

        //System.out.println("directory:"+directory);

        File name=new File(directory,photoName);//创建名为name名的文件,保存文件的路径和名字;

        FileInputStream filename=new FileInputStream(name);//用二进制输入流输入

    String sql="insert into USERINFO(userid,password,sex,photo,selfdescription) values(?,?,?,?,?)";//values前要有空格

    try

    {

        PreparedStatement ps=cn.prepareStatement(sql);

        ps.setString(1, userid);

        ps.setString(2, password);

        ps.setString(3, sex);

        ps.setBinaryStream(4,filename,(int)name.length());

        ps.setString(5, selfdescription);

        ps.executeUpdate();

        ps.close();

        response.sendRedirect("login.jsp");

    }catch(Exception e)

    {

        System.out.print("取得sql连接出错:"+e.getMessage());

    }  

    }

    /**

     * Initialization of the servlet. <br>

     *

     * @throws ServletException if an error occurs

     */

    public void init(ServletConfig config) throws ServletException {

        super.init(config);

        ServletContext ctx=config.getServletContext();

        driverName=ctx.getInitParameter("driverName");

        url=ctx.getInitParameter("url");

        user=ctx.getInitParameter("user");

        pass=ctx.getInitParameter("pass");

        s1=config.getServletContext();

            try

            {

                Class.forName(driverName);

                cn=DriverManager.getConnection(url, user, pass);

            }catch(Exception e)

            {

                System.out.println("取得数据库连接错误:"+e.getMessage());

            }

    }

}

四、调试及运行

  1、出现的各种错误及解决办法,分析原因

2、运行(程序截图)

五、实验结果、分析和结论

通过HTTP响应处理以及会话跟踪实验,基本达到了实验的目的:熟悉JAVA EE开发环境,搭建WEB服务器架构。熟悉HTTP会话跟踪与编程以及HTTP响应处理编程,完成了实验的任务。第一个实验利用两个Java EE Web组件,实现了二进制类型响应,学会了搭建WEB 服务器构架;实验生成验证码,将Web项目部署到Tomcat服务器上,在登陆页面上嵌入了Serlet生成的随机验证码,并以图片形式显示,掌握了会话对象的使用,知道了会话对象可以作为跨越多次请求的共享容器对象,保存多次请求之间的共享信息,也进一步熟悉了JAVA EE的开发环境,积累了很多Java开发的经验,为以后的学习奠定了良好的基础,在以后的实验和学习中我会更加努力,不断提升自己的编程开发能力。

通过这次实验,了解了过滤器的概念和基本原理,进一步熟悉了Java EE的开发环境和基本操作步骤;

通过运用过滤器实现了用户登录验证和访问权限验证,为以后的学习打下了良好的基础。在以后学习中一定会更加努力,不断提升自己的编程能力。

对整个上机过程、上机结果进行总结、分析。包括收获、存在问题、改进等方面。

更多相关推荐:
大连理工大学实验报告模版

【大物实验】拉伸法测弹性模量http://hi.baidu.com/%CE%D2%B5%C4%D3%EE%D6%AE%D6%E6/blog/item/2fa915f54e65df75dcc4741b.html【…

RLC电流研究实验报告-大连理工大物实验

RLC电流研究实验报告

大连理工大学 大物实验报告 温度传感技术

这个实验操作步骤比较简单实验过程中主要就是等待不难老师是武震林人特别好报告为什么扣分我也不太清楚可能是数据点没用X表示需要注意的是伏安特性曲线要过原点有些点要舍去

大连理工大学盘锦校区大学物理实验报告页

大连理工大学大学物理实验报告实验报告完成日期学号姓名班级实验准备时间第周周第节实验完成时间第周周第节实验名称大连理工大学大学物理实验实验报告附件1预习与准备学号姓名班级实验准备时间年月日第周周第节实验名称大连理...

大工大物实验报告——低压气体直流击穿特性

低压气体直流击穿特性实验目的1研究低气压的实验和维持方法了解气压的测量原理2观测直流暗放电的脉冲现象研究电子碰撞引起雪崩电离的过程掌握分析和识别微观现象的实验方法认识低气压气体直流击穿现象研究雪崩电离过程与气体...

大工电机与拖动实验报告一

实验报告一实验名称单相变压器实验实验目的1通过空载和短路实验测定变压器的变比和参数2通过负载实验测取变压器的运行特性实验项目1空载实验测取空载特性U0fI0P0fU02短路实验测取短路特性UkfIkPkfI3负...

20xx年大连理工大学考研884物理化学及实验凯程学员回忆版

凯程考研集训营为学生引路为学员服务20xx年大连理工大学考研884物理化学及实验凯程学员回忆版选择填空题12小题每小题2分共24分恒温下反应As3Bg2CgDl判断该反应过程的H和U的大小正确答案是HU对于理想...

柏诺兹(J - 大学物理 大连理工大学国家级精品课程建设工程

柏诺兹JGeorgBednorz19xx和缪勒KarlAMuller19xx因发现钡镧铜氧系统中的高Tc超导电性共同分享了19xx年度诺贝尔物理学奖超导电性的发现使人们认识到超导技术有广泛的应用前景为了寻找更适...

大连理工大学物理与光电工程学院

大连理工大学物理与光电工程学院20xx年硕士研究生复试标准及复试方法学术型和全日制专业学位一复试分数线二复试比例以网上公布的复试名单为准按照物理学一级学科招生人数不含推免生下同的120来确定复试人数分专业排序录...

大连理工大学物理与光电工程学院

大连理工大学物理与光电工程学院20xx年硕士研究生复试标准及复试方法学术型和全日制专业学位一复试分数线二复试比例以网上公布的复试名单为准按照物理学一级学科招生人数不含推免生下同的120来确定复试人数分专业排序录...

大连理工大学考研物理试题及答案

考试日期20xx年1月19日下午大连理工大学二三年硕士生入学考试化工原理及实验试题注试题必须注明题号答在答题纸上否则试卷作废一填空45分1流体流动的两种基本类型为判断流体流动类型的无因次数群特征数2在重力场中流...

大连理工大学数字图像处理实验预习报告2

数字图像处理实验预习报告学院系电信学部专业电子信息工程班级电子1102姓名陈柯锦学号20xx81442组实验时间实验室实验台指导教师签字邢慧玲成绩实验名称图像的边缘检测一实验目的和要求1理解图像边缘提取的基本概...

大连理工大学大物实验报告(17篇)