Karl.Li
Karl.Li

Reputation: 167

Best way to separate javascript and java in jsp

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.

Upvotes: 0

Views: 1285

Answers (5)

Andrea Ligios
Andrea Ligios

Reputation: 50203

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.

Upvotes: 0

Ashish Jagtap
Ashish Jagtap

Reputation: 2819

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

Upvotes: 0

Uooo
Uooo

Reputation: 6334

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.

Upvotes: 0

Silviu Burcea
Silviu Burcea

Reputation: 5348

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.

Upvotes: 0

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?

Upvotes: 2

Related Questions