JSP

구글링 검색  -> httpservletrequest java bean mapping

commons beanUtils 라이브러리 추가

https://commons.apache.org/proper/commons-beanutils/download_beanutils.cgi

commons logging  라이브러리 추가

https://commons.apache.org/proper/commons-logging/download_logging.cgi

 

 

핵심 코드

		User user =  new User();
		try {
			BeanUtilsBean.getInstance().populate(user, request.getParameterMap());
		} catch (IllegalAccessException | InvocationTargetException e1) {
			throw new ServletException(e1);
		}

 

 

class User

 

public class User {
	
	@Expose
	@NotNull
	@Size(min=4, max=12)
	private String userId;
	
	@Expose(serialize=false)
	@NotNull
	@Size(min=4, max=12)
	private  String password;
	
	@Expose
	@NotNull
	@Size(min=2, max=12)
	private String name;
	
	@Expose
	@Email
	private String email;
	

	public boolean matchPassword(String newPassword) {
		return this.password.equals(newPassword);
	}
	
	public static boolean login(String userid, String password) throws NotFoundUserException, PasswordMismatchException {
		UserDAO userDao=new UserDAO();
		User user=null;
		//User user =Database.findByUserId(userid);
		
		user=userDao.findByUserId(userid);
		
		if(user==null){
			throw new NotFoundUserException();
		}
		
		if(!user.matchPassword(password)){
			throw new PasswordMismatchException();
		}
		
		return true;
	}

	
	public boolean isSameUser(String newUserId){
		if(this.userId==null){
			return false;
		}
		return this.userId.equals(newUserId);
	}

setter ,getter


}	

 

class JavaBeanUtilsTest 

package com.slipp.user;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.junit.Test;

public class JavaBeanUtilsTest {

	@Test
	public void populate() throws Exception{
		final Map<String, String[]> params=new HashMap<>();
		params.put("userName", new String[]{"userA"});
		params.put("password", new String[]{"secrect"});
		params.put("id", new String[]{"10"});
		final JavaBean javaBean=new JavaBean();
		BeanUtilsBean.getInstance().populate(javaBean, params);
		System.out.println(javaBean.getUserName());
		System.out.println(javaBean.getPassword());
		System.out.println(javaBean.getId());
	}
	
	
	
}

 

 

 

class MyValidatorFactory

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

public class MyValidatorFactory {

	//유효성 체크
	public static Validator createValidator(){
		ValidatorFactory factory =Validation.buildDefaultValidatorFactory();
		return factory.getValidator();
	}
	
}

 

 

class CreateUserServlet

@WebServlet("/users/save")
public class CreateUserServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		User user =new User();
		try {
			BeanUtilsBean.getInstance().populate(user, request.getParameterMap());
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}


		Validator validator=MyValidatorFactory.createValidator();  
		Set<ConstraintViolation<User>> constraintViolations=validator.validate(user);
		if(constraintViolations.size() >0){
			String errorMessage=constraintViolations.iterator().next().getMessage();
			String page="/form.jsp";
			System.out.println("회원 가입 에러");
			forwordJSP(request, response, errorMessage, page);
			return;
		}else {
			System.out.println("회원 가입 성공");
		}
		
		Iterator<ConstraintViolation<User>> iterator =constraintViolations.iterator();
		while(iterator.hasNext()){
			ConstraintViolation<User> each=iterator.next();	
		}	
		//Database.addUser(user);
		UserDAO dao =new UserDAO();
		dao.insert(user);	
		response.sendRedirect("/");
		
	}
	
	private void forwordJSP(HttpServletRequest request, HttpServletResponse response,
			String errorMessage, String page) throws ServletException, IOException{
		request.setAttribute("errorMessage", errorMessage);
		RequestDispatcher rd=request.getRequestDispatcher(page);
		rd.forward(request, response);
	}
	

}

 

 

class UpdateUserServlet

package com.slipp.user;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Set;

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.validation.ConstraintViolation;
import javax.validation.Validator;

import org.apache.commons.beanutils.BeanUtilsBean;

import com.slipp.SessionUtils;
import com.slipp.support.MyValidatorFactory;

@WebServlet("/users/update")
public class UpdateUserServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		String sessionUserId = SessionUtils.getStringValue(session, LoginServlet.SESSION_USER_ID);
		if (sessionUserId == null) {
			response.sendRedirect("/");
			return;
		}
		
		User user =  new User();
		try {
			BeanUtilsBean.getInstance().populate(user, request.getParameterMap());
		} catch (IllegalAccessException | InvocationTargetException e1) {
			throw new ServletException(e1);
		}
		
		if (!user.isSameUser(sessionUserId)) {
			response.sendRedirect("/");
			return;
		}
		
		Validator validator = MyValidatorFactory.createValidator();
		Set<ConstraintViolation<User>> constraintViolations = validator.validate(user);
		if (constraintViolations.size() > 0) {
			request.setAttribute("isUpdate", true);
			request.setAttribute("user", user);
			String errorMessage = constraintViolations.iterator().next().getMessage();
			forwardJSP(request, response, errorMessage);
			return;
		}
		
		UserDAO userDAO = new UserDAO();	
		userDAO.updateUser(user);
		response.sendRedirect("/");
	}
	
	private void forwardJSP(HttpServletRequest request,
			HttpServletResponse response, String errorMessage) throws ServletException, IOException {
		request.setAttribute("errorMessage", errorMessage);
		RequestDispatcher rd = request.getRequestDispatcher("/form.jsp");
		rd.forward(request, response);
	}
	
	
}

 

 

 

 

 

 

jsp

 

about author

PHRASE

Level 60  머나먼나라

일을 선택할 때에는 자신의 소질과 사회의 수요를 함께 생각해 보아야 한다. -간디

댓글 ( 4)

댓글 남기기

작성