정수리
309
2015-08-05 20:33:42
2
2059

어제 HTTP Status 500 - java.lang.NullPointerException 에러 나서 올렸는데 다시한번..


어제  HTTP Status 500 - java.lang.NullPointerException 에러가 나서 올렸는데 댓글로 많이 올려주셔서 감사합니다 ㅜ.ㅜ 말씀하신대로 admin_005fgoods_005flist_jsp에서 오류나는 부분을 찾았는데 어떤 것이 문제 인지 모르겠습니다 ㅜ.ㅜ

일단 상품을 등록하면 상품 리스트에 등록한 상품이 나오는 흐름입니다.

디비에는 상품이 잘들어 갑니다 에러 메시지를 보시면 

admin_goods_write//상품등록 폼 admin_005fgoods_005flist_jsp.java:165 라인에서 에러가 난다고 떠서

확인 해보니 165라인은  out.print(agb.getGOODS_IMAGE().split(",")[0] ); 입니다.


상품 리스트를 출력하는 jsp페이지

<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>
<%@ page import="java.util.*"%>
<%@ page import="jnmk.admin.goods.db.*"%>
<%
	ArrayList list = (ArrayList) request.getAttribute("list");
    GoodsBean agb = null;
%>
<html>
<head>
<title>쇼핑몰</title>
<script type="text/javascript">
function goodsdelete(goods_num){
	document.goodsform.action="./GoodsDelete.ag?goods_num="+goods_num;
	document.goodsform.submit();	
}
function goodsmodify(goods_num){
	document.goodsform.action="./GoodsModify.ag?goods_num="+goods_num;
	document.goodsform.submit();	
}
</script>
</head>
<body>
<table width="960" cellspacing="0" cellpadding="0" border="0"
	bordercolor="gray" align="center">
	<tr>
		<td colspan=2>
		<!-- 상품 목록 -->
		<table border="0" width="80%">
			<tr>
				<td height="22" bgcolor="#6699FF">
					<p align="center">
						<font size=2>상품목록</font>
					</p>
				</td>
			</tr>
			<tr>
				<td>
				<p align="right">
					<font size=2>
						<a href="./GoodsAdd.ag">상품등록</a>
					</font>
				</p>
				</td>
			</tr>
			<tr>
			<td>
			<form name=goodsform method="post">
			<table border="1">
			<tr>
				<td width="50">
				<p align="center"><font size=2>번호</font></p>
				</td>
				<td width="141">
				<p align="center"><font size=2>카테고리</font></p>
				</td>
				<td width="100">
				<p align="center"><font size=2>사진</font></p>
				</td>
				<td width="141">
				<p align="center"><font size=2>상품명</font></p>
				</td>
				<td width="141">
				<p align="center"><font size=2>단가</font></p>
				</td>
				<td width="80">
				<p align="center"><font size=2>수량</font></p>
				</td>
				<td width="141">
				<p align="center"><font size=2>등록일자</font></p>
				</td>
				<td width="100">
				<p align="center"><font size=2>&nbsp;</font></p>
				</td>
			</tr>
			<%
					for (int i = 0; i < list.size(); i++) {
					agb = (GoodsBean) list.get(i);
			%>
			<tr>
			<td>
			<p align="center">
				<font size=2><%=agb.getGOODS_NUM()%></font>
			</p>
			</td>
			<td>
			<p align="center">
				<font size=2>
					<%=agb.getGOODS_CATEGORY()%>
				</font>
			</p>
			</td>
			<td>
			<p align="center"><img
			src="./upload/<%=agb.getGOODS_IMAGE().split(",")[0] %>"//이부분에서 에러가뜹니다.
			width="50" height="50" border="0"></p>
			</td>
			<td>
			<p align="center">
				<font size=2><%=agb.getGOODS_NAME()%></font>
			</p>
			</td>
			<td>
			<p align="center">
				<font size=2><%=agb.getGOODS_PRICE()%></font>
			</p>
			</td>
			<td>
			<p align="center">
				<font size=2><%=agb.getGOODS_AMOUNT()%></font>
			</p>
			</td>
			<td>
			<p align="center">
				<font size=2>
					<%=agb.getGOODS_DATE().substring(0,10) %>
				</font>
			</p>
			</td>
			<td>
			<p align="center">
			<a href="javascript:goodsmodify(<%=agb.getGOODS_NUM()%>);">
				<font size=2>수정</font>
			</a>/
			<a href="javascript:goodsdelete(<%=agb.getGOODS_NUM()%>);">
				<font size=2>삭제</font>
			</a>
			</p>
			</td>
			</tr>
			<%
				}
			%>
			</table>
			</td>
			</tr>
			</form>
		</table>
		<!-- 상품 목록 -->
		</td>
	</tr>
</table>
</body>
</html>


상품 등록하는 비즈니스 로직

package jnmk.admin.goods.action;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import jnmk.admin.goods.db.*;
public class AdminGoodsAddAction implements Action {//상품등록 비즈니스 로직
	public ActionForward execute(HttpServletRequest request,
			HttpServletResponse response) {
		ActionForward forward = new ActionForward();
		AdminGoodsDAO agoodsdao= new AdminGoodsDAO();
		GoodsBean agb = new GoodsBean();
		String realPath = "";
		String savePath = "upload";
		int maxSize = 5 * 1024 * 1024;
		realPath = request.getRealPath(savePath);
		//서버 상의 물리적인 업로드 경로를 얻어 옴
		List savefiles=new ArrayList();
		try {
			MultipartRequest multi = null;
			multi = new MultipartRequest(request, realPath, maxSize, "euc-kr",
					new DefaultFileRenamePolicy());
			//
			Enumeration files=multi.getFileNames();
			while(files.hasMoreElements()){
				String name=(String)files.nextElement();
				//file input box 의 이름들을 하나씩 가져옴
				if(files.hasMoreElements()){
					//지금 가져온 이름 다음 이름이 더 있으면
					//즉, 지금 enumeration에서 가져온 이름이 마지막 요소가 아니면
					savefiles.add(multi.getFilesystemName(name)+",");
				}else{
					savefiles.add(multi.getFilesystemName(name));
				}
				//마지막 파일이 아니면 파일명 뒤에 , 를 붙여서 추가하고
				//마지막 파일이면 , 를 붙이지 않고 추가
			}
			StringBuffer fl=new StringBuffer();
			for(int i=0;i<savefiles.size();i++){
				fl.append(savefiles.get(i));	
			}
			//main.jpg,image1-1.jpg,image1-2.jpg,image1-3.jpg
			agb.setGOODS_CATEGORY(multi.getParameter("goods_category"));
			agb.setGOODS_NAME(multi.getParameter("goods_name"));
			agb.setGOODS_CONTENT(multi.getParameter("goods_content"));
			agb.setGOODS_SIZE(multi.getParameter("goods_size"));
			agb.setGOODS_COLOR(multi.getParameter("goods_color"));
			agb.setGOODS_AMOUNT(
					Integer.parseInt(multi.getParameter("goods_amount")));
			agb.setGOODS_PRICE(
					Integer.parseInt(multi.getParameter("goods_price")));
			agb.setGOODS_IMAGE(fl.toString());
			agb.setGOODS_BEST(
					Integer.parseInt(multi.getParameter("goods_best")));
			
			int result = agoodsdao.insertGoods(agb);
			//MultiPartRequest 객체 생성할 때 이미 업로드 처리 되었고
			//업로드 된 파일에 관련된 정보 속성들을 TO 객체에 담아서 파라미터로 전송하면서
			//DB에 입력 작업을 함
			if (result <= 0){
				response.setContentType("text/html;charset=euc-kr");
				PrintWriter out = response.getWriter();
				out.println("<script>");
				out.println("alert('등록실패')");
				out.println("history.back()");
				out.println("</script>");
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}		
		forward.setRedirect(true);
		forward.setPath("GoodsList.ag");
		return forward;
	}
}

실제 DB 저장 소스

package jnmk.admin.goods.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class AdminGoodsDAO {
	DataSource ds;
	Connection con = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	public AdminGoodsDAO(){
		try{
			Context initCtx=new InitialContext();
			   Context envCtx=(Context)initCtx.lookup("java:comp/env");
			   ds=(DataSource)envCtx.lookup("jdbc/jshop");
			  
		}catch(Exception ex){
			System.out.println("DB 연결 실패 : " + ex);
			return;
		}
	}
public int insertGoods(GoodsBean agb) {
		int result = 0;
		int num=0;
		String sql="select max(goods_num) from goods";
		try {
			con = ds.getConnection();
			pstmt=con.prepareStatement(sql);
			rs=pstmt.executeQuery();
			rs.next();
			num=rs.getInt(1)+1;
			sql="insert into goods (goods_num,goods_category,goods_name,goods_content,goods_size,goods_color,goods_amount,goods_price,goods_image,goods_best,goods_date) values "+
			"(?,?,?,?,?,?,?,?,?,?,now())";
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.setString(2, agb.getGOODS_CATEGORY());
			pstmt.setString(3, agb.getGOODS_NAME());
			pstmt.setString(4, agb.getGOODS_CONTENT());
			pstmt.setString(5, agb.getGOODS_SIZE());
			pstmt.setString(6, agb.getGOODS_COLOR());
			pstmt.setInt(7, agb.getGOODS_AMOUNT());
			pstmt.setInt(8, agb.getGOODS_PRICE());
			pstmt.setString(9, agb.getGOODS_IMAGE());
			pstmt.setInt(10, agb.getGOODS_BEST());
			result = pstmt.executeUpdate();
			} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			try{
				if(rs!=null)rs.close();
				if(pstmt!=null)pstmt.close();
				if(con!=null)con.close();
			}catch(Exception ex) {}
		}
		return result;
	}

상품리스트 가져오는 비지니스로직

package jnmk.admin.goods.action;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jnmk.admin.goods.db.*;
public class AdminGoodsListAction implements Action {
	public ActionForward execute(HttpServletRequest request,
			HttpServletResponse response) {
		AdminGoodsDAO agoodsdao=new AdminGoodsDAO();
		GoodsBean agb=new GoodsBean();
		
		ActionForward forward=new ActionForward();
		
		ArrayList list=(ArrayList)agoodsdao.getGoodsList();
		
		request.setAttribute("list",list);
		
		forward.setPath("./admingoods/admin_goods_list.jsp");
		return forward;
	}
}

DB에서 상품을 부르는 로직

package jnmk.admin.goods.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class AdminGoodsDAO {
	DataSource ds;
	Connection con = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	public AdminGoodsDAO(){
		try{
			Context initCtx=new InitialContext();
			   Context envCtx=(Context)initCtx.lookup("java:comp/env");
			   ds=(DataSource)envCtx.lookup("jdbc/jshop");
			  
		}catch(Exception ex){
			System.out.println("DB 연결 실패 : " + ex);
			return;
		}
	}
public List getGoodsList() {
		List goodslist = new ArrayList();
		try {
			con = ds.getConnection();
			String sql="select * from goods order by goods_num";
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				GoodsBean agb = new GoodsBean();
				agb.setGOODS_NUM(rs.getInt("goods_num"));
				agb.setGOODS_CATEGORY(rs.getString("goods_category"));
				agb.setGOODS_NAME(rs.getString("goods_name"));
				agb.setGOODS_CONTENT(rs.getString("goods_content"));
				agb.setGOODS_SIZE(rs.getString("goods_size"));
				agb.setGOODS_COLOR(rs.getString("goods_color"));
				agb.setGOODS_AMOUNT(rs.getInt("goods_amount"));
				agb.setGOODS_PRICE(rs.getInt("goods_price"));
				agb.setGOODS_IMAGE(rs.getString("goods_image"));
				agb.setGOODS_BEST(rs.getInt("goods_best"));
				agb.setGOODS_DATE(rs.getString("goods_date"));
				goodslist.add(agb);
			}
		} catch (Exception e) {
			e.getStackTrace();
		}
		finally{
			try{
				if(rs!=null)rs.close();
				if(pstmt!=null)pstmt.close();
				if(con!=null)con.close();
			}catch(Exception ex) {}
		}
		return goodslist;
	}


0
  • 답변 2

  • 오늘도삽질중
    831
    2015-08-05 22:08:53

    디비에 해당 이미지 파일의 값이 있는지 있으면

    이미지 파일의 값을 가져오는지 부터

    디버깅을 해보시는것이 좋아보이네요

  • 정수리
    309
    2015-08-05 22:39:06

    아감사합니다 ㅜ.ㅜ 말씀하신대로 해보니 디비에는 이미지 이름값이 들어가있는데 

    select문을 써서 가져올때 agb.setGOODS_IMAGE(rs.getString("goods_image")); 값을 보니

    null 값으로 되어있더라구요 ㅜ.ㅜ 왜 못불러오는지 모르겠네요 ㅜ.ㅜㅎㅎ 그래도 

    알려주셔서 감사합니다 ㅜㅜ.

  • 로그인을 하시면 답변을 등록할 수 있습니다.