jsp入门
创建一个新的jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
int a =10;
%>
<%
out.print(a);
%>
<%=a %>
</body>
</html>
我们运行一下
发现页面上显示的是
10 10
这里的out.print就是向页面输出内容
而 <%= %>
其实也是向页面输出
里面放的是参数
所以其实这里的两部分的代码
是一样的
jsp中操作session
我们创建2个jsp页面,一个a.jsp,一个b.jsp
<html>
<head>
<title>Title</title>
</head>
<body>
<%
session.setAttribute("name", "Alice");
%>
</body>
</html>
我们在a页面,用session调用setAttribute方法
保存一个name属性
然后
<html>
<head>
<title>Title</title>
</head>
<body>
<%
String name = (String) session.getAttribute("name");
%>
<%=name %>
</body>
</html>
在b页面中,从session中取出name属性
然后用<%= %>来输出
然后我们运行项目
我们先访问a.jsp,这个时候已经保存了属性
然后我们访问b.jsp
发现页面上显示了Alice
这就是jsp中使用session的简单例子
我们再来一个小例子
用session来保存登录状态
我们先来写一个登录页面
<form action="/login" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit" value="登录">
</form>
就是一个简单的表单
现在我们点击提交
会把表单提交到/login路径
public class LoginServlet extends BaseServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置request编码
request.setCharacterEncoding("utf-8");
//从request请求中获取username和password
String username = request.getParameter("username");
String password = request.getParameter("password");
//简单验证用户名
if (username.equals("abc")) {
//将username保存到session中,保持登录状态
request.getSession().setAttribute("username", username);
request.setAttribute("username", username);
response.sendRedirect("/login/success.jsp");
} else {
//保存一个msg属性,存入提示信息
request.setAttribute("msg", "账号或密码错误");
request.getRequestDispatcher("/login/login.jsp").forward(request, response);
}
}
}
然后我们把login页面和success页面修改一下
success页面
<body>
<%
String username = (String) session.getAttribute("username");
if (username == null) {
request.setAttribute("msg", "请先登录吧");
request.getRequestDispatcher("/login/login.jsp").forward(request, response);
return;
}
%>
<div>欢迎会员 <%=username %></div>
</body>
从session中取出username属性
如果username为空
那么就说明用户还没有登录
那么就将请求转发到login.jsp页面
<body>
<%
String message = "";
String msg = (String) request.getAttribute("msg");
if (msg != null) {
message = msg;
}
%>
<form action="/login" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit" value="登录">
</form>
<div><%=message%>
</div>
</body>
从request中取出msg属性
如果有提示信息
就显示出来