javaweb專案(1)連線資料庫,登入註冊

伊瑞綺嘉拉發表於2020-12-02

servlet

login Servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String name=request.getParameter("name");
		String pwd =request.getParameter("pwd");
		System.out.println(name+pwd);
		String cook =request.getParameter("cookie");
		String  code1=request.getParameter("code");
		HttpSession session=request.getSession(true);
		String code2=(String)session.getAttribute("rand");
		UserDao ud=new UserDao();
		if(code2.equalsIgnoreCase(code1)) {
		try {
				if(ud.isLogin(name, pwd)==1) {
					if(cook!=null) {
						Cookie CookieName=new Cookie("name",name);
						Cookie CookiePwd=new Cookie("pwd",pwd);
						CookieName.setMaxAge(60*60);
						CookiePwd.setMaxAge(60*60);
						response.addCookie(CookieName);
						response.addCookie(CookiePwd);
						System.out.println(CookieName);
						System.out.println(CookiePwd);
					}
					session.setAttribute("name", name);
					System.out.println(session.getAttribute(name));
					response.sendRedirect("loginSuccess.jsp");
				}else {
					request.setAttribute("loginInfo","使用者名稱或密碼錯誤!");
					request.getRequestDispatcher("login.jsp").forward(request, response);
				}
		} catch (Exception e) {
			e.printStackTrace();
		}
		}else {
			request.setAttribute("loginInfo", "驗證碼輸入錯誤!");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

register Servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String name=request.getParameter("name");
		String pwd =request.getParameter("pwd");
		String repwd =request.getParameter("repwd");
		System.out.println(name+pwd+repwd);
		String  code1=request.getParameter("code");
		HttpSession session=request.getSession(true);
		String code2=(String)session.getAttribute("rand");
		UserVO user=new UserVO();
		user.setUserName(name);
		user.setPwd(pwd);
		UserDao ud=new UserDao();
		if(code2.equalsIgnoreCase(code1)) {
		try {
			if(ud.isExit(name)==0){
				if(pwd.length()<6||pwd.length()>10) {
					request.setAttribute("loginInfo","密碼在6位到10位之間");
					request.getRequestDispatcher("register.jsp").forward(request, response);
				}
				else if(pwd==repwd){
					request.setAttribute("loginInfo","兩次輸入的密碼不同");
					request.getRequestDispatcher("register.jsp").forward(request, response);
				}
				else {
				ud.addUser(user);
				response.sendRedirect("login.jsp");
				}
			}else {
				request.setAttribute("loginInfo","該使用者已存在,請重新設定暱稱");
				request.getRequestDispatcher("register.jsp").forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}else {
		request.setAttribute("loginInfo", "驗證碼輸入錯誤!");
		request.getRequestDispatcher("register.jsp").forward(request, response);
	}
	}

DAO

public int isExit(String uname)throws Exception{//判斷使用者名稱是否存在
		int b=0;//使用者名稱不存在
		Connection con=DBUtil.connectDB();
		String sql="select * from user_info1 where user_name=?";
		PreparedStatement ps=con.prepareStatement(sql);
		ps.setString(1, uname);
		ResultSet rs=ps.executeQuery();
		if(rs.next()) {//使用者名稱存在
			b=1;
		}
		close(rs,ps,con);
		return b;
	}

	public int isLogin(String uname,String pwd)throws Exception{//登入
		int b=0;//使用者不存在
		Connection con=DBUtil.connectDB();
		String sql="select * from user_info1 where user_name=? and pwd=?";
		PreparedStatement ps=con.prepareStatement(sql);
		ps.setString(1, uname);//指定user_name為uname
		ps.setString(2, pwd);
		ResultSet rs=ps.executeQuery();//操作物件呼叫查詢方法,返回一個ResultSet類的值
		if(rs.next()) {
			b=1;
		}
		System.out.println(b);
		close(rs,ps,con);
		return b;
	}
	public void addUser(UserVO user)throws Exception{//UserVO包含使用者個人資料屬性
		Connection conn=DBUtil.connectDB();
		String sql="INSERT INTO user_info1(user_name,pwd,age,sex,create_dt)"+"VALUES(?,?,?,?,?)";
		PreparedStatement pstmt=conn.prepareStatement(sql);
		pstmt.setString(1,user.getUserName());
		pstmt.setString(2,user.getPwd());
		pstmt.setInt(3, user.getAge());
		pstmt.setInt(4, user.getSex());
		pstmt.setDate(5,new Date(new java.util.Date().getTime()));
		pstmt.execute();
	}

JSP

login

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登入</title>
<style type="text/css">
 body {
       border: 1px solid #ADD8E6;
       width: 380px;
       text-align: center;
       background-image: url(bai.jpg);
       background-size:100% 100%;
       fileter:alpha(opacity=80);
       -moz-opacity: 0.8;
       opacity: 0.8;
       font-family: Arial, Helvetica,sans-serif;
       margin-top: 200px;
       margin-left: auto;
       margin-right: auto;
   }

#header {
         padding:10px;
         margin: 0px;
          background-color:#568271;
         height: 50px;
         text-align: center;
    }

#header p{
       font-family: cambria;
       padding-top:10px;
       font-size: 40px;
       margin: 10px;
       color: #9370db;
  }

#contain {
          height: 200px;
          border: 2px solid #ADD8E6;
          text-align: center;
          line-height: 1.5em;
          background: -webkit-linear-gradient(top,lavender,lightsteelblue);
          padding:10px;
          margin: 0px;
    }

#footer {
       padding:10px;
        background-color:#568271;
       text-align: center;
   }
* {
          margin: 0px;
          padding: 0px;
    }

</style>
</head>
<script type="text/javascript">
  function refreshCode(){
	  document.getElementById("code").src="validateCodeServlet?t="+Math.random();
  }
</script>
<body>
 <form action="loginServlet" method="post">
 <div id="header"></div>
 <div id="contain">
 <div><%=request.getAttribute("loginInfo")==null?"":request.getAttribute("loginInfo")%></div>
   <table>
     <tr>
         <td>姓名:</td>
         <td><input type="text" name="name" value="${cookie.name.value}"/></td>
     </tr>
     <tr>
         <td>密碼:</td>
         <td><input type="password" name="pwd" value="${cookie.pwd.value}"/></td>
     </tr>
     <tr>
         <td>驗證碼:</td>
         <td><input type="text" name="code"></td>
     </tr>
     <tr>
         <td class="ared"><img id="code" src="before_validateCode"/></td>
         <td><a href="javascript:refreshCode();"><font color="green">看不清楚,換一張</font></a></td>
     </tr>
     <tr>
        <td>記住密碼</td>
        <td><input type="checkbox" name="cookie" value="cookie"></td>
     </tr>
     <tr>
         <td align="right"><input type="reset" value="取消"></td>
         <td><input type="submit" value="確定"></td>
         </td>
        </tr>
     <tr>
        <td>沒有賬號?<a href="register.jsp">立即註冊</a></td>
        </tr>
   </table>
 </form>
</div>
<div id="footer">Copyright@Rotuce</div>
</body>
</html>

register

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
 body {
       border: 1px solid #ADD8E6;
       width: 380px;
       text-align: center;
       background-image: url(bai.jpg);
       background-size:100% 100%;
       fileter:alpha(opacity=80);
       -moz-opacity: 0.8;
       opacity: 0.8;
       font-family: Arial, Helvetica,sans-serif;
       margin-top: 200px;
       margin-left: auto;
       margin-right: auto;
   }

#header {
         padding:10px;
         margin: 0px;
          background-color:#568271;
         height: 50px;
         text-align: center;
    }

#header p{
       font-family: cambria;
       padding-top:10px;
       font-size: 40px;
       margin: 10px;
       color: #9370db;
  }

#contain {
          height: 200px;
          border: 2px solid #ADD8E6;
          text-align: center;
          line-height: 1.5em;
          background: -webkit-linear-gradient(top,lavender,lightsteelblue);
          padding:10px;
          margin: 0px;
    }

#footer {
       padding:10px;
        background-color:#568271;
       text-align: center;
   }
* {
          margin: 0px;
          padding: 0px;
    }

</style>
<title>註冊</title>
</head>
<script type="text/javascript">
  function refreshCode(){
	  document.getElementById("code").src="validateCodeServlet?t="+Math.random();
  }
</script>
<body style="background-image:url('images/bb.jpg');">
<div id="header"></div>
 <div id="contain">
 <form action="registerServlet" method="post" name="registForm">
 <div><%=request.getAttribute("loginInfo")==null?"":request.getAttribute("loginInfo")%></div>
   <table>
     <tr>
     <td>暱稱:</td>
     <td>
   <input class="textSize" type="text" id="uname" name="name" placeholder="名字不能為空" />
        <span id="isExit"></span>
        </td>
      </tr>
        <tr>
        <td>密碼:</td>
        <td><input class="textSize" type="password" name="pwd" placeholder="密碼在6位到10位之間"/></td>
      </tr>
      <tr>
        <td>確認密碼:</td>
        <td><input class="textSize" type="password" name="repwd" placeholder="再輸入一遍密碼進行確認"/></td>
      </tr>
      <tr>
         <td>驗證碼:</td>
         <td><input type="text" name="code"></td>
     </tr>
     <tr>
         <td class="ared"><img id="code" src="before_validateCode"/></td>
         <td><a href="javascript:refreshCode();"><font color="green">看不清楚,換一張</font></a></td>
     </tr>
      <tr>
    <td align="right"><input type="reset" value="重置"></td>
    <td><input type="submit" value="註冊" onclick="return go()"></td>
    </tr>
    <tr>
        <td>已有賬號?<a href="login.jsp">馬上登入</a></td>
        </tr>
   </table>
 </form>
</div>
<div id="footer">Copyright@Rotuce</div>
</body>
</html>

下一篇:javaweb驗證碼的自動生成

相關文章