整体结构
四个核心文件:
两个jsp文件(test.jsp与form.jsp),一个xml文件,一个java类(HelloServlet)
首先创建一个java类,这个类接收form.jsp传过来的参数,然后转发到test.jsp显示出来。
package com.cy.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HelloServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.获取前端参数
String method=req.getParameter("method");
if(method.equals("add")){
req.getSession().setAttribute("name","执行了add方法");
}else{
req.getSession().setAttribute("name","执行了其他方法");
}
//2.试图转发或者重定向
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
传递参数的form.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>发送参数</title>
</head>
<body>
<form action="/hello" method="post">
<input type="text" name="method">
<input type="submit">
</form>
</body>
</html>
显示参数的jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>显示地址栏传递过来的param</title>
</head>
<body>
${name}
</body>
</html>
配置文件,映射jsp到java类
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.cy.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<!-- session过期时间-->
<!-- <session-config>-->
<!-- <session-timeout>15</session-timeout>-->
<!-- </session-config>-->
<!-- 欢迎页-->
<!-- <welcome-file-list>-->
<!-- <welcome-file>index.jsp</welcome-file>-->
<!-- </welcome-file-list>-->
</web-app>
整体流程:xml通过<servlet>
与<servlet-mapping>
把java类(HelloServlet)与地址栏输入的地址绑定,当地址栏输入/hello
时,HelloServlet
就知道他该干活了,接收地址栏参数并且用req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp);
转发到test.jsp页面,最终在test.jsp页面显示出数据。
如下图所示:/hello表示路径,?method=add表示传递参数(key=method,value=add)
来源:CSDN
作者:weixin_45059888
链接:https://blog.csdn.net/weixin_45059888/article/details/104611752