JSP登录中Session的用法实例详解(jsp实现用户登录注册)学会了吗

随心笔谈3年前发布 admin
225 0 0

文章摘要

该文章介绍了一个基于JavaxServlet框架的JavaServlet实现。代码中定义了一个名为`IndexServlet`的类,继承自`HttpServlet`。该Servlet实现了基本的用户认证功能,通过读取`user`和`password`参数来验证用户身份。如果用户和密码正确,会将会话设置为名为`user`,并将响应重定向到`success.jsp`页面;否则,会将响应重定向回初始页面`Index.jsp`。文章重点描述了Servlet的构造函数、`doGet`和`doPost`方法的实现逻辑,以及其在Web应用开发中的应用场景。


import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(“/IndexServlet”)
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID=1L;

public IndexServlet() {
super();
// TODO Auto-generated constructor stub
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append(“Served at: “).append(request.getContextPath());
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding(“utf-8”);
String user=request.getParameter(“user”);
String password=request.getParameter(“password”);

String path=request.getContextPath();
HttpSession session=request.getSession();

if (“1”.equals(user) && “1”.equals(password)) {

session.setAttribute(“name”, user);
response.sendRedirect(path + “/success.jsp”);

}else{
response.sendRedirect(path + “/Index.jsp”);
}
}

}

© 版权声明

相关文章