package com.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name="helloUser2", urlPatterns={"/getUser","/userInfo"},loadOnStartup=1) public class HelloUser extends HttpServlet{ private static final String DEFAULT_USER="rzm"; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String user=request.getParameter("user"); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter writer=response.getWriter(); writer.append("<!DOCTYPE html>") .append("<html><head></head><body>") .append("用户是"+user) .append("</body></html>"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
上面是一个servlet,我们知道web项目里web.xml中需要配置url和servlet之间对应。
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" metadata-complete="false" version="2.5"> <display-name>mavenWeb</display-name> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.servlet.HelloWorldServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet> <servlet-name>helloUser</servlet-name> <servlet-class>com.servlet.HelloUser</servlet-class> </servlet> <servlet-mapping> <servlet-name>helloUser</servlet-name> <url-pattern>/helloUser</url-pattern> </servlet-mapping> </web-app>
注意:
metadata-complete="false" 默认的是
metadata-complete="true" 必须的修改掉
Servlet 3.0 的部署描述文件 web.xml 的顶层标签 <web-app> 有一个 metadata-complete 属性,该属性指定当前的部署描述文件是否是完全的。如果设置为 true,则容器在部署时将只依赖部署描述文件,忽略所有的注解(同时也会跳过 web-fragment.xml 的扫描,亦即禁用可插性支持,);如果不配置该属性,或者将其设置为 false,则表示启用注解支持(和可插性支持)。
应用注解方便很多,不过现在都用集成spring等基本原始的servlet也不会多写了。