写了一个form.html:
Beer selection Page
一个servlet Beerselect.java:
package com.example.web;
import java.io.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Beerselect
*/
@WebServlet(“/Beerselect.do”)
public class Beerselect extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Beerselect() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
out.println(“Beer Selection Advice
”);
String c = request.getParameter(“color”);
out.println(“
Got beer color” + c);
}
}
要想访问form.html,点击submit按钮之后出现Beerselect生成的页面,一般在web.xml配置,常见web.xml配置:
xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee/web-app_3_1.xsd”
version=”3.1″>
当你访问/Beerselect.do时,web.xml将/Beerselect.do映射到Beerselect.java.
可是servlet3.0版本,你将找不到web.xml. 那么这些配置放在哪里呢?
我们可以看到Beerselect.java里有一行:
@WebServlet(“/Beerselect.do”),它指定了这个servlet的
一般@WebServlet()会这样:
@WebServlet(urlPatterns = {"/Beerselect.do"}, asyncSupported = true, loadOnStartup = -1, name = "BeerServlet", displayName = "bs", initParams = {@WebInitParam(name = "username", value = "tom")} )
@WebServlet 主要属性列表
属性名 | 类型 | 描述 |
---|---|---|
name | String | 指定 Servlet 的 name 属性,等价于 |
value | String[] | 该属性等价于 urlPatterns 属性。两个属性不能同时使用。 |
urlPatterns | String[] | 指定一组 Servlet 的 URL 匹配模式。等价于 |
loadOnStartup | int | 指定 Servlet 的加载顺序,等价于 |
initParams | WebInitParam[] | 指定一组 Servlet 初始化参数,等价于 |
asyncSupported | boolean | 声明 Servlet 是否支持异步操作模式,等价于 |
description | String | 该 Servlet 的描述信息,等价于 |
displayName | String | 该 Servlet 的显示名,通常配合工具使用,等价于 |