Package

Source Code of SimpleBBSEntry

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
*
* @author nagayama
*/
@WebServlet(urlPatterns = {"/SimpleBBSEntry"})
@MultipartConfig(fileSizeThreshold = 5000000, maxFileSize = 10000000, location = "C:\\Data")
public class SimpleBBSEntry extends HttpServlet
{
    public static final String CONTENT_UTF8  = CommonsText.CONTENT_HTML_UTF8;
    private static final int NAME_MAX_LENGTH = 64;
    private static final String NAME_MAX_LENGTH_ERROR_MESSAGE = "名前が長すぎます。" + Integer.toString(NAME_MAX_LENGTH) + "文字以下にしてください。";
    private static final int CONTENT_MAX_LENGTH = 512;
    private static final String CONTENT_MAX_LENGTH_ERROR_MESSAGE = "内容が長すぎます。" + Integer.toString(CONTENT_MAX_LENGTH) + "文字以下にしてください。";

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try
        {
            //日時情報の定義
            SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy'/'MM'/'dd'('E')' HH:mm:ss");
            Date resDate = new Date();
            //各アイテムの取得
            String time  = simpleDate.format(resDate).toString();
            String name  = new String(request.getParameter("post_name").getBytes("iso-8859-1"), "UTF-8");
            String text  = new String(request.getParameter("post_content").getBytes("iso-8859-1"), "UTF-8");
            String file  = CommonsText.ENPTY;
//            // アップロードファイル情報を記録(確認用)
//            FileWriter fw = new FileWriter(new File("c:\\data\\check.txt"));
//            fw.write(time + CommonsText.LFCR + name + CommonsText.LFCR + text + CommonsText.LFCR);
//            fw.close();
            // 例外処理 (長すぎる場合 IOException)
            CommonsText.checkMaxLength(name, NAME_MAX_LENGTH, NAME_MAX_LENGTH_ERROR_MESSAGE);
            CommonsText.checkMaxLength(text, CONTENT_MAX_LENGTH, CONTENT_MAX_LENGTH_ERROR_MESSAGE);
            // 画像追加
            // <INPUT type="file" name="post_file"> で指定した名前より取得
            Part part = request.getPart("post_file");
            file  = uploadFile(part);
            // 投稿情報を追加
            Response addResponse =  new Response(time, name, text, CommonsText.ENPTY, file);
            ResponseManager resManager = new ResponseManager();
            boolean error = !resManager.add(addResponse);
            // 追加成否による後処理
            if(error)
            {
                out.println("<div>Error</div>");
//                response.sendRedirect("./BadRequest");
            }
            else
            {
//                response.sendRedirect("./BBS");
            }
        }
        finally
        {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo()
    {
        return "Short description";
    }// </editor-fold>
   
    private String getFilename(Part part)
    {
        for (String cd : part.getHeader("Content-Disposition").split(";"))
        {
            if (cd.trim().startsWith("filename"))
            {
                return cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
       
    /**
     * ファイルアップロードメソッド
     * @param part
     * @return
     * @throws IOException
     */
    private String uploadFile(Part part)
            throws IOException
    {
        String file = CommonsText.ENPTY;
        try
        {
            // アップロードファイル情報を記録(Part確認用)
            FileWriter fw = new FileWriter(new File("c:\\data\\log.txt"));
            fw.write(part.toString());
            fw.close();
            // アップロードファイルが存在するならば保存
            if(part.getSize() != 0)
            {
                // ファイル名の取得
                String pname = getFilename(part);
                // ファイルの保存 @MultipartConfig(location="C:\\Data") で設定した
                // ディレクトリ配下に保存される。
                part.write(pname);
                file  = pname;
            }
        } catch (IOException ex) {
            Logger.getLogger(Entry.class.getName()).log(Level.SEVERE, null, ex);
            throw new IOException();
        }
        finally
        {
            return file;
        }
    }
}
TOP

Related Classes of SimpleBBSEntry

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.