工程如下:
index.jsp中
前台提交表单,表单如下:
<body>
<formaction="test"method="post">
<inputtype="text"name="enter">
<inputtype="submit">
</form>
</body>
提交之后跳转到指定的url,通过web.xml这个配置文件进行映射,web.xml如下:
<?xml version="1.0"encoding="UTF-8"?>
<web-app xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Servelet</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>test</display-name>
<servlet-name>test</servlet-name>
<servlet-class>com.test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
<servlet> </servlet>包含的是servlet的相关属性
Servlet的名字:<servlet-name>test</servlet-name>
Servlet对应的class:<servlet-class>com.huawei.test</servlet-class>
<servlet-mapping> </servlet-mapping>包含的是servlet的映射关系
Servlet的名字:<servlet-name>test</servlet-name>
Servlet映射的url:<url-pattern>/test</url-pattern>
整个请求的过程是这样的:
提交表单->跳转到表单action中的url->去web.xml配置文件中找对应的servlet的名字->最后根据servlet的名字找到对应的servlet,比如这里是跳转到com.test,执行该servlet的get或者post方法。Com.test内容如下:
protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {
// TODO Auto-generated method stub
String hello =request.getParameter("enter");
response.sendRedirect("success.jsp?hello=" + hello);
}
protectedvoiddoPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {
// TODO Auto-generated method stub
doGet(request,response);
}
最后跳转到success.jsp中并传参数hello。完成前后台的响应。
success.jsp:
<body>
hello:<%= request.getParameter("hello") %>
</body>
执行结果:
前台提交:world
传到后台,处理之后返回前台: