I am working on a dynamic project for my own but struggling to create an article. The idea is that one registered user can publish an article with an image .

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>


    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/articlecontroller" encType="multipart/form-data">

<input type="file" name="file" value="Select image ..." />
 title:<input type="text" name="title"/><br/>
            content:
            <textarea name="content" cols="80" rows="15"></textarea>
            <br/>
            poster:<input type="file" name="poster"/><br/>

<input type="submit" value="Start upload" />
</form>


</body>
</html>

and the servlet is

package Controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import Database.Article;

/**
 * Servlet implementation class articlecontroller
 */

@WebServlet("/articleontroller")
public class articlecontroller extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */

    private DataSource ds;
    String imgname = null;

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

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */

    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub

        try {
            InitialContext initContext = new InitialContext();

            Context env = (Context) initContext.lookup("java:comp/env");

            ds = (DataSource) env.lookup("jdbc/therap");

        } catch (NamingException e) {
            throw new ServletException();
        }

    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        PrintWriter out = response.getWriter();


            if (!ServletFileUpload.isMultipartContent(request)) {
                out.println("Nothing uploaded");
                return;
            }

            FileItemFactory itemFactory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(itemFactory);

            try {
                List<FileItem> items = upload.parseRequest(request);

                for (FileItem item : items) {
                    String contentType = item.getContentType();

                    if (!contentType.equals("image/png")) {
                        out.println("Only png format image files supported");
                        continue;
                    }

                    File uploadDir = new File(
                            "C:\\workspace\\servlets2\\upload");
                    File file = File.createTempFile("img", ".png", uploadDir);

                    item.write(file);


                }

            } catch (FileUploadException e) {
                out.println("Upload failed.");
                return;
            } catch (Exception ex) {
                out.println("Can't save file");
            }

        }

        // File copied to hardrive upto by these lines of code

        String author = "Admin";
    String content = request.getParameter("content");
    String title = request.getParameter("title");

    Connection conn = null;

    try {
        conn = ds.getConnection();
    } catch (SQLException e) {
        throw new ServletException();
    }

    Article art = new Article(conn);

    try {
        art.createArticle(author,title,content,imgname);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
         out.println(e);
    }
    request.getRequestDispatcher("/articlesuccess.jsp").forward(request, response);


    }

and Article class is like

package Database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;


public class Article {


    private Connection conn;

    public Article(Connection conn) {
        this.conn = conn;
    }

    public void createArticle(String au,String ti,String con,String imn) throws SQLException{


        String sql = "insert into article(article_author,article_title,article_content,article_post_date,article_poster) values(?,?,?,NOW(),?) ";

        PreparedStatement stmt = conn.prepareStatement(sql);

        stmt.setString(1,au);
        stmt.setString(2,ti );
        stmt.setString(3, con);
        stmt.setString(4, imn);


        stmt.executeUpdate();

        stmt.close();



    }

}

where my article table in database name therap is like

CREATE TABLE IF NOT EXISTS `article` (
  `article_content` longtext  NOT NULL,
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `article_author` int(11) NOT NULL,
  `article_title` text  NOT NULL,
  `article_post_date` datetime NOT NULL,
  `article-modify_date` datetime,
  `article_poster` varchar(50) DEFAULT NULL,
  `article_view` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

help me get out of this problem. I think I did my mistake in jsp form.

Recommended Answers

All 2 Replies

What is the error?
Can you please tell us the error you are getting in jsp ?
Did you verify the server logs? please give the server logs for the issue?

It is a good practice to use some logging framework like log4j to log important events in the application.
please use log4j in your application to debug the issue.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.