Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- React
- 코드프로그래머스
- 라도무스dvd
- vscode
- JSON
- Config
- minimalAPI
- 명시적외래키
- 에스가든스냅
- mac
- 상속
- Request
- 스냅잘찍음
- intellij
- extjs
- c#코딩의기술실전편
- JavaScript
- EFCore
- 대전본식영상
- Store
- c#
- error
- extraParams
- lazy loading
- ORM
- dbContext
- ViewModel
- scanner
- .net
- LINQ
Archives
- Today
- Total
ejyoo's 개발 노트
MVC 패턴 본문
💡 pom.xml(oracle, jstl 라이브러리폼)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>model2</groupId> <artifactId>model2</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.3</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> </configuration> </plugin> </plugins> </build> <!-- https://mvnrepository.com/artifact/com.oracle/ojdbc6 --> <dependencies> <!-- https://mvnrepository.com/artifact/com.oracle.ojdbc/ojdbc8 --> <dependency> <groupId>com.oracle.ojdbc</groupId> <artifactId>ojdbc8</artifactId> <version>19.3.0.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-pool/commons-pool --> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.6</version> </dependency> <!-- 외부 라이브러리 추가 --> <!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> </project>
💡 content.xml
<?xml version="1.0" encoding="UTF-8"?> <context> <Resource name="jdbc/java" auth="container" type="javax.sql.DataSource" username="ejyoo" password="java" driverClassName="oracle.jdbc.driver.OracleDriver" factory="org.apache.commons.dbcp.BasicDataSourceFactory" url="jdbc:oracle:thin:@localhost:1521:xe" maxActive="100" maxIdle="10" /> </context>
💡 web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>model2</display-name> <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> <resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/java</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> </web-app>
💡 Board DTO
package model1; import java.util.Date; public class Board { int bno;// number, String title;// varchar2(200) not null, String content;// varchar2(255), String writer;// varchar2(50) not null, String regdate;// date default sysdate not null, int viewcnt;// number default 0, int replycnt;// number default 0 public int getBno () { return bno; } public void setBno (int bno) { this.bno = bno; } 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 getWriter () { return writer; } public void setWriter (String writer) { this.writer = writer; } public String getRegdate () { return regdate; } public void setRegdate (String regdate) { this.regdate = regdate; } public int getViewcnt () { return viewcnt; } public void setViewcnt (int viewcnt) { this.viewcnt = viewcnt; } public int getReplycnt () { return replycnt; } public void setReplycnt (int replycnt) { this.replycnt = replycnt; } }
💡 User DTO
package model1; public class User { int idx;// number, String uid;// userid varchar2(50) not null, String upw;// userpw varchar2(50) not null, public int getIdx () { return idx; } public void setIdx (int idx) { this.idx = idx; } public String getUid () { return uid; } public void setUid (String uid) { this.uid = uid; } public String getUpw () { return upw; } public void setUpw (String upw) { this.upw = upw; } public String getRegdate () { return regdate; } public void setRegdate (String regdate) { this.regdate = regdate; } String regdate;// date default sysdate }
💡 login.jsp(View)
<%@ 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> <fieldset> <form action="/model2/loginProc"> <input type="text" name="uid"> <input type="password" name="upw"> <input type="submit" value="로그인"> </form> </fieldset> </body> </html>
💡 loginProc Servlet(Controller,Model)
package com.s; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.naming.Context; import javax.naming.InitialContext; import javax.servlet.RequestDispatcher; 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.sql.DataSource; import model1.User; //Controller @WebServlet(name = "loginProc", description = "로그인 처리", urlPatterns = { "/loginProc" }) public class LoginProc extends HttpServlet { private static final long serialVersionUID = 1L; Connection conn; public LoginProc() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // response.getWriter().append("Served at: ").append(request.getContextPath()); try { Context initCtx = new InitialContext(); Context envCtx = (Context)initCtx.lookup ("java:comp/env"); DataSource ds = (DataSource)envCtx.lookup("jdbc/java"); conn = ds.getConnection (); System.out.println ("커넥션 풀로부터 커넥션 객체 획득"); //쿼리 수행 String uid = request.getParameter ("uid");//"guest" String upw = request.getParameter ("upw");//"1234" // String sql = "select * from tbl_user where userid='" + uid + "' and userpw='" + upw + "'"; String sql = "select * from tbl_user where userid=? and userpw=?"; PreparedStatement ps = conn.prepareStatement (sql); ps.setString(1, uid); ps.setString (2, upw); ResultSet rs = ps.executeQuery (); // model User userBean = null; if(rs.next()) { userBean = new User (); userBean.setIdx (rs.getInt ("idx")); userBean.setUid (rs.getString ("userid")); userBean.setUpw (rs.getString ("userpw")); userBean.setRegdate (rs.getString ("regdate")); } //반납 rs.close (); ps.close (); // stmt.close (); conn.close (); System.out.println ("커넥션풀로부터 커넥션 객체 반납"); //디스페쳐로 전달 if(userBean == null) { RequestDispatcher rd = request.getRequestDispatcher ("loginError.jsp"); rd.forward (request, response); }else { request.setAttribute ("user", userBean); // 게시물을 읽기위한 서블릿 생성 RequestDispatcher rd = request.getRequestDispatcher ("/bbsProc"); rd.forward (request, response); } } catch (Exception e) { System.out.println ("커넥션 객체 획득 오류" + e.getMessage ()); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
💡 BbsProc Servlet(Controller,Model)
package com.s; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.naming.Context; import javax.naming.InitialContext; import javax.servlet.RequestDispatcher; 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.sql.DataSource; import model1.Board; @WebServlet(name = "bbsProc", description = "게시물 데이터를 가져오는 서블릿", urlPatterns = { "/bbsProc" }) public class BbsProc extends HttpServlet { private static final long serialVersionUID = 1L; Connection conn; public BbsProc() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // response.getWriter().append("Served at: ").append(request.getContextPath()); // 게시물을 읽어와서 전달만!(페이징 해야하지만 전체를 읽어와서 결과만!) try { Context initCtx = new InitialContext(); Context envCtx = (Context)initCtx.lookup ("java:comp/env"); DataSource ds = (DataSource)envCtx.lookup("jdbc/java"); conn = ds.getConnection (); System.out.println ("커넥션 풀로부터 커넥션 객체 획득"); // 쿼리 수행 String sql = "select * from tbl_board"; PreparedStatement ps = conn.prepareStatement (sql); ResultSet rs = ps.executeQuery (); // model // 여러줄의 게시글을 갖고오기 위한 ArrayList 생성 ArrayList<Board> boards = new ArrayList<Board>(); Board boardBean = null; while(rs.next()) { boardBean = new Board(); boardBean.setBno ( rs.getInt ("bno") ); boardBean.setTitle ( rs.getString("title") ); boardBean.setContent ( rs.getString ("content") ); boardBean.setWriter ( rs.getString ("writer") ); boardBean.setRegdate ( rs.getString ("regdate") ); boards.add (boardBean); } rs.close (); ps.close (); conn.close (); System.out.println ("커넥션풀로부터 커넥션 객체 반납"); //디스페쳐로 전달 if(boardBean == null) { RequestDispatcher rd = request.getRequestDispatcher ("loginError.jsp"); rd.forward (request, response); }else { request.setAttribute ("bbs", boards); // 게시물을 읽기위한 서블릿 생성 RequestDispatcher rd = request.getRequestDispatcher ("bbs2.jsp"); rd.forward (request, response); } } catch (Exception e) { System.out.println ("커넥션 객체 획득 오류 " + e.getMessage ()); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
💡 bbs2.jsp(View)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!-- jstl 세팅 --> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!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> ${ user.uid }님 반갑습니다.<br> <!-- 게시물 내용 --> <table border="1"> <thead> <tr> <td>글번호</td> <td>작성자</td> <td>제목</td> <td>내용</td> <td>등록일</td> </tr> </thead> <tbody> <c:forEach var="board" items="${ bbs }"> <tr> <td>${ board.bno }</td> <td>${ board.title }</td> <td>${ board.content }</td> <td>${ board.writer }</td> <td>${ board.regdate }</td> </tr> </c:forEach> </tbody> </table> </body> </html>
'BackEnd > Java' 카테고리의 다른 글
JDK 버전 별 컴파일러 지원기능 정리 (0) | 2021.03.05 |
---|---|
Set & TreeSet (0) | 2021.03.05 |
Java equals(), HashCode() (2) | 2021.03.04 |
Maven - Oracle 설정 (pom.xml) (0) | 2021.03.04 |
Comparable, Comparator 차이 (0) | 2021.03.04 |