서블릿 생성
- 톰캣4.0v
: 클래스 상단부분에 자동생성됨
@WebServlet(name = "서블릿이름",urlPatterns = {"/서블릿path"})
@WebServlet(name = "emplist",urlPatterns = {"/emp/list.do"})
- 톰캣5.0v
web.xml파일 생성되고 여기에 자동추가됨
<servlet>
<description></description>
<display-name>basic</display-name>
<servlet-name>basic</servlet-name>
<servlet-class>basic.basic</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>basic</servlet-name>
<url-pattern>/basic.do</url-pattern>
</servlet-mapping>
메소드 분리하기
package basic;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "calc2",urlPatterns = {"/calc2.do"})
public class CalcServlet2 extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
res.setContentType("text/html;charset=UTF-8");
PrintWriter pw = res.getWriter();
// 클라이언트의 요청 정보 추출
int num1 = Integer.valueOf(req.getParameter("num1"));
String method = req.getParameter("method");
int num2 = Integer.valueOf(req.getParameter("num2"));
switch (method) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
}
pw.print("<h1>계산결과</h1>");
pw.print("<hr/");
pw.println("<h3>num1의 "+num1+"과 num2의 "+num2+"을(를) 연산한 결과는"+result+"입니다.</h3>");
=========메소드 분리========>
public class Calc {
public int clac(int num1, int num2, String method) {
System.out.println("비지니스메소드 호출 성공~~"); //연결됐는지 확인하기
int result = 0;
switch (method) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
}
return result;
}
}
=> 매개변수를 만들어 결과 리턴하기
int num1 = Integer.valueOf(req.getParameter("num1"));
String method = req.getParameter("method");
int num2 = Integer.valueOf(req.getParameter("num2"));
// 비지니스메소드 call
Calc calc = new Calc();
int result = calc.clac(num1, num2, method);
//응답메세지생성
pw.print("<h1>계산결과</h1>");
pw.print("<hr/");
pw.println("<h3>num1의 "+num1+"과 num2의 "+num2+"을(를) 연산한 결과는"+result+"입니다.</h3>");
=> 리턴값의 타입과 같은 타입의 변수를 만들어 리턴값(result)받아주기
메소드 분리하기 + DB와 연결하기
1. 서블릿 작성하기
2. DTO작성하기(생성자, get,set메소드, toString메소드 생성)
3. DAO(메소드 클래스)작성하기
* 단계별로 sysout찍으면서 디버깅하기
① 사원등록하기(insert)
package kr.multicampus.erp.user;
import 생략
@WebServlet(name = "empinsert",urlPatterns = {"/emp/insert.do"})
public class EmpInsertServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
//요청과 응답에 한글을 셋팅
req.setCharacterEncoding("UTF-8");
res.setContentType("text/html;charset=UTF-8");
PrintWriter pw = res.getWriter();
System.out.println("서블릿요청성공");
int deptno = Integer.parseInt(req.getParameter("deptno")); //리퀘스트 안의 값을 꺼냄
String name = req.getParameter("name");
String id = req.getParameter("id");
String pass = req.getParameter("pass");
String addr = req.getParameter("addr");
int grade = Integer.parseInt(req.getParameter("grade"));
empDAO dao = new empDAO();
empDTO emp = new empDTO(deptno, name, id, pass, addr, deptno, grade);
System.out.println(emp); //emp.tiString()
int result = dao.insert(emp);
System.out.println(result);
if(result > 0) {
pw.println("<img src=/serverweb/images/yc05.jpg />");
pw.print("삽입성공!");
}else {
pw.print("삽입실패...");
}
}
}
package kr.multicampus.erp.user;
import생략
public class empDAO {
public int insert(empDTO emp) { //사원등록
System.out.println("비지니스메소드 호출 성공~~");
String sql = "insert into myemp values(?, ?, ?, ?, ?, 1000, ?)";
Connection con = null;
PreparedStatement ptmt = null;
int result = 0;
try {
con = DBUtil.getConnect();
ptmt = con.prepareStatement(sql);
System.out.println("Statement객체 생성 : "+ptmt);
ptmt.setInt(1, emp.getDeptno());
ptmt.setString(2, emp.getName());
ptmt.setString(3, emp.getId());
ptmt.setString(4, emp.getPass());
ptmt.setString(5, emp.getAddr());
ptmt.setInt(6, emp.getGrade());
result = ptmt.executeUpdate();
}catch(SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(null, ptmt, con);
}
return result;
}
}
② 전체사원조회하기(select)
package kr.multicampus.erp.user;
@WebServlet(name = "emplist",urlPatterns = {"/emp/list.do"})
public class EmpListServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
res.setContentType("text/html;charset=UTF-8");
PrintWriter pw = res.getWriter();
System.out.println("서블릿요청성공");
req.getParameterNames();
empDAO dao = new empDAO();
ArrayList<empDTO> allList = dao.select();
System.out.println(allList);
int size = allList.size();
for (int i = 0; i < size; i++) {
empDTO user = allList.get(i);
pw.print("부서번호 : " + user.getDeptno()+", ");
pw.print("이름 : " + user.getName()+", ");
pw.print("아이디 : " + user.getId()+", ");
pw.print("비밀번호 : " + user.getPass()+", ");
pw.print("주소 : " + user.getAddr()+", ");
pw.print("포인트 : " + user.getPoint()+", ");
pw.print("등급 : " + user.getGrade());
pw.print("<hr/>");
}
}
}
=> 전체내용 가져와야 하기 때문에 req.getParameterNames(); 사용하기
public ArrayList<empDTO> select() { //2.전체사원조회
//조회된 레코드를 CustomerDTO에 담아서 ArrayList에 저장하는 작업
String sql = "select * from myemp";
ArrayList<empDTO> userlist = new ArrayList<empDTO>();
empDTO user = null;
Connection con = null;
PreparedStatement ptmt = null;
ResultSet rs = null;
try {
con = DBUtil.getConnect();
ptmt = con.prepareStatement(sql);
rs = ptmt.executeQuery();
System.out.println("조회된 ResultSet객체 : "+rs);
while(rs.next()) {
System.out.print(rs.getString("id")+"\t");
user = new empDTO(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5),
rs.getInt(6), rs.getInt(7));
userlist.add(user);
}
System.out.println("리스트 사이즈 : "+userlist.size());
}catch(SQLException e) {
e.printStackTrace();
}finally{
DBUtil.close(rs, ptmt, con);
}
return userlist;
}
'MVC' 카테고리의 다른 글
MVC 패턴이란? (0) | 2022.11.27 |
---|---|
2022-11-17 MVC, 요청 재지정 (0) | 2022.11.17 |
2022-11-16 MVC, 요청 재지정 (0) | 2022.11.16 |
2022-11-15 서블릿 메소드 분리하기(delete), jsp문법 (0) | 2022.11.15 |
댓글