本实例将应用JSTL实现电子商城网站中的用户登陆,显示分时问候和页面重定向等功能。
显示结果:
实现代码如下:
1、在JSTL页面中添加Taglib指令:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
2、index.jsp
<c:import url="top.jsp" charEncoding="utf-8">
</c:import>
3、top.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<table style="background-color:orange" width="100%">
<tr>
<td>
<c:choose>
<c:when test="${empty sessionScope.name}">
<a href="login.jsp">你好,请登陆</a>
</c:when>
<c:otherwise>
欢迎您!${sessionScope.name}[<a href="logout.jsp">退出</a>]
</c:otherwise>
</c:choose>
</td>
<td>
<jsp:useBean id="date" class="java.util.Date"></jsp:useBean>
<c:choose>
<c:when test="${date.hours>=0 && date.hours<5}">凌晨好!</c:when>
<c:when test="${date.hours>=5 && date.hours<8}">早上好!</c:when>
<c:when test="${date.hours>=8 && date.hours<11}">上午好!</c:when>
<c:when test="${date.hours>=11 && date.hours<13}">中午好!</c:when>
<c:when test="${date.hours>=13 && date.hours<17}">下午好!</c:when>
<c:otherwise>晚上好!</c:otherwise>
</c:choose>
现在时间是:${date.hours}时${date.minutes}分${date.seconds}秒
</td>
<td>
<c:import url="http://i.tianqi.com/index.php?c=code&id=99" charEncoding="utf-8"></c:import>
</td>
<td width="50%"></td>
</tr>
</table>
4、logout.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:remove var="name" scope="session"/>
<c:redirect url="index.jsp"></c:redirect>
5、login.jsp
<form action="bdsServlet">
用户昵称:<input name="name" type="text"/><br>
密码:<input name="pwd" type="text"/><br>
<input name="Submit" type="submit" value="登陆"/>
<input type="reset" value="重置"/>
</form>
6、BdsServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name=new String(request.getParameter("name").getBytes("ISO-88859-1"),"utf-8");
HttpSession session=request.getSession();
session.setAttribute("name", name);
response.sendRedirect("index.jsp");
}
注意:
1、servlet配置路径:
2、新建servlet时将url改为servlet类名,第一个首字母小写,避免访问浏览器时修改路径