0

Example

<%
Editor editor = (Editor)session.getAttribute("editor");
if(null == editor){
%>
<script type="text/javascript">
window.parent.location.href = "login.jsp";
</script>
<%
}
%>

It appears lots of time like this

use java code to get something....
if(something is true){
    Then do something with javascript;
}

So, I need a good impl to separate js,java in jsp file.

Karl.Li
  • 169
  • 12

5 Answers5

2

Use Tag libraries in JSPs instead of Java code. The code that you posted is simple and can be achieved with the simple core tag. There are so many open source tag libraries which you can use to avoid java code in JSP. It will look cleaner once you start use them. Check the below link for the similar question:

How to avoid Java code in JSP files?

Community
  • 1
  • 1
0

For this use case, you can check your Editor inside the servlet(you can get the session from the request) and redirect to the login from it.

Tag libraries will also solve this, but it still feels like Java inside JSP if you ask me.

Silviu Burcea
  • 5,103
  • 1
  • 29
  • 43
0

Based on the code given, I would suggest not to check for authentication in every of your JSPs, but use a filter instead. In your filter, check whatever you need to know, and sent a HTTP redirect to the loginform instead.

Uooo
  • 6,204
  • 8
  • 36
  • 63
0

I think the best way to use java code in jsp by using JSTL tags. you can learn more about JSTL here

just include following line in your jsp file

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

and your code will be like

function redirectFunction() {   
    <c:choose>
        <c:when test="${empty sessionScope.editor}">
            window.parent.location.href = "login.jsp";
        </c:when>
        <c:otherwise>
            //other code will go here.
        </c:otherwise>
    </c:choose>
}

also you can write this function in one demo.js file and include it into your jsp file as

<script type="text/javascript" src="javascript/demo.js"></script>

that all

Ashish Jagtap
  • 2,799
  • 3
  • 30
  • 45
0

Best way to separate javascript and java in jsp

Don't use Java in JSP.

Forget about Scriptlets, avoid Business Logic in JSP, use JSTL (or OGNL in Struts) to perform Presentation Logic only.

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243