简体   繁体   中英

JSP String To Java Class

I have a jsp page. Page have a requested field as string.

<% String token = ""+request.getParameter(); %>

In this jsp page also has a test class.

 <%!
      public static String usetoken()
          {
              String testtoken = ""+token;
          }

 %>

This usetoken class can not solve the token string. How can I solve that ? I need to call a string inside a class which inside a jsp page.

Thanks,

Firstly, as you may know, a jsp will be compiled to a servlet. All scriptlet code will be "inserted" into service() method and all declarations will be inserted to servlet class. So, for your situation, we'll have something like this(simplified):

public class FooServlet extends HttpServlet {

    public static String useToken() {
        String testtoken = ""+ token;
        return testtoken;
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String token = ""+ request.getParameter();
    }
}

As you see, userToken() method can't know about 'token' local variable inside service() method.

Also, you can't access HttpServletRequest in your jsp declaration, because it's a parameter of service() method.

BUT

You can use JSTL for something like this. You can declare variable:

<c:set var="token" value="${requestScope.token}"/>

And access it anywhere in your jsp using expression language(EL):

${token}


If you don't know, writing scriptlets inside your jsp considered bad practice . You need to do business logic somewhere outside and provide view as jsp. So use JSTL, your custom tags and EL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM