zoukankan      html  css  js  c++  java
  • Servlet 处理请求

    一:Servlet 处理请求也是通过request来进行处理,类似于python。

    get请求通过request.getparameter("key");key为前端传过来的key,get以 key=val形式进行传递。

    响应以response.getWrite().print("return String")

     1 package ser_Test;
     2 
     3 import javax.servlet.ServletException;
     4 import javax.servlet.http.HttpServlet;
     5 import javax.servlet.http.HttpServletRequest;
     6 import javax.servlet.http.HttpServletResponse;
     7 import java.io.IOException;
     8 
     9 public class Hello_Demo extends HttpServlet{
    10     @Override
    11     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    12         System.out.println("请求已经收到.........");
    13         //接收前端传递参数,方法:req.getparameter();
    14         String user=req.getParameter("username");
    15         String pwd=req.getParameter("pwd");
    16         System.out.println("data:"+user+pwd);
    17         //返回数据,方法resp,getWrite().prin("返回的字符串。)
    18         resp.getWriter().print("data:"+user+pwd);
    19 
    20 
    21     }
    22 
    23     @Override
    24     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    25 
    26     }
    27 }

     注意:

    在返回中文的时候,需要设置response的content-type的编码。建议写在第一行,需要注意设置的参数之间是分号分隔的

    
    
    1 resp.setContentType("text/html;charset=utf8");
    配置文件配置(web.xml) :
    1)注册 servlet使用<servlet>标签<servlet-name>和<servlet-class>子标签来写servlet名字和class名字,注意名字要在web.xml唯一,class要全局路径。
    2)绑定访问路径使用<servlet-mapping>和<servlet>标签同一级。子标签<servlet-name>和<url-pattern> name是servlet的名字,url是访问的路径。
    例子:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <web-app version="2.4"
     3          xmlns="http://java.sun.com/xml/ns/j2ee"
     4          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     5          xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
     6         <servlet>
     7             <!--注册-->
     8             <servlet-name>login_Servlet</servlet-name>
     9             <servlet-class>jd.com.servlet.login_Servlet</servlet-class>
    10         </servlet>
    11         <servlet-mapping>
    12             <!--绑定路径-->
    13             <servlet-name>login_Servlet</servlet-name>
    14             <url-pattern>/login/</url-pattern>
    15         </servlet-mapping>
    16 
    17 </web-app>
    
    
    
     
  • 相关阅读:
    vue使用elementui合并table
    使用layui框架导出table表为excel
    vue使用elementui框架,导出table表格为excel格式
    前台传数据给后台的几种方式
    uni.app图片同比例缩放
    我的博客
    【C语言】取16进制的每一位
    SharePoint Solution 是如何部署的呢 ???
    无效的数据被用来用作更新列表项 Invalid data has been used to update the list item. The field you are trying to update may be read only.
    SharePoint 判断用户在文件夹上是否有权限的方法
  • 原文地址:https://www.cnblogs.com/evilliu/p/8544833.html
Copyright © 2011-2022 走看看