상품(Good)에 대한 메소드와 정보를 담는 패키지 생성
package kr.or.dip.wshop.good;
1. AddGoodService.java
package kr.or.dip.wshop.good;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
/**
* Servlet implementation class for Servlet: AddGoodService
*
*/
public class AddGoodService extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public AddGoodService() {
super();
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=euc-kr");
String savePath="c://J2EE/Project/wshop/WebContent/image";
//저장할 디렉토리 (절대경로)
PrintWriter out = response.getWriter();
int sizeLimit = 5 * 1024 * 1024;
//5메가까지 제한 넘어서면 예외발생
try{
MultipartRequest multi=new MultipartRequest(request, savePath, sizeLimit, "euc-kr", new DefaultFileRenamePolicy());
//DefaultFileRenamePolicy() - 파일중복시 파일명에 일련번호 추가
Enumeration formNames=multi.getFileNames(); // 폼의 이름
String formName=(String)formNames.nextElement();
String fileName=multi.getFilesystemName(formName);
//클라이언트가 선택했던 파일이름
String originalName=multi.getOriginalFileName(formName);
String gname=multi.getParameter("gname");
String price=multi.getParameter("price");
String detail=multi.getParameter("detail");
Good good = new Good();
good.setGid(GoodDAO.getGid());
good.setGname(gname);
long longPrice = 0;
if(price!=null)
longPrice=Long.parseLong(price);
good.setPrice(longPrice);
good.setDetail(detail);
good.setImage(fileName);
GoodDAO.insertGood(good);
response.sendRedirect(request.getContextPath()+"/Good");
/*if(fileName == null) { // 파일이 업로드 되지 않았을
out.print("파일이 업로드 되지 않았음");
}else { // 파일이 업로드 되었을때
fileName=new String(fileName.getBytes("8859_1"),"euc-kr");//한글인코딩-브라우저에 출력
out.print("Form Name : " + formName + "<br>");
out.print("File Name : " + fileName + "<br>");
out.print("gname : " + gname + "<br>");
out.print("price : " + price + "<br>");
out.print("detail : " + detail + "<br>");
} // end if
*/
} catch(Exception e){
e.printStackTrace();
}
}
}
2.ConnectionUtil.java
package kr.or.dip.wshop.good;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class ConnectionUtil {
public static Connection getConnection() {
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/javadb";
con = DriverManager.getConnection(url,"root","1234");
System.out.println("con..."+con);
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void main(String args[]){
getConnection();
}
}
3.Good.java
package kr.or.dip.wshop.good;
/**
*
* 선택한 물건의 정보를 속성에 저장하는 객체
*
*/
public class Good {
private String gid;// 물건의 아이디
private String gname;// 물건의 이름
private long price;// 물건의 가격
private String detail; // 물건의 설명
private String image;// 물건의 이미지 파일의 이름
private int gty=1;
@Override
public boolean equals(Object obj) {
boolean equal = false;
if(obj instanceof Good){
Good good=(Good)obj;
if(good.getGid().equals(gid))
equal=true;
}
return equal;
}
public String getGid() {
return gid;
}
public void setGid(String gid) {
this.gid = gid;
}
public String getGname() {
return gname;
}
public void setGname(String gname) {
this.gname = gname;
}
public long getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public int getGty() {
return gty;
}
public void setGty(int gty) {
this.gty = gty;
}
}
4.GoodDAO.java
package kr.or.dip.wshop.good;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import kr.or.dip.wshop.good.Good;
public class GoodDAO {
public static String getGid()throws Exception {
Connection conn=null;
PreparedStatement psmt=null;
ResultSet rs=null;
String sql=null;
// Good good=null;
long gid = 0;
try{
conn=ConnectionUtil.getConnection();
/*1.변수 sql에 SELECT max(gid) FROM good 쿼리를 대입*/
sql = "Select max(gid)" + " from good";
/*2.PreparedStatement 타입의 객체를 생성*/
psmt = conn.prepareStatement(sql);
/*3.SELECT 쿼리를 실행하고 rs에 검색결과 대입*/
rs=psmt.executeQuery();
/*4. 4의 rs에서 검색된 결과가 있다면 컬럼의 데이터를 gid=rs.getLong(1); */
if(rs.next())
{
gid=rs.getLong(1);
}
}catch(Exception e){e.printStackTrace();
}finally{
try{rs.close();}catch(Exception e){ }
try{psmt.close();}catch(Exception e){ }
try{conn.close();}catch(Exception e){ }
}
/* 5. gid 값을 1증가시킨후 String으로 변환 해서 리턴) */
return new Long(++gid).toString();
}
// 물품정보를 DB에 저장
public static void insertGood(Good good)throws Exception {
Connection conn=null;
PreparedStatement psmt=null;
ResultSet rs=null;
String sql=null;
//Good good=null;
try{
conn=ConnectionUtil.getConnection();
if(GoodDAO.selectGood(good.getGid()) != null) throw new Exception("존재하는 상품입니다.");
/*1.변수 sql에 INSERT쿼리를 대입*/
sql = "insert into good" + " (gid, gname, price, detail, image)" + " values(?,?,?,?,?)";
/*2.PreparedStatement 타입의 객체를 생성*/
psmt = conn.prepareStatement(sql);
/*3.2에서 생성한 객체의 ? 에 good.gid,
* good.gname, good.price, good.detail, good.image 대입 */
psmt.setString(1,good.getGid());
psmt.setString(2,good.getGname());
psmt.setLong(3,good.getPrice());
psmt.setString(4,good.getDetail());
psmt.setString(5,good.getImage());
/*4.INSERT 쿼리를 실행
* studentWeb의 StudentDAO의 insertStudent 참고구현*/
psmt.executeUpdate();
}catch(Exception e){e.printStackTrace();
}finally{
try{rs.close();}catch(Exception e){ }
try{psmt.close();}catch(Exception e){ }
try{conn.close();}catch(Exception e){ }
}
// return good;
}
/*물품정보검색*/
public static Good selectGood(String gid)throws Exception {
Connection conn=null;
PreparedStatement psmt=null;
ResultSet rs=null;
String sql=null;
Good good=null;
try{
conn=ConnectionUtil.getConnection();
/*1.변수 sql에 SELECT쿼리를 대입*/
sql = "Select gid, gname, price, detail, image" + " from good where gid=?";
/*2.PreparedStatement 타입의 객체를 생성*/
psmt = conn.prepareStatement(sql);
/*3.2에서 생성한 객체의 ? 에 인자 gid 대입 */
psmt.setString(1,gid);
/*4.SELECT 쿼리를 실행하고 rs에 검색결과 대입*/
rs=psmt.executeQuery();
/*5. 4의 rs에서 검색된 결과가 있다면 Good객체를 생성
* 각 컬럼의 데이터를 꺼내서 Good 객체의
* set메서드를 호출해서 검색 결과를 대입*/
if(rs.next())
{
good=new Good();
good.setGid(rs.getString(1));
good.setGname(rs.getString(2));
good.setPrice(rs.getLong(3));
good.setDetail(rs.getString(4));
good.setImage(rs.getString(5));
}
}catch(Exception e){e.printStackTrace();
}finally{
try{rs.close();}catch(Exception e){ }
try{psmt.close();}catch(Exception e){ }
try{conn.close();}catch(Exception e){ }
}
return good;
}
public static ArrayList selectGoodList()throws Exception {
Connection conn=null;
PreparedStatement psmt=null;
ResultSet rs=null;
String sql=null;
ArrayList <Good>list =new ArrayList<Good>();
try{
conn=ConnectionUtil.getConnection();
/*1.변수 sql에 SELECT쿼리를 대입*/
sql = "Select gid, gname, price, detail, image" + " from Good ";
/*2.PreparedStatement 타입의 객체를 생성*/
psmt = conn.prepareStatement(sql);
/*3.SELECT 쿼리를 실행하고 rs에 검색결과 대입*/
rs=psmt.executeQuery();
/*4. 3의 rs에서 검색된 결과가 있다면 Good객체를 생성
* 각 컬럼의 데이터를 꺼내서 Good 객체의
* set메서드를 호출해서 검색 결과를 대입*/
while(rs.next()){
Good good = new Good();
good.setGid(rs.getString(1));
good.setGname(rs.getString(2));
good.setPrice(rs.getLong(3));
good.setDetail(rs.getString(4));
good.setImage(rs.getString(5));
/*5.4의 객체를 list에 추가list.add(good);*/
list.add(good);
}
}catch(Exception e){e.printStackTrace();
}finally{
try{psmt.close();}catch(Exception e){}
try{conn.close();}catch(Exception e){}
}
return list;
}
public static void main(String args[])
throws Exception{
Good newGood = new Good();
newGood.setGid(GoodDAO.getGid());
newGood.setGname("잭필드3종세트");
newGood.setPrice(39000);
newGood.setImage("jack.gif");
newGood.setDetail("놀라지 마십시오 잭필드 3종세트" + "단돈 3만9천원!!!");
GoodDAO.insertGood(newGood);
ArrayList <Good> list = GoodDAO.selectGoodList();
for(int i=0;i<list.size();i++){
Good good=list.get(i);
System.out.println(good.getGid());
System.out.println(good.getGname());
System.out.println(good.getPrice());
System.out.println(good.getImage());
System.out.println(good.getDetail());
System.out.println("==================");
}
Good pin=GoodDAO.selectGood("1030");
System.out.println("===========================");
System.out.println("===========================");
System.out.println("gid 1030의 검색 결과");
System.out.println(pin.getGid());
System.out.println(pin.getGname());
System.out.println(pin.getPrice());
System.out.println(pin.getImage());
System.out.println(pin.getDetail());
System.out.println("===========================");
}
}
5. GoodService.java
package kr.or.dip.wshop.good;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
public class GoodService extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("euc-kr");
String method = request.getParameter("method");
if(method==null){
method="viewGoodList";
}
try{
if(method.equals("viewGood")){
viewGood(request,response);
}else {
viewGoodList(request,response);
}
}catch(Exception e){e.printStackTrace();}
}
public static void viewGoodList(HttpServletRequest request,HttpServletResponse response) throws Exception{
/*1.GoodDAO의 selectGoodList( ) 메서드 호출해서
* 전체 상품정보를 ArrayList 타입변수에 대입*/
ArrayList list=GoodDAO.selectGoodList();
/*2. 1의 list 를 request 에 Good_LIST 속성에
* 저장 */
request.setAttribute("GOOD_LIST", list);
/* 3.RequestDispatcher 를 이용
* viewGoodList.jsp 로 이동 */
RequestDispatcher rd = request.getRequestDispatcher("/good/viewGoodList.jsp");
rd.forward(request,response);
}
public static void viewGood(HttpServletRequest request,HttpServletResponse response) throws Exception{
/*1.파라메터에서 물건아이디를 입력받아서 변수에 대입*/
String gid = request.getParameter("gid");
/*2.GoodDAO의 viewGood() 메서드 호출해서
* 검색된 물건정보를 변수에 대입*/
Good GOOD = GoodDAO.selectGood(gid);
/*3.검색된 물건정보 를 request객체의 GOOD
* 속성에 대입*/
request.setAttribute("GOOD", GOOD);
/*4.RequestDispatcher 를 이용
* viewGood.jsp로 이동*/
RequestDispatcher rd = request.getRequestDispatcher("/good/viewGood.jsp");
rd.forward(request, response);
}
}




덧글