界面跳转
效果描述: 用户在index.jsp
输入用户名和密码,若两者都是与预置信息匹配(check.jsp
)则跳转到login.jsp
,否则跳回到登陆界面index.jsp
进行网页跳转,有两种方法 。
1 jsp页面+java代码编写: 需要用<%%>
标签隔开,代码比较杂乱。
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
<form action="check.jsp" method="post" name="frm">
用户名:<input type="text" name="txtname" id="txtname" style="width=120px">
<br>
密码:<input type="password" name="txtpwd" id="txtpwd"style="width=120px">
<br>
<input type="submit" name="smt" id="login" >
<input type="reset" name="rst" id="reset" >
</form>
</body>
</html>
check.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<body>
<%
request.setCharacterEncoding("utf-8");
String user_name=request.getParameter("txtname");//获取用户名字
String user_pwd=request.getParameter("txtpwd");//获取用户密码
if(user_name.equals("佳")&& user_pwd.equals("123")){
%>
<jsp:forward page="login.jsp">
<jsp:param value="<%=user_name %>" name="t_u_name"/>
</jsp:forward>
<%
}else{%>
<jsp:forward page="index.jsp"/>
<% }
%>
This is my JSP page. <br>
</body>
</html>
login.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<head>
<title>登录</title>
</head>
<body>
<%
String uname=request.getParameter("t_u_name");
out.println("welcome "+ uname + " login!");
%>
</body>
</html>
效果:
可以看到,当用户信息不匹配时,本应该跳转回index.jsp页面的却留在check.jsp页面上。
2 cookie 服务器跳转
sessionuser.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
<form action="sessioncheck.jsp" method="post" name="frm">
用户名:<input type="text" name="txtname" id="txtname" style="width=120px">
<br>
密码:<input type="password" name="txtpwd" id="txtpwd"style="width=120px">
<br>
<input type="submit" name="smt" id="login" >
<input type="reset" name="rst" id="reset" >
</form>
</body>
</html>
sessioncheck.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<body>
<%
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
String user_name=request.getParameter("txtname");//获取用户名字
String user_pwd=request.getParameter("txtpwd");//获取用户密码
if(user_name.equals("佳")&& user_pwd.equals("123")){
session.setAttribute("t_u_name", user_name);
response.sendRedirect("sessionlogin.jsp");
}else{
response.sendRedirect("sessionuser.jsp");
}
%>
This is my JSP page. <br>
</body>
</html>
sessionlogin.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<head>
<title>登录</title>
</head>
<body>
welcome <%=session.getAttribute("t_u_name")%> login!
</body>
</html>
效果:
cookie机制下就回跳转回user.jsp,但是大概是浏览器的原因,跳回去的时候默认的正确信息已经填好了。
注意点:
- 输入输出涉及到中文字符,记得把字符集改成
UTF-8
- 表单中想要input中文字符,要记得加这条语句:
request.setCharacterEncoding("utf-8");