Index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
</head>
<style>
table,th,td{
border: 1px solid black;
border-collapse: collapse;
padding:5px 10px;
}
</style>
<body>
<form action="login" method="post">
<table>
<tr>
<th>ID</th>
<td><input type ="text" name="id"/></td>
</tr>
<th>PW</th>
<td><input type ="password" name="pw"/></td>
</tr>
<th colspan="2"><input type ="submit" value="login"/></th>
</tr>
</table>
</form>
</body>
<script>
var msg ='${msg}';
if(msg != ""){
alert(msg);
}
</script>
</html>
Login Controller
package kr.co.gudi.controller;
import java.io.IOException;
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.servlet.http.HttpSession;
import javax.websocket.Session;
@WebServlet ("/login")// login 요청만 받아올거
public class LoginCotroller extends HttpServlet {
@Override // dopost
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//post 방식으로 전송시 한글 깨짐 방지
req.setCharacterEncoding("UTF-8");
String id = req.getParameter("id"); // 이름과 String id를 같게 한다
String pw = req.getParameter("pw");
System.out.println(id+"/"+pw);//1. 무조건 찍어보기
//id 가 admin이고,pw 가 pass 일 경우 로그인을 시켜 준다
String page = "index.jsp"; //실패할 경우 돌려 보냄
String msg = "아이디 또는 비밀번호를 확인 하세요";
//id나 비밀번호의 앞에 공백을 넣는 실수를 방지하기 위해 trim()을 통해 공백을 제거한다 복붙을 했는데도 앞뒤 공백때문에 로그인 안될때가 있음
id = id.trim();
pw = pw.trim();
if(id.equals("admin")&&pw.equals("pass")){ //이거는 아이디하고 비번이 같을 경우에 나온다
msg =id +"님 , 반갑습니다.";
page = "main.jsp";
//session 은 jsp 에서는 내장객체였다.
//사실 session은 req 객체로 부터 나온다
HttpSession seesion = req.getSession();
seesion.setAttribute("loginID",id);
}
req.setAttribute("msg", msg);
RequestDispatcher dis = req.getRequestDispatcher(page);
dis.forward(req, resp);
}
}
Main jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
</head>
<body>
<h3>업로드 전 파일명 주의 사항</h3>
<ol>
<li>파일명은 20자가 넘으면 안됩니다.</li>
<li>파일명에 다음의 문자가 포함되면 안됩니다.(@,$,#,%,&)</li>
<li>파일명 앞에 [img]가 붙어야 합니다</li>
<li>허용되는 확장자는 .png .jpg .gif 입니다</li>
<li>.jpeg 확장자는 .jpg로 강제 변환 됩니다.</li>
</ol>
<form action="upload" method="post">
파일명 검사 : <input type="text" name="fileName" value="[image]test@image.jpeg"/>
<button>검사</button>
</form>
</body>
<script>
var msg = '${msg}';
if(msg != ""){
alert(msg);
}
</script>
</html>
UploadCtroller
package kr.co.gudi.controller;
import java.io.IOException;
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 kr.co.gudi.model.Stringutils;
@WebServlet("/upload")
public class UploadController extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");// do post를 쓰면한글이 깨지기 때문에 한글 깨짐 방지를 해줘야 한다
String fileName =req.getParameter("fileName");
System.out.println("fileName "+fileName); //1. 찍어서 나오는지 확인해보기
Stringutils utils = new Stringutils(); //생성자
String msg = utils.check(fileName);// filename을 튕겨서 보내줄거임
System.out.println("msg: "+msg);// 위에 msg 변수 만든이유는 찍어서 나오는지 확인해볼려고 한거다
req.setAttribute("msg", msg);
RequestDispatcher dis = req.getRequestDispatcher("main.jsp");
dis.forward(req, resp);
}
}
Model
package kr.co.gudi.model;
public class Stringutils {
public String check(String fileName) {
//ctrl +f로 변경 하고 싶은거 변경 하면됨
//파일명은 20자가 넘으면 안됩니다.(length,size 가 무조건 길이이다)
int len =fileName.length();
System.out.println("글자수 "+len);
if(len>20) {
//return은 해당 메서드를 탈출한다. 함수에서 탈출할때 사용
return"글자수가 20자를 넘었습니다."; // 여기에서 return은 걸리면 밑에를 보지도 않고 나가버린다
}
// 파일명에 다음의 문자가 포함되면 안됩니다.(@,$,#,%,&)
String[] arr = {"$","#","%","&","@"};
for (String str : arr) {
boolean contain = fileName.contains(str); //contains는 문자열 포함여부 확인을 위해 씀
System.out.println(str+":"+contain);
if(contain == true) {
return"@,$,#,%,& 가 포함되어 있으면 안됩니다.";
}
}
// 파일명 앞에 [img]가 붙어야 합니다 == 파일명이 [img] 로 시작되어야 한다.
if(fileName.startsWith("[img]") == false) {
return"파일명 앞에 [img]가 붙어야 합니다.";
}
// 허용되는 확장자는 .png .jpg .gif 입니다
//String[] exts = new String[] {".png",".jpg",".jpeg",".gif"};
// .jpeg 확장자는 .jpg로 강제 변환 됩니다.
boolean pass =false;// 초기값을 펄스로 넣어준다
String[] exts = new String[] {".png",".jpg",".jpeg",".gif"};
for (String ext : exts) {
pass = fileName.endsWith(ext);//endwith는 끝난는 문장일 맞는지 알아볼수 있다
System.out.println(ext+":"+pass);// 찍어본다
if(pass == true) {
break;
}
}
System.out.println(pass); //위에 다돌고 나서 펄스냐 트루냐에 따라 작동된다
if(pass == false) {
return"허용되는 확장자는 .png .jpg .gif .jpeg 입니다.";
}
//리플레이스(=치환)
if(fileName.endsWith(".jpeg")) {
fileName = fileName.replace(".jpeg", ".jpg");
}
return fileName+"은 정상적인 파일 입니다.";
}
}