一、Servlet的请求流程
web项目中的web.xml文件配置为:
<servlet> <!--别名--> <servlet-name>Hello</servlet-name> <!--类的全限定名--> <servlet-class>hello.HelloServlet</servlet-class> </servlet> <!-- 向外暴露一个资源名称,供外界访问,资源名称前面必须有 / --> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>-
1、第一次在浏览器地址栏输入upload/201811231142178475.png" style="margin: 0px; padding: 0px; border: none; max-width: 800px; height: auto;" alt="" />
我们只要继承HttpServlet,
public class TestServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void init() throws ServletException { //自己的初始化操作 } //编写Servlet方式一 protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //编写处理请求的代码 //不能调用父类中 的service : super.service(); } //编写Servlet方式二 //处理POST请求 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } //处理GET请求 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //处理全部的请求 } }四、HttpSevletRequst的常用方法
HttpServletRequst是ServletRequest的子接口,封装了处理http协议请求的方法
String getMethod();//返回请求方式GET 或 POST String getRequestURI();//返回请求行中的资源名称 StringBuffer getRequestURL();//返回浏览器中地址栏中的信息 String getContextPath(); //返回上下文路径path属性值 String getHeader(String name) //返回请求头信息 String getParameter(String name);//返回指定参数名的参数值(一般是表单用户输入) String getParameterValues(String name);//返回指定名称的多个参数值请求乱码处理
请求默认是ISO-8859-1,不支持中文
- 方式一:解决中文乱码
- 1.按照ISO-8859-1把乱码恢复成二进制形式byte[] data = username.getBytes("ISO-8859-1");
- 2.对二进制形式重新编码为UTF-8,username = new String(data,"UTF-8");
- 方式一:解决中文乱码
