1、Servlet的写法如下:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestJS extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String sname=req.getParameter("name");
String sage=req.getParameter("age");
PrintWriter pw =resp.getWriter();
pw.println("sname="+sname+" sage"+sage);
pw.close();
}
}
2、web.xml的写法如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>jack2</servlet-name>
<servlet-class>org.jspServlet.com.TestJS</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>jack2</servlet-name>
<url-pattern>/test2</url-pattern>
</servlet-mapping>
</web-app>
3、前端jsp的写法如下:
<%@ page language="java" contentType="text/html"
pageEncoding="utf-8"%>
<html>
<head>
<title>this first jsp and Servlet</title>
</head>
<body>
<form action="test2" method="post">
姓名:<input type="text" name="name">
年龄:<input type="text" name="age"><br>
<input type="submit" values="提交">
</form>
</body>
</html>
4、总结
这个程序也很简单,就是多了一个前端的jsp可以输入一些值
流程是这样的:先登录jsp页面,jsp就会找到web.xml的配置文件。web.xml就会找到Servlet类(web.xml主要用来找到要用的servlet是哪个)。通过jsp的请求,这样Servlet类,就可以等到一些请求的信息。把得到的值输出,或转给别的jsp页面。
5、配置文件
<servlet-mapping>
<servlet-name>jack2</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
form表单
<form action="test2.do" method="post">
姓名:<input type="text" name="name">
年龄:<input type="text" name="age"><br>
<input type="submit" values="提交">
</form>
这样修改也是可以提交的。所有的action="xxx.do"都能通过。