티스토리 뷰
ControllerAction.java
//get방식의 서비스 메소드
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
requestPro(request, response);
}
//post방식의 서비스 메소드
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
requestPro(request, response);
}
//시용자의 요청을 분석해서 해당 작업을 처리
private void requestPro(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//요청
System.out.println("test : " + request.getRequestURI());
String category = request.getServletPath().substring(1);
System.out.println("category = " + category);
CommandAction command = (CommandAction) map.get(category);
System.out.println("command = " + command);
String view=null;
try {
view = command.requestPro(request, response);
} catch (Throwable e) {
e.printStackTrace();
}
//응답 해당하는 디스패처를 포워딩시켜주는 작업을 한다.
RequestDispatcher dispatcher = request.getRequestDispatcher(view);//상대번지
dispatcher.forward(request, response);
}
}
내부서버 오류에 500 뜨면서 sql 구문 확인하라고 할 때는 테이블에 컬럼을 먼저 확인하자 / drop 테이블 안하고 했더니 java.lang.ClassNotFoundException계속 뜸 재ㅔ발 장서정 정신차려
** 2번째 오류
SqlSessionFactory는 resource를 "mybatis/mybatis-config.xml" 으로 해줘야하고
boardInsert(BoardDTO dto)의 경우는 n에 담길 세션을 ""mybatis.BoardMapper.boardInsert", dto" 으로 해줘야 함
전체 구성과 코드
1. 로그인 완성하기
web 먼저
index.jsp (싱딘 메뉴바 포함시킴)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="menu.jsp" %>
<p>여기에 오신걸 환영합니다</p>
</body>
</html>
menu.jsp
<%@page import="com.login.dto.LoginDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
p{ color:green;font-weight: bold; font-size: 30px;}
body { margin: 0; padding: 0; }
#menu { height: 100px; background-color: #eee; }
a { display:inline-block; margin-top:40px; text-decoration: none; font: bold; width: 100px; text-align: center; }
#login_info { font-size: 12px; }
</style>
</head>
<body>
<div id="menu">
<a href="/bbs/index.jsp">처음화면</a>
<%
LoginDTO entity = (LoginDTO)session.getAttribute("logOK");
if(entity == null)
{
%>
<a href="/bbs/login/login.jsp" >로그인화면</a>
<%
}else{
%>
<a href="/bbs/board/boardWrite.jsp">글쓰기</a>
<a href="/bbs/boardList.do?pg=1" >글읽기</a>
<a href="/bbs/logout.do" >로그아웃</a>
<span id="login_info"><b><%=entity.getName()%></b>님이 로그인 하셨습니다
현재 소유하신 포인터는 <b><%=entity.getPoint()%></b>점 입니다</span>
<%
}
%>
</div>
<hr>
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>step13_boardProject</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>
</web-app>
table_schema에서 DB 생성
select * from tab;
select * from users;
drop table users purge;
--primary key : unique + not null
create table users(
id varchar2(10) primary key,
pwd varchar2(10) not null,
name varchar2(20) not null,
point number(7,2));
insert into users(id,pwd,name,point) values('admin','1111','어드민',35.34);
insert into users(id,pwd,name,point) values('abcd','1111','테스트',65.78);
commit
select * from users;
com.login.dto
LoginDTO.java
package com.login.dto;
//기본생성자, 인자4개받는 생성자, setter & getter
public class LoginDTO {
private String id;
private String pwd;
private String name;
private double point;
public LoginDTO() {
super();
}
public LoginDTO(String id, String pwd, String name, double point) {
super();
this.id = id;
this.pwd = pwd;
this.name = name;
this.point = point;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPoint() {
return point;
}
public void setPoint(double point) {
this.point = point;
}
}
데이터 흐름 완성하기
[ JSP ] Day 14 - ② MVC 2 패턴으로 개발하기
# Project Structure 더보기 MVC 스타일의 이해를 돕기 위한 프로젝트구조이다. 자바 소스에는 Controller와 Model을 구현하는 control, dao, service 패키지가 있고, WebContent 아래에는 View를 구현하는 jsp..
dadmi97.tistory.com
# 개발 순서
|
mybatis Framework (마이바티스 개념, ibatis와 차이, 구조, api, SqlSession)
1. 마이바티스란? 객체지향 언어인 자바의 관계형 데이터 베이스 프로그래밍을 좀더 쉽게 할수 있게 도와주는 개발 프레임워크이다. 자바는 jdbc api 를 제공해주지만, 이런 JDBC를 이용하면 1개 클
sjh836.tistory.com
LoginDAO.java
package com.login.dao;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.login.dto.LoginDTO;
public class LoginDAO {
private static SqlSessionFactory factory;
static {
try {
String resource="mybatis/mybatis-config.xml";
Reader reader=Resources.getResourceAsReader(resource);
factory=new SqlSessionFactoryBuilder().build(reader);
}catch(IOException e) {}
}
//----------------------------------------------------------------------
public LoginDTO getLoginUser(String id, String pwd) {
SqlSession session=factory.openSession();
LoginDTO dto=new LoginDTO(id,pwd,"",0);
LoginDTO entity=session.selectOne("mybatis.LoginMapper.getLoginUser", dto);
session.close();
return entity;
}
}
- DBCP를 이용한 DB 연결 수행파트가 SqlSessionFactory factory다. (마이바티스 활용)
:SqlSessionFactory 클래스 : SqlSession 객체에 대한 팩토리 객체다. 이 객체의 openSession() 이라는 메소드를 통해 SqlSession 객체를 얻을 수 있다.
: mybatis 패키지? 폴더?를 열면 이렇다
BoardMapper.xml : 쿼리문으로 DB를 처리한다.
** 이때 중요한 건 중괄호 안에도 대문자로 쓰면 안됨!**
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mybatis.BoardMapper">
<insert id="boardInsert" parameterType="BoardDTO">
<![CDATA[
INSERT INTO BOARD
VALUES(SEQ_BOARD.NEXTVAL,#{id},#{name},#{email},#{subject},#{content},
SEQ_BOARD.CURRVAL,0,0,0,0,0,SYSDATE)
]]>
</insert>
</mapper>
LoginMapper.xml : 같다.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mybatis.LoginMapper">
<select id="getLoginUser" parameterType="LoginDTO" resultType="LoginDTO">
<![CDATA[
SELECT *
FROM USERS WHERE ID=#{id} AND PWD=#{pwd}
]]>
</select>
</mapper>
config.properties : sqlplus 계정과 아이디 / 오라클 DB에 접근할 수 있도록 함.
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:XE
username=edu
password=1234
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="mybatis/config.propertis"/>
<typeAliases>
<typeAlias type="com.login.dto.LoginDTO" alias="LoginDTO"/>
<typeAlias type="com.board.dto.BoardDTO" alias="BoardDTO"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mybatis/LoginMapper.xml"/>
<mapper resource="mybatis/BoardMapper.xml"/>
</mappers>
</configuration>
[MyBatis] MySQL 연결하기 - 1. Config XML 설정파일
우선 내가 사용하는 DB는 MySQL, MsSQL 2가지인데 우선 MySQL로 연결하는 것을 해보겠다. DB가 달라지더라도 바뀌는 것은 JDBC 파일과 커넥션 정보 뿐이니 MyBatis 의 본질만 잘알고 있다면 어느 DB라도 연
emflant.tistory.com
: 마이 바티스 패키지 만드는 법이 나와있다.
service 패키지에서 명령처리를 위한 인터페이스 생성
/com.login.service
LoginService.java
package com.login.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.ServiceMode;
import com.login.dao.LoginDAO;
import com.login.dto.LoginDTO;
import controller.CommandAction;
public class LoginService implements CommandAction{
@Override
public String requestPro(HttpServletRequest request, HttpServletResponse response) throws Throwable {
String id=request.getParameter("id");
String pwd=request.getParameter("pwd");
// System.out.println(id+" "+pwd);
LoginDAO dao=new LoginDAO();
LoginDTO entity=dao.getLoginUser(id,pwd);
if(entity != null) {
//세션설정
HttpSession session=request.getSession();
session.setAttribute("logOK", entity);
return "login/loginOK.jsp";
}else {
return "login/loginFail.jsp";
}
}
}
LogoutService.java
package com.login.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.login.dto.LoginDTO;
import controller.CommandAction;
public class LogoutService implements CommandAction{
@Override
public String requestPro(HttpServletRequest request, HttpServletResponse response) throws Throwable {
HttpSession session=request.getSession();
LoginDTO entity=(LoginDTO)session.getAttribute("logOK");
if(entity != null)
{
session.removeAttribute("logOK"); //or session.invalidate();
return "index.jsp";
}
return null;
}
}
service의 Action 클래스 정의하기.
: CommandProcess 상속 -> requestPro 메소드 오버라이딩
: requestPro 메소드에서 request 속성 설정
CommandAction: requestPro
package controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface CommandAction {
public String requestPro(HttpServletRequest request,
HttpServletResponse response) throws Throwable;
}
ControllerAction.java :get, post모두 requestPro로 받도록 throw 해준다. (urlPattern에 *.do)
package controller;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="ControllerAction", urlPatterns={"*.do"})
public class ControllerAction extends HttpServlet{
Map map = new HashMap();
public void init(ServletConfig config) throws ServletException {
String props = config.getServletContext().getRealPath(
"/WEB-INF/commandPro.properties");
FileInputStream fin=null;
Properties properties = new Properties();
try {
fin = new FileInputStream(props);
properties.load(fin);
System.out.println("properties="+properties);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Iterator it = properties.keySet().iterator();
while(it.hasNext()){
String key = (String)it.next();
// System.out.println("key="+key);
String className = properties.getProperty(key);
// System.out.println("className="+className);
try {
Class classType = Class.forName(className);
Object ob = classType.newInstance();
map.put(key, ob);//맵에 저장
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}//while
}//init()
//get방식의 서비스 메소드
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
requestPro(request, response);
}
//post방식의 서비스 메소드
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
requestPro(request, response);
}
//시용자의 요청을 분석해서 해당 작업을 처리
private void requestPro(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//요청
// System.out.println("test : " + request.getRequestURI());
String category = request.getServletPath().substring(1);
// System.out.println("category = " + category);
CommandAction command = (CommandAction) map.get(category);
// System.out.println("command = " + command);
String view=null;
try {
view = command.requestPro(request, response);
} catch (Throwable e) {
e.printStackTrace();
}
//응답
RequestDispatcher dispatcher = request.getRequestDispatcher(view);//상대번지
dispatcher.forward(request, response);
}
}
WebContent에 jsp 파일(view) 생성하여 기술.
: 이때, Action 클래스에서 request나 session을 통해 받은 속성을 이용하여 기술한다.
: index.jsp에 메인화면에 등록할 페이지로 이동시키는 코드를 작성한다.
- <script>location.href="list.do"</script>
- 하지만 우리는 list.do로 list.jsp로 이동할 수 없으니, 반드시 web.xml의 설정파일에 기술해줘야한다.
/web
/login
login.jsp (form action에 login.do)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../menu.jsp" %>
<form action="/bbs/login.do" method="post">
<table border="0" align="center" width="350">
<tr>
<td>아이디</td>
<td><input type="text" name="id"></td>
</tr>
<tr>
<td>비밀번호</td>
<td><input type="password" name="pwd"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="로그인">
<input type="reset" value="취 소">
</td>
</tr>
</table>
</form>
</body>
</html>
loginFail.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="../menu.jsp" %>
로그인 실패
</body>
</html>
loginOK.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="../menu.jsp" %>
로그인 성공
</body>
</html>
Web.xml 파일 설정
: web.xml 파일은 Tomcat의 실행환경에 대한 정보를 담당하는 환경설정 파일로, 각종 servlet의 설정과 servlet 매핑, 필터, 인코딩 등을 담당한다.
: web.xml 파일에 서블릿 파일인 Controller와 위치를 등록하고, config파일과 위치를 등록한다. 또한 servlet 파일이 실행될 url 확장자과 Controller를 매핑하는 코드를 작성해준다.
-- 게시글 데이터흐름 작성 필요 --
'JAVA' 카테고리의 다른 글
13_이어서 (0) | 2020.11.26 |
---|---|
13_이어서 (0) | 2020.11.24 |
웹크롤링/ 이미지보드 프로젝트 (0) | 2020.11.20 |
DB파일올리기2_JSP (0) | 2020.11.20 |
DB에 파일올리기_JSP (0) | 2020.11.20 |