Servlet----------在 Servlet 中的xml配置

时间:2023-03-08 21:49:19

今天弄了大半天,才弄好了,还是请教了别人,主要原因在于把web.xml文件放在了WEB-INF文件夹下面了,正常的情况是在WebRoot下面的。

还有一个,我是在MyEclipse中操作的,起初不知道,在创建web project时候,没有出现web.xml文件,所以web.xml文件都是复制过来的。

在这里,给大家讲讲怎么在创建web project的时候也一起创建了web.xml文件。

(1)在创建web project工程时,写好name后,不要直接点Finish,我就是直接点了Finish才不行的,这个时候点击Next,如下图

Servlet----------在 Servlet 中的xml配置

(2)点击Next后,看到下图所示,我们还是点击Next

Servlet----------在 Servlet 中的xml配置

(3)点击Next后,看到下图所示,这个时候,我们应该把图片上的那个方框打上勾才行,这样才可以创建web.xml文件

Servlet----------在 Servlet 中的xml配置

(4)打上勾后,再点击Finish就行了

Servlet----------在 Servlet 中的xml配置

回归正文,主要的内容还是在xml文件的配置中,文件名就不写了,直接看图

Servlet----------在 Servlet 中的xml配置

 <!DOCTYPE html>
<html>
<head>
<title>input.html</title> </head> <body>
<form action="InputServlet" method="post">
输入内容:<input type="text" name="info">
<input type="submit" value="提交">
</form>
</body>
</html>
 package org.lxh.serletdemo;

 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 InputServlet extends HttpServlet{ protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String info= req.getParameter("info");
PrintWriter out = resp.getWriter();
out.print("<html>");
out.print("<head><title>MLDNJAVA</title></head>");
out.print("<body>");
out.print("<h1>"+info+"</h1>");
out.print("<body>");
out.print("</html>");
out.close(); } protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doGet(req, resp);
}
}
<?xml version="1.0" encoding="GBK"?>
<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_3_1.xsd"
version="3.1"
metadata-complete="true">
<servlet> <!-- 定义servlet -->
<servlet-name>input</servlet-name> <!--与servlet-mapping相对应 -->
<servlet-class> <!-- 定义包.类名称 -->
org.lxh.serletdemo.InputServlet
</servlet-class>
</servlet>
<servlet-mapping> <!-- 映射路径 -->
<servlet-name>input</servlet-name> <!-- 与servlet相对应 -->
<url-pattern>/InputServlet</url-pattern> <!-- 页面的映射路径 -->
</servlet-mapping>
</web-app>

Servlet----------在 Servlet 中的xml配置

在input.html中的action="InputServlet"  这个表示的示表单提交就会跳转到另一个页面中去,在web.xml这件中又配置了<url-pattern>/InputServlet</url-pattern> <!-- 页面的映射路径 -->,这个 <url-pattern>配置的是input.html这件中action要跳转的路径,但是在web.xml中有映射路径,也有定义了servlet,所有这个时候又跳转到servlet设置的文件中去,在这里就是

<servlet-class> <!-- 定义包.类名称 --> org.lxh.serletdemo.InputServlet </servlet-class>,所以这个时候就跳转到

执行InputServlet.java中去

如图:

Servlet----------在 Servlet 中的xml配置

点击提交后

Servlet----------在 Servlet 中的xml配置