JavaWeb原生客户端发送的数据是如何被服务器接收
1.前端通过action发送form表单的数据
<form action="add" method="post">
<input type="text" name="username"><br/>
<input type="password" name="password"><br/>
<input type="text" name="age"><br/>
<input type="submit" value="提交"><br/>
</form>
2.通过Tomcat的HttpServletRequest对象接收数据,具体代码如下:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
//强制类型转换
Integer age = Integer.parseInt(req.getParameter("age"));
System.out.println("username = " + username);
System.out.println("password = " + password);
System.out.println("age = " + age);
}
}
3.在web.xml中配置servlet
<?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>addServlet</servlet-name>
<servlet-class>addServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>addServlet</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
</web-app>
4.运行结果