0

我正在尝试从缓冲阅读器中检查字符串值是否与浏览器中的用户输入匹配。如果用户输入 localhost:9999/getMusic 数据输出正常,但是我试图确保只有 /getMusic 或 /getMusic= 被传递,而不是给出我制作的 404 错误页面。现在,如果我输入 /getSomething,我只能得到 404。

如果我输入例如 /getMusicc (最后有两个 c),我希望它也给我一个 404,但它不会给我。我意识到它是因为 .contains 方法,但我不知道还能使用什么。基本上我需要与我指定的内容匹配的确切字符串值。我尝试使用 .contentsEqual 没有运气。

String line = reader.readLine();
        if(line !=null){
        System.out.println("[CLIENT] " + soc.getInetAddress().getHostName() 
                + " - " + soc.getInetAddress().getHostAddress() + " requesting: " + line);

        //the first line should be: GET /path HTTP/1.1
        if (line.startsWith("GET ")&& (line.endsWith("HTTP/1.0")||line.endsWith("HTTP/1.1"))){
            String path = line;//check this

            OutputStream output = soc.getOutputStream();
//here is my problem below...
            if(path.contains("/getMusic") || path.contains("/getMusic=")){
                String type = "";

                if (path.contains("/getMusic=rap")){
                    type = "Rap";
                }

我应该补充一点,字符串只有几个单词,我要测试的值在所有这些单词的中间。IE GET /getMusic HTTP1.1。只有 /getMusic 应该被测试。

在第一级上运行良好,但是如果我想测试 /getMusic=rap 它不起作用。

  if(path.matches(".*/getMusic=?(\\s+.*)?")){
                String type = "";


                if(path.matches(".*/getMusic=rap")){
                    type = "Rap";
                }
4

3 回答 3

0

One easy solution is to use regex to test the end of your string. Something like:

If(str.matches(".*/getMusic=?$")) {}

This will test that anything can appear before the phrase '/getMusic', but nothing can appear after!

于 2013-04-08T09:44:07.203 回答
0

代替:

if(path.contains("/getMusic") || path.contains("/getMusic="))

你应该使用:

if(path.matches("^.*?/getMusic=?.*$"))
于 2013-04-08T09:43:43.380 回答
0

您可以使用

if(path.matches(".*/getMusic=?(\\s+.*)?"))

基本上是

.* - 要测试的字符串之前的任何内容
/getMusic - 你知道这是什么
=?- 检查“=”是否可选存在
(\s+.*)?- 如果它可选地包含一个或多个空格 + 空格后面的任何内容

于 2013-04-08T10:02:53.237 回答