Java Servlet 3.0 уже официально выпущен. Сегодня я покажу вам одну из новых функций: аннотации WebServlet . Я буду использовать Netbeans 7 с Jetty и Maven для создания и запуска демонстрационного кода.
Создайте новое веб-приложение Maven с NetBeans 7 под названием: Servlet3Demo
После создания проекта обязательно удалите файл index.jsp, так как мы не будем его использовать.
Добавьте новый сервлет в проект под названием: MyServlet
До Servlet 3.0 вы должны были поместить всю информацию о сервлетах, фильтрах и т. Д. В файл web.xml . С аннотациями теперь вам больше не нужно полагаться на web.xml . Ниже приведен код для MyServlet , обратите внимание на использование аннотаций для определения этого сервлета и для установки некоторых начальных параметров.
package com.giantflyingsaucer.servlet3demo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(asyncSupported = false, name = "MyServlet", urlPatterns = {"/"},
initParams = {@WebInitParam(name="webInitParam1", value="Hello"), @WebInitParam(name="webInitParam2", value="World")})
public class MyServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html><head><title>MyServlet</title></head><body>");
out.write(getServletConfig().getInitParameter("webInitParam1") + " ");
out.write(getServletConfig().getInitParameter("webInitParam2"));
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}
}
Now we need to add support to run Jetty and have it load up the WAR file compliments of Maven. Modify your POM to include Jetty and the Jetty plugin.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.giantflyingsaucer</groupId>
<artifactId>Servlet3Demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>Servlet3Demo</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.0.1.v20110908</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>6.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.0.1.v20110908</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<webAppConfig>
<contextPath>/</contextPath>
</webAppConfig>
</configuration>
</plugin>
</plugins>
</build>
</project>
Set the project properties for Maven like the following:
Run your project, NetBeans 7 will display a prompt which you can use the following settings.
Load the project in your browser: http://localhost:8080
You should see Hello World in the browser.