사용자 표 의 추가 삭제 검사 (조건 과 페이지 없 음 조회) 의 dao 구현 클래스 와 servlet, 로그 인 및 종료, 동적 메뉴

19054 단어 JAVA
dao 인터페이스:
//     ,     
	public int addUser(User user);

	//   ,            
	public List queryUsers(User user);

	//   ,          
	public int deleteUser(int userId);

	//        
	public int updateUser(User user);
	//    Id     
	public User updateUser(int userId);
    
	public User loginUser(User user);
	
	//    Id     ,      
	public User getUserById(int userId);
	
	//  
	public User login(String userName,String password);

dao 구현 클래스:


	@Override
	public User login(String userName, String password) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
	    User user=null;
		String sql="SELECT USER_ID,USER_NAME,PASSWORD,REAL_NAME,SEX,BIRTHDAY,ROLE_ID FROM T_USER "
				+ "WHERE USER_NAME=? AND PASSWORD=?";
		
		try {
			conn = DBUtil.getConnection();
			ps=conn.prepareStatement(sql);
			ps.setString(1, userName);
			ps.setString(2, password);
			rs=ps.executeQuery();
			while(rs.next()) {
				int userId=rs.getInt("USER_ID");
			    String username=rs.getString("USER_NAME");
			    String passWord=rs.getString("PASSWORD");
			    String realName=rs.getString("REAL_NAME");
			    int sex=rs.getInt("SEX");
			    String birthday=rs.getString("BIRTHDAY");
			    int roleId=rs.getInt("ROLE_ID");
			    user=new User(userId,username,passWord,realName,sex,birthday,roleId);
			   
			}
			
		} catch (SQLException e) {
			
			e.printStackTrace();
		}finally {
			DBUtil.closeConn(conn, ps, rs);
		}
		return user;
	}
	@Override
	public int updateUser(User user) {
		Connection conn = DBUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;

String sql = "UPDATE T_USER SET USER_NAME=?,PASSWORD=?,REAL_NAME=?,SEX=?,BIRTHDAY=TO_DATE(?,'YYYY-MM-DD'),ROLE_ID=?"
		+ " WHERE USER_ID=?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, user.getUserName());
			ps.setString(2, user.getPassword());
			ps.setString(3, user.getRealName());
			ps.setInt(4, user.getSex());
			ps.setString(5, user.getBirthday());
			ps.setInt(6, user.getRoleId());
			ps.setInt(7,user.getUserId());
			return ps.executeUpdate();
			
			
		} catch (SQLException e) {

			e.printStackTrace();
		} finally {
			DBUtil.closeConn(conn, ps, rs);
		}

		return 0;
	}
	@Override
	public User updateUser(int userId) {
		Connection conn =null;
		PreparedStatement ps = null;	
		User user=null; 
		try {
			 conn=DBUtil.getConnection();
			 String sql = "UPDATE T_USER SET USER_NAME=?,PASSWORD,REAL_NAME=?,SEX=?,BIRTHDAY=TO_DATE(?,'YYYY-MM-DD'),ROLE_ID=? WHERE USER_ID=?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, user.getUserName());
			ps.setString(2, user.getPassword());
			ps.setString(3, user.getRealName());
			ps.setInt(4, user.getSex());
			ps.setString(5, user.getBirthday());
			ps.setInt(6, user.getRoleId());
			ps.setInt(7, user.getUserId());
			int result=ps.executeUpdate();
			if(result>0) {
				System.out.println("    ");
			}else {
				System.out.println("    ");
			}
		} catch (SQLException e) {

			e.printStackTrace();
		} finally {
			DBUtil.closeConn(conn, ps, null);
		}

		return user;
	}
	@Override
	public User getUserById(int userId) {
		Connection conn = DBUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		User user=null;
		String sql = "SELECT USER_ID,USER_NAME,PASSWORD,REAL_NAME,SEX,BIRTHDAY,ROLE_ID FROM T_USER WHERE USER_ID=?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, userId);
			rs = ps.executeQuery();
			if(rs.next()) {
				user=new User();
				user.setUserId(rs.getInt("USER_ID"));
				user.setUserName(rs.getString("USER_NAME"));
				user.setPassword(rs.getString("PASSWORD"));
				user.setRealName(rs.getString("REAL_NAME"));
				user.setSex(rs.getInt("SEX"));
				String birthday=(rs.getString("BIRTHDAY")).substring(0,10);
				user.setBirthday(birthday);
				user.setRoleId(rs.getInt("ROLE_ID"));

			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DBUtil.closeConn(conn, ps, rs);
		}
		return user;
	}


	@Override
	public int deleteUser(int userId) {
		Connection conn = DBUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "DELETE FROM T_USER WHERE USER_ID=?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, userId);
			return ps.executeUpdate();
		} catch (SQLException e) {

			e.printStackTrace();
		} finally {
			DBUtil.closeConn(conn, ps, rs);
		}

		return 0;
	}

	@Override
	public int addUser( User user) {
    	Connection conn=DBUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "INSERT INTO T_USER(USER_ID,USER_NAME,PASSWORD,REAL_NAME,SEX,BIRTHDAY,ROLE_ID) VALUES(SEQ_T_USER.NEXTVAL,?,?,?,?,TO_DATE(?,'yyyy-mm-dd'),?)";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, user.getUserName());
			ps.setString(2, user.getPassword());
			ps.setString(3, user.getRealName());
			ps.setInt(4, user.getSex());
			ps.setString(5, user.getBirthday());
			ps.setInt(6, user.getRoleId());
			return ps.executeUpdate();
		} catch (SQLException e) {

			e.printStackTrace();
		} finally {
			DBUtil.closeConn(conn, ps, rs);
		}

		return 0;
	}

	@Override
	public User loginUser(User user) {
		Connection conn = DBUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		User users = null;
		String sql = "SELECT * FROM T_USER WHERE USER_NAME=? AND PASSWORD=?";
		try {

			ps = conn.prepareStatement(sql);
			ps.setString(1, user.getUserName());
			ps.setString(2, user.getPassword());
			rs = ps.executeQuery();
			while (rs.next()) {
//				users = new User();
//				users.setUserId(rs.getInt("USER_ID"));
//				users.setUserName(rs.getString("USER_NAME"));
//				users.setPassword(rs.getString("PASSWORD"));
//				users.setRealName(rs.getString("REAL_NAME"));
//				users.setSex(rs.getInt("SEX"));
//				users.setBirthday(rs.getString("BIRTHDAY"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.closeConn(conn, ps, rs);
		}
		return users;
	}
	

	@Override
	public List queryUsers(User user) {
		List users = new ArrayList();
		Connection conn = DBUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "SELECT USER_ID,USER_NAME,PASSWORD,REAL_NAME,SEX,BIRTHDAY FROM T_USER WHERE 1=1";
		try {
			//           
			if (user.getRealName() != null && user.getRealName().equals("")) {
				sql += "AND REAL_NAME LIKE ?";
			}
			ps = conn.prepareStatement(sql);
			//      +       
			if (user.getRealName() != null && user.getRealName().equals("")) {
				ps.setString(1, "%" + user.getRealName() + "%");
			}

			rs = ps.executeQuery();
			while (rs.next()) {
				int userId = rs.getInt("USER_ID");
				String userName = rs.getString("USER_NAME");
				String password = rs.getString("PASSWORD");
				String realName = rs.getString("REAL_NAME");	
				int sex = rs.getInt("SEX");
				String birthDay = rs.getString("BIRTHDAY");
				User temp = new User();
				temp.setUserId(userId);
				temp.setUserName(userName);
				temp.setPassword(password);
				temp.setRealName(realName);
				temp.setSex(sex);
				temp.setBirthday(birthDay);
				users.add(temp);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.closeConn(conn, ps, rs);
		}
		return users;
	}

UserServlet:
package com.cyzy.servlet;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cyzy.bean.Role;
import com.cyzy.bean.User;

import com.cyzy.service.RoleService;
import com.cyzy.service.UserService;
import com.cyzy.util.ServiceFactory;

/**
 * Servlet implementation class UserServlet
 */
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String userAction = request.getParameter("userAction");
	     if (userAction != null && userAction.equals("addBefore")) {
			addBefore(request, response);
		} else if (userAction != null && userAction.equals("add")) {
			addUser(request, response);
		} else if (userAction != null && userAction.equals("delete")) {
			deleteUser(request, response);
		} else if (userAction != null && userAction.equals("updateBefore")) {
			updateBefore(request, response);
		} else if (userAction != null && userAction.equals("update")) {
			updateUser(request, response);
		} else if (userAction != null && userAction.equals("list")) {
			queryUserList(request, response);
		} else if (userAction != null && userAction.equals("detail")) {
			userDetail(request, response);
		}else if (userAction != null && userAction.equals("userId")) {
			byUserId(request, response);
		}else if (userAction != null && userAction.equals("getRoleList")) {
			getRoleList(request, response);
		}
	}

	private void userDetail(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//     
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");

		byUserId(request, response);
		getRoleList(request, response);
		request.getRequestDispatcher("/user/user_detail.jsp").forward(request, response);
	}

	private void addBefore(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//    
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		getRoleList(request, response);	
		request.getRequestDispatcher("/user/user_add.jsp").forward(request, response);
	}
	//      
	private void getRoleList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Role role=new Role();
		RoleService roleService=(RoleService)ServiceFactory.getServiceImpl(RoleService.class.getName());
		List roleList=roleService.queryRole(role);	
		request.setAttribute("roleList", roleList);
	}

	private void addUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//    
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
        
		//    
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String realName = request.getParameter("realName");
		int sex=Integer.parseInt(request.getParameter("sex"));
		String birthday = request.getParameter("birthday");
		int roleId=Integer.parseInt(request.getParameter("roleId"));
		
		User user = new User(0,userName,password,realName,sex,birthday,roleId);
     
		UserService userService=(UserService)ServiceFactory.getServiceImpl(UserService.class.getName());
		int result=userService.addUser(user);
		if(result>0) {
			queryUserList(request,response);
		}

	}

	//        
	private void updateBefore(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		byUserId(request, response);
		getRoleList(request, response);	
		request.getRequestDispatcher("/user/user_update.jsp").forward(request, response);
	}
	//        
	private void byUserId(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String userId = request.getParameter("userId");
		UserService userService=(UserService)ServiceFactory.getServiceImpl(UserService.class.getName());
		User user=userService.getUserById(Integer.parseInt(userId));	    
		request.setAttribute("user", user);		
	}

	private void updateUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		int userId=Integer.parseInt(request.getParameter("userId"));
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String realName = request.getParameter("realName");
		int sex=Integer.parseInt(request.getParameter("sex"));
		String birthday = request.getParameter("birthday");
		int roleId=Integer.parseInt(request.getParameter("roleId"));

		User user=new User(userId,userName,password,realName,sex,birthday,roleId);
	
		UserService userService=(UserService)ServiceFactory.getServiceImpl(UserService.class.getName());
		int result=userService.updateUser(user);
		System.out.println("result:"+result);
		if(result>0) {
			queryUserList(request, response);
		}
	}

	private void deleteUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");

		String userId = request.getParameter("userId");
		UserService userService=(UserService)ServiceFactory.getServiceImpl(UserService.class.getName());
		int result = userService.deleteUser(Integer.parseInt(userId));
		if (result > 0) {
			queryUserList(request, response);
		}
	}

	private void queryUserList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//     
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		User user = new User();
		UserService userService=(UserService)ServiceFactory.getServiceImpl(UserService.class.getName());
		List userList = userService.queryUsers(user);
		request.setAttribute("userList", userList);
		request.getRequestDispatcher("/user/user_list.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		doGet(request, response);
	}

}

LoginServlet:
package com.cyzy.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.cyzy.bean.Menu;
import com.cyzy.bean.User;
import com.cyzy.service.MenuService;
import com.cyzy.service.UserService;
import com.cyzy.util.ServiceFactory;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();       
    }
   

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String loginAction=request.getParameter("loginAction");
		if (loginAction != null && loginAction.equals("login")) {
			login(request,response);
		}else if (loginAction != null && loginAction.equals("loginOut")) {
			loginOut(request,response);
		}
	}
	
	private void login(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		//         
		String userName=request.getParameter("userName");
		String password=request.getParameter("password");
	    UserService userService=(UserService)ServiceFactory.getServiceImpl(UserService.class.getName());
	    User user=userService.login(userName, password);
	    if(user!=null) {
			HttpSession session=request.getSession();
			//session.setMaxInactiveInterval(10);//         
			session.setAttribute("loginUser", user);
			//             
			//      request/session  
			List menuList=new ArrayList();
			MenuService menuService=(MenuService)ServiceFactory.getServiceImpl(MenuService.class.getName());
			menuList=menuService.queryMenuByuserName(userName);
			request.getSession().setAttribute("menuList", menuList);
			//      iframe  ,    request      
			//request.setAttribute("menuList", menuList);
			request.getRequestDispatcher("/admin/adminMain.jsp").forward(request, response);
			
		}else {
			PrintWriter out =response.getWriter();
			out.println("");
			out.println("window.alert('     ');");
			out.println("window.location.href='http://localhost:8080/JF190902/index.jsp';");
			out.println("");
		}		
	}
	
	private void loginOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");	
		HttpSession session=request.getSession();
		session.removeAttribute("loginUser");
		response.sendRedirect("http://localhost:8080/JF190902/index.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

좋은 웹페이지 즐겨찾기