您的位置:首页 > Web前端 > JavaScript

一个 JSP 简单的登录例子

2017-07-11 14:05 288 查看
需求图:



理解:



login.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="handleLogin.jsp" method="post">
用户名:<input type="text" name="username" value=""/><br/>
密码:<input type="password" name="password" value=""/><br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>

handleLogin.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%

request.setCharacterEncoding("utf-8");//post方式提交处理乱码

String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username);
/*if(username == "sa"&&password == "sa"){//比较的是地址
response.sendRedirect("welcome.jsp");
}*/
/**
username.equals("sa")
这样写的话当username为空时且不通过登录界面直接进入此页面时会抛异常!
*/
if("sa".equals(username) && "sa".equals(password))//比较的是值
{
session.setAttribute("sessionUserName", username);
//request.setAttribute("sessionUserName", username);/*request无法充当session的作用*/
/**
转发:地址不变,request数据不丢失,因为request数据只能在同一请求中有效,转发是在服务器内部完成的。
重定向:地址改变,request数据丢失,发了两个请求,request数据已经丢失,在服务器外部完成的。
*/
//response.sendRedirect("welcome.jsp");
//请求调度器来转发
request.getRequestDispatcher("welcome.jsp").forward(request,response);
}
else{
response.sendRedirect("login.jsp");
}
%>
welcome.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ include file="loginControl.jsp" %><!-- 引入访问控制的文件 -->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<style type="text/css">
body{
font-size:50px;
text-align:center;
color:#0ff;
}
</style>
<body>

<%
String user = request.getParameter("username");
%>
登录成功!热烈欢迎<%=user %>的到来!
</body>
</html>

loginControl.jsp:

<%
String sessionUserName = (String)session.getAttribute("sessionUserName");
//String sessionUserName = (String)request.getAttribute("sessionUserName");
//不适合做访问控制,因为request只在一次请求中有效,数据会丢失。
if(sessionUserName==null){
response.sendRedirect("login.jsp");
}
%>

效果图:



登录成功界面:



有了session之后直接访问welcome.jsp就可以进去了,界面如下:



大概就这样吧,比较简陋的效果。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: