간단한 미니게시판을 만드는 프로젝트를 진행 및 정리하고자 한다.
JNDI 방법을 사용하려 한다.
글목록보기
JNDI(Java Naming Directory Interface)->DB연결의 정보->Context.xml 저장
->DB정보이름(default jdbc/orcl,,,) 등록=>DAO=>url,driver,계정,암호X(필요없다)->암기X
JNDI이름을 검색(연결객체 가져옴)
이름을 가지고 찾아내는 시스템
web.xml 작성
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>SpringMVC</display-name>
<!-- 요청을 받아서 처리해주는 컨트롤러 클래스를 등록
환경설정(test-servlet.xml)로 지정 -->
<servlet>
<servlet-name>borad</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>board</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
board-servlet.xml 만들기
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- (4)viewResolver(위치(prefix),이동할페이지의 확장자(suffix)지정 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- (2) 요청명령어에 따른 처리해주는 컨트롤러를 문의? -->
<bean id="defaultHandlerMapping"
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<!-- (3) 요청명령어에 해당하는 컨트롤러를 이용
<bean name="/요청명령어.do" class="패키지명...처리할 컨트롤러클래스명" />
/index.do -> /list.jsp 이동
setViewName("list")->페이지 이동시켜주는 메서드
-->
<bean name="/index.do"
class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName" value="list" />
</bean>
<bean name="/good/index.do"
class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName" value="list2" />
</bean>
<!-- 요청명령어에 따른 컨트롤러 클래스를 작성(=모델2의 액션클래스) -->
<bean name="/index2.do" class="lee.TestActionController" />
</beans>
db연동
Context.xml를 생성해서 작업
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource nama="jdbc/orcl"
auth="container"
type="javax.sql.DataSource"
username="scott"
password="tiger"
driverClassName="oracle.jdbc.driver.OracleDriver"
factory="org.apache.commons.dbcp.BasicDataSourceFactory"
url="jdbc:oracle:thin:@localhost:1521:orcl"
maxActive="20"
maxIdle="10"/>
</Context>
테이블생성
테이블
오라클에 입력
create table springboard(
num number(3) primary key,
author varchar2(15),
title varchar2(50),
content varchar2(4000),
writeday date default sysdate,
readcnt number(4) default 0);
insert into springboard(num,author,title,content)
values(1,'홍길동','스프링 연습1','스프링 테스트 내용중');
commit;
DTO만들기 => Board.java
-DTO를 Board.java로 만드려한다.
package lee;
public class Board {//BoardVO or BoardDTO
private int num;
private String author,title,content,date;
private int readcnt;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getReadcnt() {
return readcnt;
}
public void setReadcnt(int readcnt) {
this.readcnt = readcnt;
}
}
DAO만들기 => BoardDAO
package lee;
import java.sql.*;//Connection~등을 사용하기 위해
import java.util.*;//ArrayList,List~등을 사용하기 위해
/////////JNDI 방법//////////
import javax.sql.*;//DataSource객체->getConnection()
import javax.naming.*;//Context(인터페이스),InitialContext(자식)
// jdbc/orcl=>lookup('찾고자하는 jndi명')
///////////////////////////
public class BoardDAO{
DataSource ds; //DBConnectionMgr pool;와 기능이 같다.
public BoardDAO(){
//생성자 : DataSource 얻기 : InitialContext 와 JNDI 명
try {
//InitialContext ctx=new InitialContext();
Context ctx=new InitialContext(); // 인터페이스를 자식클래스로 가져옴
//형식) ds객체=(DataSource)ctx객체명.lookup("java:componet/env/찾는 이름명")
ds=(DataSource)ctx.lookup("java:component/env/jdbc/orcl");
System.out.println("ds=>"+ds);//Connection객체
}catch(Exception e) {
e.printStackTrace();
}
}
//public List list(){
public ArrayList list(){ //글목록보기->레코드여러개 존재(ex 회원리스트,상품리스트,예약리스트)
ArrayList list = new ArrayList();
try{
String sql = "SELECT * FROM springboard ORDER BY num desc";
//----------------------------------------------
Connection con = ds.getConnection();
//Connection con = pool.getConnection();
//---------------------------------------------------
PreparedStatement stmt = con.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while(rs.next()){//더이상 불러올수 없을때까지
Board data = new Board();
data.setNum( rs.getInt( "num" ) );
data.setAuthor(rs.getString( "author" ));
data.setTitle(rs.getString( "title"));
data.setContent(rs.getString( "content" ));
data.setDate(rs.getString( "writeday" ));
data.setReadcnt(rs.getInt( "readcnt" ));
list.add( data );
}//end while
rs.close(); stmt.close(); con.close();//finally구분에 사용
}catch(Exception e){ e.printStackTrace(); }
return list;//list.jsp에 출력
}//end list
board-servlet.xml에 환경설정 내용추가
-----------------------------------------
~생략~
<!-- 0.DB접속 -->
<bean id="boardDAO" class="lee.BoardDAO" />
<!-- 1.글목록보기 (list()) setDao(BoardDAO객체)-->
<bean name="/list.do" class="lee.ListActionController">
<property name="dao">
<ref bean="boardDAO" />
</property>
</bean>
ListActionController 생성 (컨트롤러)
-글목록보기에 관한 컨트롤러다
package lee;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
//public class ListAction implements CommandAction(페이지 이동,클래스는 틀리지만 처리메서드동일)
public class ListActionController implements Controller {
BoardDAO dao;//BoardDAO dao=new BoardDAO();
public void setDao(BoardDAO dao) {//<property name="dao"><ref bean="id명" />~
this.dao=dao;
System.out.println("setDao() 호출됨(dao)=>"+dao);
}
@Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
System.out.println("ListActionController의 handleRequest()호출됨");
ArrayList list=dao.list();
//화면에 출력할 list.jsp에 전달할 페이지와 전달할값을 설정하기위해서 필요
ModelAndView mav=new ModelAndView();//이동할페이지,화면에 출력할 데이터를 임시저장
mav.setViewName("list");//이동할 페이지명만 지정=>경로? 확장자?
//모델2=>request.setAttribute("키명",저장할값)->request.getAttribute("키명")
mav.addObject("list",list);//request.setAttribute("list",list);
//${list(키명)}
return mav; //return "/list.jsp";->viewResolver가 분리 /list3.jsp
}
}
list.jsp생성
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="java.util.*,lee.*" %>
<html><body>
<table border="1">
<tr>
<td align="center" colspan="5">
*** 게시판 목록 ***
<a href="writeui.do">글쓰기</a>
</td>
</tr>
<tr>
<th>번호</th><th>제목</th><th>작성자</th><th>작성일</th><th>조회수</th>
</tr>
<%
ArrayList list=(ArrayList)request.getAttribute("list"); //${list}
if(list!=null){ //데이터가 존재한다면
Iterator iter=list.iterator();//ArrayList->iterator()이용,Enumeration객체
while(iter.hasNext()){//꺼낼 데이터가 존재한다면
Board data=(Board)iter.next();//Object->(Board)형으로 형변환
int num=data.getNum();
String title=data.getTitle();
String author=data.getAuthor();//작성자
String content=data.getContent();//글 내용
String writeday=data.getDate();//날짜출력시->10글짜만 뽑아서 출력하도록 코딩
int readcnt=data.getReadcnt();//조회수
%>
<tr>
<td align="center"><%= num %></td>
<td><a href="retrieve.do?num=<%= num %>"><%= title %></a></td>
<td><%= author %></td>
<td><%= writeday.substring(0,10)%></td>
<td><%= readcnt%></td>
</tr>
<%
}//end while
}//end if
%>
<!-- 검색 기능 시작 -->
<tr><td colspan="5" align="center">
<form action="search.do">
<select name="searchName" size="1">
<option value="author">작성자</option>
<option value="title">제목</option>
</select>
<input type="text" name="searchValue"><input type="submit" value="검색">
</form>
</td></tr>
</table>
</body></html>
만든 게시판의 글쓰기를 클릭하면 글쓰기 부분으로 이동되도록하고싶다면
board-servlet.xml에 환경설정 내용추가
~생략~
<!-- 2.글쓰기 폼으로 이동시 사용-->
<bean name="/writeui.do"
class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName" value="write" />
</bean>
글쓰기
BoardDAO 글쓰기 메서드 추가
~생략~
//글쓰기
public int getNewNum(){ //글쓰기 번호 얻기
int newNum=1;//저장할 게시물번호 디폴트 설정값1
try {
String sql="select max(num) from springboard";
Connection con=ds.getConnection();
PreparedStatement pstmt=con.prepareStatement(sql);
ResultSet rs=pstmt.executeQuery();
if(rs.next()) {//최대값+1 => 다음번에 저장할게시물번호
newNum=rs.getInt(1)+1;
}
}catch(Exception e) {e.printStackTrace();}
return newNum;
}//end getNewNum();
//public void write(Board board){
public void write(String author, String title , String content){
try{
int newNum = getNewNum();//2
String sql ="insert into springboard(num,author,title,content) values(";
sql += newNum + ",'" + author + "','" + title + "','" + content + "')";
System.out.println(sql);//sql구문을 통한 데이터입력값 확인
Connection con = ds.getConnection();
PreparedStatement stmt = con.prepareStatement(sql);
stmt.execute(sql);//pstmt.executeUpdate(sql);//정석 => execute로 써도된다
stmt.close(); con.close();
}catch(Exception e ) {e.printStackTrace();}
}//end write
write.jsp 생성
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="write.do">
제 목 : <input type="text" name="title" /><br/>
작성자 : <input type="text" name="author" /><br/>
내 용 : <textarea name="content" rows="5" cols="30"></textarea><p/>
<input type="submit" value="저장" />
</form>
</body>
</html>
board-servlet.xml에 환경설정 내용추가 (요청명령어 등록 )
~생략~
<!-- 3)글쓰기(글수정하기와 거의 유사) -->
<bean name="/write.do" class="lee.WriteActionController">
<property name="dao">
<ref bean="boardDAO" />
</property>
<property name="commandClass" value="lee.BoardCommand"/>
</bean>
BoardCommand 생성
BpardDTO 또는 VO는 하나의 레코드에 관련된 필드와 연관이있는 클래스다
하지만 BoardCommandsms 실질적으로 사용자로부터 값을 입력을 받는 필드로만 구성된 클래스다
직접 입력받는 author,title,content만 사용한다.
package lee;
/*
*BoardDTO or BoardVO->하나의 레코드에 관련된 필드와 연관이있는 클래스
*BoardCommand=>실질적으로 사용자로부터 값을 입력을 받는
* 필드로만 구성된 클래스
*/
public class BoardCommand {
String author,title,content;//num,data,readcnt=>입력X
//스프링=><jsp:setProperty name="~" property="*" />
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
System.out.println("setAuthor() call");
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
System.out.println("setTitle() call");
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
System.out.println("setContent() call");
}
}
WriteActionController 생성 (컨트롤러)
AbstractCommandController를 상속받는다
=>(글쓰기,글수정,회원가입,회원수정)같이 입력을 받아서 처리할때 상속받는다
=>(페이지 이동(글쓰기폼),글상세보기,글삭제(출력목적)같이 입력받지 않고 처리할땐 Controller를 상속받는다.
commandClasss는 AbstractCommandController가 가지고있어서 따로 멤버변수를 설정하고 호출할 필요없다
주석에 설명이 많다 잘 읽어보자
package lee;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;
/*
* 입력을 받아서 처리(글쓰기,글수정,회원가입,회원수정)->AbstractCommandController을 상속받는다
* 입력X 처리(페이지 이동(글쓰기폼),글상세보기,글삭제(출력목적))->Controller를 상속받는다.
*/
public class WriteActionController extends AbstractCommandController {
/* 상속때문에 부모의 멤버변수,메서드를 이미 가지고 있는 상태
* <property name="commandClass" value="lee.BoardCommand"/>
setCommandClass(BoardCommand)호출
*commandClasss는 AbstractCommandController가 가지고있어서 따로 멤버변수를 설정하고 호출할 필요없다
*/
BoardDAO dao;
public void setDao(BoardDAO dao) {
this.dao = dao;
System.out.println("setDao() write call");
}
//1.request(요청객체) 2.response(응답객체)
//3.입력받은값을 저장한 객체(Object->자료형에 상관없이 다 저장이 가능하게 설정)
//4.BindException->사용자로부터 값을 입력시 에러발생->예외처리클래스
@Override
protected ModelAndView handle(HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException error)
throws Exception {
// TODO Auto-generated method stub
System.out.println("WriteActionController execute");
request.setCharacterEncoding("utf-8");//한글처리
BoardCommand data=(BoardCommand)command; //BoardCommand의 값을 받음
//확인
String author=data.getAuthor();
String title=data.getTitle();
String content=data.getContent();
/*
*AbstractCommandController를 사용하지 않는다면 이렇게 다써야한다.
*
* BoardCommand commend=new BoardCommand();
*String author=request.getParameter("author);
*command.setAuthor(author)
*/
dao.write(author, title, content);//dao.write(date);
//response.sendRedirect("list.jsp")
//=>형식) redirect:/요청명령어->/list.jsp
//글쓰기버튼->/write.do(저장)->/list.do->ListActionController->/list.jsp
/*
ModelAndView mav=new ModelAndView("redirect:/list.do");//404에러 조심
return mav;
위에꺼를 이렇게 쓸수있다*/
return new ModelAndView("redirect:/list.do");
}
}
글상세보기
board-servlet.xml에 환경설정 내용추가 (요청명령어 등록)
~생략~
<!-- 4)글상세보기 -->
<bean name="/retrieve.do" class="lee.RetrieveActionController">
<property name="dao">
<ref bean="boardDAO" />
</property>
</bean>
BoardDAO에 글상세보기 추가
~생략~
//글상세보기->1.조회수증가 2.검색해서 화면에 출력(글 상세 보기위해서 번호를 검색하기때문)
public Board retrieve(String num){ // 글 자세히 보기
Board data=new Board();
try {
String sql="update springboard set readcnt=readcnt+1 where num="+num;
Connection con=ds.getConnection();
PreparedStatement pstmt=con.prepareStatement(sql);
int update=pstmt.executeUpdate(sql);//1 성공 0 실패
System.out.println("조회수 증가유무(update)=>"+update);
pstmt=null;//전에 저장된 정보를 제거 => 제거하고 새로운 sql실행
sql="select * from springboard where num="+num;
pstmt=con.prepareStatement(sql);
ResultSet rs=pstmt.executeQuery();
if(rs.next()) {
data.setNum(rs.getInt("num"));
data.setAuthor(rs.getString("author"));
data.setTitle(rs.getString("title"));
data.setContent(rs.getString("content"));
}
rs.close(); pstmt.close(); con.close();
}catch(Exception e) {
e.printStackTrace();
}
return data;
}//end retrieve
RetrieveActionController작성 (컨트롤러)
package lee;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class RetrieveActionController implements Controller {
BoardDAO dao;//BoardDAO dao=new BoardDAO();
public void setDao(BoardDAO dao) {//<property name="dao"><ref bean="id명" />~
this.dao=dao;
System.out.println("setDao() 호출됨(dao)=>"+dao);
}
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
System.out.println("Retrieve~ handleRequest()호출됨");
//글상세보기 메서드 호출-> /retrieve.do?num=3
//ArrayList list=dao.list();
String num=request.getParameter("num");
Board data=dao.retrieve(num);
//화면에 출력할 list.jsp에 전달할 체이지명과 전달할값을 설정
/*
ModelAndView mav=new ModelAndView();//이동할페이지,화면에 출력할 데이터를 임시저장
mav.setViewName("retrieve");//이동할 페이지명만 지정=>경로? 확장자?
*/
//생성자(이동할 페이지명(=redirect:/요청명령어)) 위에 두줄을 이렇게 한줄로 가능
ModelAndView mav=new ModelAndView("retrieve");
mav.addObject("data",data);//경로? 확장자?
//${list(키명)}
return mav; //return "/list.jsp";->viewResolver가 분리 /list3.jsp
}
}
retrieve.jsp 생성하여 출력
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="lee.*" %>
<%
Board data=(Board)request.getAttribute("data");//${data}
//웹상에서 Getter Method
int num=data.getNum();
String title=data.getTitle();
String author=data.getAuthor();
String content=data.getContent();
%>
<!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=UTF-8">
<title>내용보기 및 수정</title>
</head>
<body>
<form action="update.do">
<!-- readonly="readonly"(읽기전용) -->
번 호 : <input type="text" name="num" value="<%= num %>" readonly="readonly" /><br>
제 목 : <input type="text" name="title" value="<%= title %>"><br>
작성자:<input type="text" name="author" value="<%= author %>"><br>
내 용 : <textarea name="content" rows="5" cols="30"><%= content %></textarea><p/>
<input type="submit" value="수정완료" />
<a href="delete.do?num=<%= num %>">삭제</a>
<a href="list.do">목록보기</a>
</form>
</body>
</html>
글수정
board-servlet.xml에 환경설정 내용추가 (요청명령어 등록)
~생략~
<!-- 5)글수정하기 -->
<bean name="/update.do" class="lee.UpdateActionController">
<property name="dao">
<ref bean="boardDAO" />
</property>
<property name="commandClass" value="lee.BoardCommand"/>
</bean>
BoardDAO에 글수정하기 추가
~생략~
//글수정하기
public void update( String num , String author,
String title , String content){ // 글 수정하기
try{
String sql ="update springboard set title='" + title + "',";
sql += " content='" + content+"',";
sql += " author ='" + author+"'";
sql += " where num=" + num;
System.out.println(sql);
Connection con = ds.getConnection();
PreparedStatement stmt = con.prepareStatement(sql);
int update=stmt.executeUpdate(sql);
System.out.println("데이터수정유무(update)=>"+update);
stmt.close(); con.close();
}catch(Exception e){e.printStackTrace();}
}//end update
UpdateActionController를 작성
package lee;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;
public class UpdateActionController extends AbstractCommandController {
BoardDAO dao;
public void setDao(BoardDAO dao) {
this.dao = dao;
System.out.println("setDao() write call");
}
@Override
protected ModelAndView handle(HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException error)
throws Exception {
// TODO Auto-generated method stub
System.out.println("UpdateActionController execute");
request.setCharacterEncoding("utf-8");//한글처리
BoardCommand data=(BoardCommand)command;
//추가(게시물번호가 전달->hidden객체 or 읽기전용 inputbox전달)
String num=request.getParameter("num");
///////////////////////////////////////////////
String author=data.getAuthor();
String title=data.getTitle();
String content=data.getContent();
dao.update(num,author, title, content);//dao.update(date);
return new ModelAndView("redirect:/list.do");
}
}
글삭제하기
board-servlet.xml에 내용추가
~생략~
<!--6)글삭제하기 -->
<bean name="/delete.do" class="lee.DeleteActionController">
<property name="dao">
<ref bean="boardDAO" />
</property>
</bean>
boardDAO 내용추가
~생략~
//delete from springboard where num=3
public void delete( String num){ //글삭제하기
try {
String sql="delete from springboard where num="+num;//?와 ? 쓰지않은것의 차이
Connection con=ds.getConnection();
PreparedStatement pstmt=con.prepareStatement(sql);
int delete=pstmt.executeUpdate(sql);
System.out.println("sql=>"+sql);
System.out.println("delete삭제유무(delete)=>"+delete);//1 성공, 0 실패
pstmt.close(); con.close();
}catch(Exception e) {e.printStackTrace();}
}//end delete
DeleteActionController(컨트롤러) 생성
package lee;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
//public class ListAction implements CommandAction{ 페이지이동,클래스는 틀리지만 처리메서드 동일
public class DeleteActionController implements Controller {
BoardDAO dao;//BoardDAO dao=new BoardDAO(); 스프링컨테이너가 해준다.
public void setDao(BoardDAO dao) {//<property name="dao"><ref bean~
this.dao = dao;
System.out.println("setDao() 호출됨(dao)=>"+dao);
}
@Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
System.out.println("DeleteActionController의 handleRequest()호출됨");
// /delete.do?num=3
String num=request.getParameter("num");
dao.delete(num);
//화면에 출력할 list.jsp에 전달할 페이지명과 전달할값을 설정하기위해
ModelAndView mav=new ModelAndView();//viewName 멤버변수
mav.setViewName("redirect:/list.do");//삭제->ListActionController->/list.jsp
return mav;
}
}
list.jsp 밑에 내용추가
~생략~
<!-- 검색 기능 시작 -->
<tr><td colspan="5" align="center">
<form action="search.do">
<select name="searchName" size="1">
<option value="author">작성자</option>
<option value="title">제목</option>
</select>
<input type="text" name="searchValue"><input type="submit" value="검색">
</form>
</td>
</tr>
board-servlet.xml에 내용추가
~생략~
<!-- 7)글검색하기(list.do와 동일) -->
<bean name="/search.do" class="lee.SearchActionController">
<property name="dao">
<ref bean="boardDAO" />
</property>
</bean>
boardDAO 내용추가
~생략~
// 검색분야 검색어
public ArrayList search( String name , String value ){ //글검색하기
ArrayList list = new ArrayList();//List list=new ArrayList();
try{
String sql = "SELECT * FROM springboard";
sql += " WHERE " + name + " LIKE '%" + value + "%' ";
System.out.println( sql );
Connection con = ds.getConnection();
PreparedStatement stmt = con.prepareStatement(sql);
ResultSet rs = stmt.executeQuery( sql );
while( rs.next()){
Board data = new Board();
data.setNum(rs.getInt( "num" ));
data.setAuthor(rs.getString( "author" ));
data.setTitle(rs.getString( "title"));
data.setContent(rs.getString( "content" ));
data.setDate(rs.getString( "writeday" ));
data.setReadcnt(rs.getInt( "readcnt" ));
list.add( data );
}
rs.close(); stmt.close(); con.close();
}catch( Exception e){ e.printStackTrace();}
return list;
}
SearchActionController생성
package lee;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
//public class ListAction implements CommandAction{ 페이지이동,클래스는 틀리지만 처리메서드 동일
public class SearchActionController implements Controller {
BoardDAO dao;//BoardDAO dao=new BoardDAO(); 스프링컨테이너가 해준다.
public void setDao(BoardDAO dao) {//<property name="dao"><ref bean~
this.dao = dao;
System.out.println("setDao() 호출됨(dao)=>"+dao);
}
@Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
System.out.println("SearchActionController의 handleRequest()호출됨");
//추가(검색분야,검색어에 해당하는 레코드만 보여줄 수 있도록)
String searchName=request.getParameter("searchName");//검색분야
String searchValue=request.getParameter("searchValue");//검색어
//----------------------------
ArrayList list=dao.search(searchName,searchValue);
//-----------------------------
//화면에 출력할 list.jsp에 전달할 페이지명과 전달할값을 설정하기위해
ModelAndView mav=new ModelAndView();//viewName 멤버변수
mav.setViewName("list");//이동할 페이지명만 확인->경로? 확장자?
mav.addObject("list",list);//request.setAttribute("list",list);
//mav.addObject("키명",전달할값),,,,
//${list(키명)} request.getAttribute("list");
return mav;
}
}
<%
response.sendRedirect("http://localhost:8090/SpringBoard/list.do");
%>
2022-08-25