jsp中java代码可以写在js中吗?

JavaScript012

jsp中java代码可以写在js中吗?,第1张

答:jsp中java代码可以写在js中。

示例如下:

<script type="text/javascript">

function check(){

var username=document.getElementById("username")

var username=document.getElementById("password")

//java代码块

<%

String sql="select * from Manger"

String user

String pass

ResultSet rs=DBHelper.query(sql)//sql代码已经写好在被的类中,此处为直接调用!!

while(rs.next()){

user=rs.getString("username")

pass=rs.getString("password")%>

if(username.value=="<%=user %>" &&passsword.value=="<%=pass%>")

{

return true

}else if(username.value==""|| password.value==""){

username.setCustomValidity("账号或密码不能为空")

return false

}else{

username.setCustomValidity("账号或密码错误,请从新输入")

return false

}

<%

}

%>

}

</script>

jsp代码中间插入JS代码的格式,代码如下:

<script lanuage="javascript">function justiice(t){

if (t>0){

alert("account is exsiting")

 }

}

else{

'redirect the other page!'

}

</script>

<%int i=conn.executeQuery("select count(1) fromtable where id='输入帐户'")%>

<input type=button onclick=justiice('<%=i%>')>

<! But i want to tell you that the sql statement you can't insert into your current page, it may incur SQL injection,Be cautious!>

最好是单独写个文件夹,然后写个js文件放置然后在jsp页面通过<script src="js文件的相对地址">来导入。当然你写在<head>里也可以。最好能不写在页面里就不写在页面里。。实现一般都用外部js文件导入。一是分离开,方便修改。二是可以js代码复用。你想啊,只写在一个jsp里,如果我另一个要用怎么便????你复制过去吗???这个和java里的封装方法一个思想所以建议通过外部 js导入 像楼主提供的这种简单的js。一般直接放在页面中即可。我说的是方法比较多的情况才用外部文件。这个也不难区别的。