JSP页面请求Servlet
首先要知道,“/“在JSP和web.xml中的意义不一样
在web.xml中,“/”代表服务器根路径,例如:http://localhost:8080/
而在JSP页面中,“/”代表该项目的根路径,例如:http://localhost:8080/myfirstjsp_war_exploded/
以form表单发起请求为例:
首先,写一个获取用户名和密码的Servlet:
package Controller;
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 java.io.IOException;
//@WebServlet(name = "CheckLogin")
public class CheckLogin extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getParameter("username"));
System.out.println(request.getParameter("userpassword"));
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
然后开始配置web.xml文件
<servlet-mapping> <servlet-name>CheckLogin</servlet-name> <!--url-pattern配置的是浏览器访问时候的路径--> <url-pattern>/a/CheckLogin</url-pattern> </servlet-mapping> <servlet> <servlet-name>CheckLogin</servlet-name> <!--具体所指向的Servlet类,需要带上包名--> <servlet-class>Controller.CheckLogin</servlet-class> </servlet>
当浏览器访问/a/CheckLogin时,项目根目录下并不需要存在a目录,这里只是一个访问的路径,可以随意写,只需要明白这里的第一个“/”代表项目根路径
最后编写JSP页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form method="post" action="a/CheckLogin">
用户名:<input type="text" name="username">
密码:<input type="text" name="userpassword">
<input type="submit">
</form>
</body>
</html>
action中如果不以“/”开头,就代表在当前目录下,如果你放在Web目录下,就是项目的根路径,这里和web.xml配置文件中 标签内容相对应
在配置完web.xml后,记得重新启动服务器。
测试:
这里可以使用IE浏览器,将鼠标放在查询按钮上,查看下方提示栏中即将要跳转的地址,是否与在web.xml中标签下配置的信息相同
输入用户名密码:
打印台输出: