更新时间:2022-06-23 12:05:24 来源:极悦 浏览1025次
与 ABAP 中类似的逻辑。
使用名为“HelloWorldServlet”的 servlet 在 Java 中创建一个动态 Web 项目:
将以下实现源代码复制到 Servlet 中:
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloWorldServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> allowedUserId = Arrays.asList(getServletContext().getInitParameter("userIds").trim().split(","));
String clientOrigin = request.getHeader("origin");
String ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null) {
ipAddress = request.getRemoteAddr();
}
String userId = request.getParameter("userId");
if( userId != null)
userId = userId.trim();
if( allowedUserId.contains(userId)){
response.setHeader("Access-Control-Allow-Origin", clientOrigin);
}
if( ipAddress.equals("0:0:0:0:0:0:0:1"))
response.getWriter().println("local one");
else
response.getWriter().println("Hello World!");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
WEB-INF 文件夹中的 web.xml,允许的用户 ID 列在节点 <context-param> 中。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>JerryTest</display-name>
<welcome-file-list>
<welcome-file>Hello</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>userIds</param-name>
<param-value>i042416,i042417,i042418</param-value>
</context-param>
<servlet>
<description></description>
<display-name>HelloWorldServlet</display-name>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>helloworld.HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<!-- http://stackoverflow.com/questions/4140448/difference-between-and-in-servlet-mapping-url-pattern -->
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/Hello</url-pattern>
</servlet-mapping>
</web-app>
现在使用列表中未包含的用户 id 访问 servlet,请求失败:
并通过请求中指定的允许用户 ID 执行正面测试:
请求成功处理并返回浏览器:
0基础 0学费 15天面授
Java就业班有基础 直达就业
业余时间 高薪转行
Java在职加薪班工作1~3年,加薪神器
工作3~5年,晋升架构
提交申请后,顾问老师会电话与您沟通安排学习