欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JSP与Servlet跳转路径问题

程序员文章站 2022-03-02 14:11:30
...

 

  • web.xml中的 /: 代表项目根路径

http://localhost:8888/Servlet25Project/

  • jsp中的/:  服务器根路径

http://localhost:8888/

  • ../   表示返回上一层目录

自定义创建包下的jsp与Servlet之间的跳转案例

1. 文件目录

      JSP与Servlet跳转路径问题

2. login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
   <form  action="../LoginServlet" method="post">
       用户名:<input type="text" name="uname"><br/>
       密码:   <input type="password" name="upwd"><br/>
        <input  type="submit" value="登录">
       </form><br/>
       ${sessionScope.error}<br/>
       
</body>
</html>

2. LoginServlet

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
    public LoginServlet() {
        super();
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String uName=request.getParameter("uname");
		String uPwd=""+request.getParameter("upwd");
//		System.out.println(uName+uPwd);
		if("admin".equals(uName)&&"admin".equals(uPwd)) {
			request.getSession().setAttribute("name", uName);
			response.sendRedirect("test6/welcome.jsp");
		}else {
			request.getSession().setAttribute("error", "账户或密码错误,请重新输入!");
			response.sendRedirect("test6/login.jsp");
		}
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

3. welcome.jsp

<body>
     登录成功!<br/>
     <%//String name=(String)session.getAttribute("name"); //session.getAttribute("name")%>
     你好,<%=session.getAttribute("name") %>
</body>