public String userLogin() throws Exception{
//获得页面传入的名称
String usname=petinfo.getPetName().trim();
//获得页面传入的密码
String upwd=petinfo.getPetPassword().trim();
if(usname!=null&&!"".equals(usname)){
System.out.println("aaaaa");
}
else{
System.out.println("11111");
response.getWriter().println("<script>alert('名称不能为空!');history.back();</script>");
}
if(upwd!=null&&!"".equals(upwd)){
System.out.println("bbbbb");
}
else{
System.out.println("22222");
response.getWriter().println("<script>alert('密码不能为空!');history.back();</script>");
}

return "userLogin";
}我在 action中写了这个,其中 response.getWriter().println("<script>alert('密码不能为空!');history.back();</script>");  有问题吗? 为什么我在页面上输出的时候在空值的情况下 可以打出 11111,22222 就是不能弹出alert()中的值???

解决方案 »

  1.   

    在action里不能这么写吧,如果出错的话让它返回到一个错误页面
    在那个错误页面里显示一下这个<script>alert('名称不能为空!');history.back(); </script>"); 
    试试!
      

  2.   

    这是Struts2,不是servlet,struts2主要是起Controller作用,也就是处理请求,调用业务逻辑,转发请求,struts2会通过userLogin转发到你配置好的页面,肯定不会出现javascript的脚本。
      

  3.   

    <script>alert('名称不能为空!');history.back(); </script>"); 
    以上代码写在userLogin对应的jsp页面
      

  4.   

    这样输出的之所以一个字符串,不是可执行脚本,是不会执行的
    定一个hidden,给这个hidden指定值,写一个js方法,检测这个hidden的值,当这个hidden的值变化的时候,执行js方法,js方法里面放history.back(); 
      

  5.   

    action不可以当Servlet用的吧
    楼主好多response
    这样是不对的
      

  6.   

    你这个写法太不Struts2了。
    利用Struts2里的workflow interceptor,
    当你有ActionError或者FieldError时跳转到"input"。public PetInfo petinfo;public String userLogin() { 
    //不要加throws Exception,只加可预测的错误
        //获得页面传入的名称 
        String usname=petinfo.getPetName().trim(); 
        //获得页面传入的密码 
        String upwd=petinfo.getPetPassword().trim(); 
        if(usname!=null&&!"".equals(usname)){ 
            System.out.println("aaaaa"); 
        } 
        else{ 
            System.out.println("11111"); 
            addActionError("名称不能为空"); 
        } 
        if(upwd!=null&&!"".equals(upwd)){ 
            System.out.println("bbbbb"); 
        } 
        else{ 
            System.out.println("22222"); 
            addActionError("密码不能为空!"); 
        }     return "userLogin"; 
    } 在你的view页面里加上
    <s:actionerror/>