利用EL和JSTL技术,改进用户登录页面(login.jsp),当用户信息验证成功则转到主页面(main,jsp)显示问候语,如“用户liming,你好!”,否则转回login.jsp,保留原来用户输入的用户名,并有提示信息:“用户名或密码错误,请重新输入”。
时间: 2024-02-27 08:52:42 浏览: 17
好的,我会尝试回答。
首先,在login.jsp页面中,需要使用EL表达式获取用户输入的用户名和密码,并将其传递到后台进行验证。可以使用JSTL的<c:if>标签判断验证结果,如果成功则重定向到主页面,否则将错误信息传递到前台并保留原来的用户名。
下面是一个可能的实现方式:
在login.jsp页面中,添加以下代码:
```html
<form action="loginServlet" method="post">
<label>用户名:</label>
<input type="text" name="username" value="${not empty param.username ? param.username : ''}" /><br/>
<label>密码:</label>
<input type="password" name="password" /><br/>
<input type="submit" value="登录" />
</form>
<c:if test="${not empty requestScope.error}">
<p>${requestScope.error}</p>
</c:if>
```
这里使用EL表达式获取用户名,并使用JSTL的<c:if>标签判断是否有错误信息需要显示。
在后台的loginServlet中,进行用户信息验证并根据结果进行重定向或传递错误信息。可以使用request.setAttribute()方法将错误信息传递到前台,使用response.sendRedirect()方法进行重定向。
以下是一个可能的实现方式:
```java
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if ("admin".equals(username) && "123456".equals(password)) {
// 验证成功,重定向到主页面并显示问候语
request.getSession().setAttribute("username", username);
response.sendRedirect("main.jsp");
} else {
// 验证失败,传递错误信息到前台并保留原来的用户名
request.setAttribute("error", "用户名或密码错误,请重新输入");
request.getRequestDispatcher("login.jsp?username=" + username).forward(request, response);
}
}
}
```
在主页面main.jsp中,可以使用EL表达式获取用户名并显示问候语:
```html
<%-- 如果用户没有登录,则重定向到登录页面 --%>
<c:if test="${empty sessionScope.username}">
<%
response.sendRedirect("login.jsp");
%>
</c:if>
<%-- 显示问候语 --%>
<c:if test="${not empty sessionScope.username}">
<p>用户${sessionScope.username},你好!</p>
</c:if>
```
这里使用EL表达式获取用户名,并使用JSTL的<c:if>标签判断是否已经登录。如果未登录,则重定向到登录页面;否则显示问候语。
以上就是利用EL和JSTL技术改进用户登录页面的一个实现方式,希望能对您有所帮助。