The execution of JSP and JavaScript in different environments (server side for JSP, client side for JavaScript) makes it impossible for them to be executed in the order they appear in your code.
var val1 = document.getElementById('userName').value;
<c:set var="user" value=""/> // How can I set val1 here?
When JSTL code is executed at the server side, the server treats JavaScript/HTML codes as plain texts. Any generated content from the JSTL code will be included in the resulting HTML alongside your other JavaScript/HTML codes. However, the browser only renders HTML and executes JavaScript codes without any knowledge of JSTL code.
For instance,
<script type="text/javascript">
<c:set var="message" value="Hello"/>
var message = '<c:out value="${message}"/>';
</script>
When this content is being rendered by the browser, it looks like:
<script type="text/javascript">
var message = 'Hello';
</script>
I hope this explanation clarifies things for you.