Validata를 상속 받아야 함
Student.java
package com.oracle.mvc05.dto;
public class Student {
private String name;
private String strId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStrId() {
return strId;
}
public void setStrId(String strId) {
this.strId = strId;
}
}
StudentValidator.java
package com.oracle.mvc05;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.oracle.mvc05.dto.Student;
public class StudentValidator implements Validator {
//검증할 객체의 클래스 타입 정보
@Override
public boolean supports(Class<?> student) {
// TODO Auto-generated method stub
return Student.class.isAssignableFrom(student); //
}
//Validate 함수 -검증
@Override //위에 정보를 읽어서 target으로 들어옴
public void validate(Object target, Errors errors) { //에러메세지 띠울수 있음
System.out.println("StudentValidator() start . . . ");
Student student = (Student) target;
String studentName = student.getName();
if(studentName == null || studentName.trim().isEmpty()) {
System.out.println("studentName is null or empty");
System.out.println("validate--> 회원 이름을 입력하세요. . . ");
errors.rejectValue("name", "회원이름 공백 또는 NULL 오류"); //에러가난이유를 출력해줌
}
String studentId = student.getStrId();
if(studentId == null || studentId.trim().isEmpty()) {
System.out.println("studentId is null or empty");
System.out.println("validate--> StrId을 입력하세요. . . ");
errors.rejectValue("StrId", "StrId 공백 또는 NULL 오류"); //에러가난이유를 출력해줌
}
}
}
StudentController.java
package com.oracle.mvc05;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class StudentController {
private static final Logger logger = LoggerFactory.getLogger(StudentController.class);
@RequestMapping("/studentForm")
public String studentForm() {
logger.info("studentForm start. . . ");
return "studentForm";
}
}
StudentController.java
@RequestMapping("/student/create") //errors를 BindingResult 객체를 통해서 result로 검증한다
public String studentCreate(Student student, BindingResult result, Model modle) {
String page = "studentDonePage";
logger.info("/student/create start. . . ");
StudentValidator validator = new StudentValidator();
validator.validate(student, result);//errors->result
System.out.println("result Message getFieldError->"+result.getFieldErrors("name"));
String name = "";
String id = "";
if(result.hasErrors()) {
if(result.hasFieldErrors("name")) {
System.out.println("result.hasErrors1->"+result.getFieldError("name"));
FieldError fieldError1 = result.getFieldError("name");
name = fieldError1.getCode();
modle.addAttribute("nameErr", name);
}
if(result.hasFieldErrors("strId")) {
System.out.println("result.hasErrors2->"+result.getFieldError("strId"));
FieldError fieldError2 = result.getFieldError("strId");
name = fieldError2.getCode();
modle.addAttribute("idErr", id);
}
page= "studentForm";
}else {
modle.addAttribute("student3", student);
}
System.out.println("result Message->End");
logger.info("result page-->{}" ,page);
logger.info("result name-->{}" , name);
return page;
}
}
StudentForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String context = request.getContextPath();
%>
context:<%=context%><p></p>
<c:if test = "${nameErr !=' ' }">
${nameErr }
</c:if>
<c:if test = "${idErr !=' ' }">
${idErr }
</c:if>
<form action="<%=context%>/student/create">
이름: <input type="text" name="name"> <br />
아이디: <input type="text" name="strId"> <br />
<input type="submit" value="전송"> <br />
</form>
</body>
</html>
studentDonePage.jsp
<body>
<h1>student 정상검증</h1>
이름: ${student.name }
ID: ${student.strId }
</body>
🔽정상입력했을때
🔽입력오류일때
.m2 폴더 - 라이브러리 모아두는 곳
spring 끈상태에서 삭제하고
정상 m2파일을 받아와서
파일이름 .m2로 바꿔서다시 붙여넣기 해주기
pacakage 4개 생성
controller
service (=command)
dao
dto
sql에서 MVC_BOARD 테이블 생성하고 데이터 넣기
commit 꼭해주기 💫💫
css파일 따로 넣어두기
sql보고 작성하기
package com.oracle.oMVCBoard.dto;
import java.sql.Timestamp;
public class BDto {
int bId;
String bName;
String bTitle;
String bContent;
Timestamp bDate;
int bHit;
int bGroup;
int bStep;
int bIndent;
public BDto() {
}
//생성자 생성
public BDto(int bId, String bName ,String bTitle, String bContent, Timestamp bDate, int bHit
, int bGroup, int bStep , int bIndent ) {
this.bId = bId;
this.bName = bName;
this.bTitle = bTitle;
this.bContent = bContent;
this.bDate = bDate;
this.bHit = bHit;
this.bGroup = bGroup;
this.bStep = bStep;
this.bIndent = bIndent;
}
public int getbId() {
return bId;
}
public void setbId(int bId) {
this.bId = bId;
}
public String getbName() {
return bName;
}
public void setbName(String bName) {
this.bName = bName;
}
public String getbTitle() {
return bTitle;
}
public void setbTitle(String bTitle) {
this.bTitle = bTitle;
}
public String getbContent() {
return bContent;
}
public void setbContent(String bContent) {
this.bContent = bContent;
}
public Timestamp getbDate() {
return bDate;
}
public void setbDate(Timestamp bDate) {
this.bDate = bDate;
}
public int getbHit() {
return bHit;
}
public void setbHit(int bHit) {
this.bHit = bHit;
}
public int getbGroup() {
return bGroup;
}
public void setbGroup(int bGroup) {
this.bGroup = bGroup;
}
public int getbStep() {
return bStep;
}
public void setbStep(int bStep) {
this.bStep = bStep;
}
public int getbIndent() {
return bIndent;
}
public void setbIndent(int bIndent) {
this.bIndent = bIndent;
}
}
환경작업하기
BDao.java
package com.oracle.oMVCBoard.dao;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class BDao {
DataSource dataSource;
//생성자
public BDao() {
try {
Context context = new InitialContext();
dataSource = (DataSource) context.lookup("java:comp/env/jdbc/OracleDB");
} catch (NamingException e) {
System.out.println("생성자 dataSource-->"+e.getMessage() );
e.printStackTrace();
}
}
}
servers에 context.xml에
연결해주는 리소스 붙여넣기
<Resource
name="jdbc/OracleDB"
auth="Container"
type="javax.sql.DataSource"
username="scott"
password ="tiger"
driverClassName="oracle.jdbc.driver.OracleDriver"
factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"
url="jdbc:oracle:thin:@127.0.0.1:1521:xe"
maxActive="50"
maxIdle="10"
/>
package com.oracle.oMVCBoard.command;
import org.springframework.ui.Model;
public interface BCommand {
void execute(Model model);
}
package com.oracle.oMVCBoard;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.oracle.oMVCBoard.command.BCommand;
@Controller
public class BController { //홈컨트롤러에서 가지고 와서 이름만 바꿔주기
private static final Logger logger = LoggerFactory.getLogger(BController.class);
BCommand command = null;
@RequestMapping("list")
public String list(Model model) {
logger.info("list start. . . ");
return "list";
}
}
뷰- 화면에 보이는 페이지
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시판 </title>
</head>
<body>
<h1>게시판 </h1>
</body>
</html>
🧡 한 바퀴 연결완료
listcommand
writecommand
updatecommand 다 작성할수 있음
service 연결시키기
BDao랑 연결시켜줘야함
package com.oracle.oMVCBoard.command;
import java.util.ArrayList;
import org.springframework.ui.Model;
import com.oracle.oMVCBoard.dao.BDao;
import com.oracle.oMVCBoard.dto.BDto;
//Service
public class BListCommand implements BCommand {
@Override
public void execute(Model model) {
//Dao 랑 연결시킴
BDao dao = new BDao();
ArrayList<BDto> boardDtoList = dao.boardList(); //boardList 를 만들어야함 Dao에 자동 껍데기 생성됨
System.out.println("BListCommand boardDtoList.size()- - >" +boardDtoList.size()); //정상 실행되었을때 size 9개 나옴
model.addAttribute("boardList", boardDtoList);
}
}
BDao.java 에서 dao.boardList 만들기
public ArrayList<BDto> boardList() {
ArrayList<BDto> bList = new ArrayList<BDto>();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
System.out.println("BDao boardList start...");
try {
conn = dataSource.getConnection();
String sql = "SELECT bId, bName, bTitle, bContent, bDate, bHit,bGroup, bStep, bIndent FROM mvc_board order by bGroup desc, bStep asc";
pstmt = conn.prepareStatement(sql);
System.out.println("boardList sql->"+sql);
rs = pstmt.executeQuery();
while(rs.next()) { //1 dto에서 다불러와서
int bId = rs.getInt("bId");
String bName = rs.getString("bName");
String bTitle = rs.getString("bTitle");
String bContent = rs.getString("bContent");
Timestamp bDate = rs.getTimestamp("bDate");
int bHit = rs.getInt("bHit");
int bGroup = rs.getInt("bGroup");
int bStep = rs.getInt("bStep");
int bIndent = rs.getInt("bIndent");
//2 BDto에 다 담아서
BDto dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent);
bList.add(dto); // bList 에 담아서 옮기기
}
//3예외처리해주고
} catch (Exception e) {
System.out.println("list dataSource-->"+e.getMessage());
//4닫아주고
} finally {
try {
if( rs != null) rs.close();
if( pstmt!= null ) pstmt.close();
if( conn != null ) conn.close();
} catch (Exception e2) {
System.out.println(e2.getMessage());
}
} //5리턴 bList 해주기
return bList;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시판</title>
*****css 걸어주기 *******
<%
String context = request.getContextPath();
%>
<link rel="stylesheet" href="<%=context %>/resources/css/board.css" type="text/css" >
****************************
</head>
<body>
<h1>게시판</h1>
<table>
<tr>
<td>번호</td>
<td>이름</td>
<td>제목</td>
<td>날짜</td>
<td>히트</td>
</tr>
<c:forEach items="${boardList }" var="mvc_board">
<tr>
<td>${mvc_board.bId }</td>
<td>${mvc_board.bName }</td>
<td>
<c:forEach begin="1" end="${mvc_board.bIndent }">-</c:forEach>
<a href= "content_view?bId="${mvc_board.bId}">${mvc_board.bTitle}</a>
</td>
<td>${mvc_board.bDate}</td>
<td>${mvc_board.bHit }</td>
</tr>
</c:forEach>
<tr>
<td colspan="5"> <a href="write_view">글작성</a></td>
</tr>
</table>
</body>
</html>