1、项目名称
restaurant
2、servlet部分
@WebServlet("/user")
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
StringBuffer sb = new StringBuffer();
sb.append("<html>");
sb.append("<body>");
sb.append("<h1 align=\"center\">User management</h1>");
sb.append("</body>");
sb.append("</html>");
out.print(sb.toString());
out.flush();
out.close();
}
}
3、web.xml部分
由于使用了annotation,因此不需要做任何修改。
4、pom部分
pom内容包括,servlet、mysql-driver、junit依赖。在开发阶段使用tomcat7做web服务器。
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.resta</groupId>
<artifactId>restaurant</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>restaurant Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.tomcat7.deloy.context>/restaurant</maven.tomcat7.deloy.context>
<maven.tomcat7.deloy.url>http://localhost:8080/manager/text</maven.tomcat7.deloy.url>
<maven.tomcat7.deloy.id>tomcat</maven.tomcat7.deloy.id>
<maven.tomcat7.deloy.usr>admin</maven.tomcat7.deloy.usr>
<maven.tomcat7.deloy.psw>admin</maven.tomcat7.deloy.psw>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- mysql driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1-b02</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>restaurant</finalName>
<pluginManagement>
<plugins>
<!-- Maven Tomcat7 Plugin -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<url>${maven.tomcat7.deloy.url}</url>
<server>${maven.tomcat7.deloy.id}</server>
<username>${maven.tomcat7.deloy.usr}</username>
<password>${maven.tomcat7.deloy.psw}</password>
<path>${maven.tomcat7.deloy.context}</path>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
5、运行
maven命令为:tomcat7:run
浏览器链接为:http://localhost:8080/restaurant/user
6、总结
这个servlet实例比较简单,甚至代码量也非常少。但是到了开发后期,在页面分发方面,会随着时间的推移,越发臃肿。