用纯jsp实现用户的登录、注册与退出

用户的登录、注册和退出是一个系统最常见的功能,现将各功能用jsp代码表示出来

用户的登录:

其中connDB是数据库连接类,将用户名username放入session中

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>

<jsp:useBean id="connBean" scope="page" class="beans.connDB"/>

<%

request.setCharacterEncoding("GB2312");

String username=request.getParameter("username");

String PWD=request.getParameter("PWD");

if(username!=""){%>

<%	ResultSet rs=connBean.executeQuery("select * from tb_User where UserName='"+username+"'");

	if (rs.next()){

		String rsPWD=rs.getString("PWD");

		if(PWD.equals(rsPWD)){%>

			<script language="javascript">

			opener.location.reload();

			window.close();

			</script>

		<%

                session.setAttribute("username",username);

		}else{%>

		<script language="javascript">

		alert("您输入的密码不正确,请重新输入!");

		history.back();

		</script>

		<%}

	}else{ %>

<script language="javascript">

alert("您输入的用户名不正确,请重新输入!");

history.back();

</script>

<%}

}%>

 

 

用户的注册:

 

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>

<jsp:useBean id="connBean" scope="page" class="beans.connDB"/>



<%

request.setCharacterEncoding("GB2312");

String username=request.getParameter("username");

String PWD=request.getParameter("PWD1");

String birthday=request.getParameter("birthday");

String sex=request.getParameter("sex");

String OICQ=request.getParameter("OICQ");

String tel=request.getParameter("tel");

String homepage=request.getParameter("homepage");

String address=request.getParameter("address");

String postcode=request.getParameter("postcode");

String Email=request.getParameter("Email");

ResultSet rs=connBean.executeQuery("select * from tb_user where username='"+username+"'");

if (rs.next()){

	out.println("<script language='javascript'>alert('该用户名已经存在,请重新注册!');window.location.href='reg.jsp';</script>");

}else{

	String sql="Insert into tb_User values('"+username+"','"+PWD+"','"+birthday+"','"+sex+"','"+OICQ+"','"+tel+"','"+homepage+"','"+address+"','"+postcode+"','"+Email+"',default )";

	int ret=0;

	ret=connBean.executeUpdate(sql);

	if (ret!=0){

		out.println("<script language='javascript'>alert('用户注册成功!');window.location.href='index.jsp';</script>");

		}else{

		out.println("<script language='javascript'>alert('用户注册失败!');window.location.href='reg.jsp';</script>");

	}

}

%>




用户的退出:

 

这其中必须注意不能简单的退到登录页面,而要在退出的时候将session中的用户名username清空。

 

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>



<%

session.removeAttribute("username");  //清空Session变量

response.sendRedirect("index.jsp");

%>




这些仅仅是用纯jsp实现的,更正规的方式是用mvc方式。

 

 

你可能感兴趣的:(jsp)