• servlert调用javabean封装的类与方法注意点


    最近做了一个javabean+servlet+jsp的web开发联系,其中解决了一些问题;

    1.在src文件下写的一些类,要在servlet中调用,其中有两个问题需要注意;

    1.1想得到一个类结果,要使用try-catch语句控制。

    1.2想把类作为对象存进request,一点要保证对象存在。

    Student stu=new Student(id,name,sex,age,weight,hight);
            studentDAO s=new studentDAO();
            Student stu2=null;
            try{stu2=s.find(stu);
            }catch(Exception e){
                e.printStackTrace();
            }
            request.setAttribute("student",stu2);

    Student是一个学生类

    studentDAO是DAO模式封装的sql处理方法

    这里想得到一个处理后返回的Student类,一定要用try-catch语句控制,同时要先给想要的结果赋值,确保request.setAttribute(String name,Obj o)中的存在。

    因为stu2有可能无法返回。

    2.在jsp页面中取得request保存的类:

    Student stu=null;
      try{
       stu=(Student)request.getAttribute("student");
      }catch(Exception e){
      e.printStackTrace();}

    "student"是request中存的Student的类的实例的名字。

    一定要强制转换:stu=(Student)request.getAttribute("student");否则会出现Object不能匹配Student的错误。

    另一种解决方法:

    把数据封装成:Map<string,string> map = new HashMap()<string,string>;这样取出来就方便多了

  • 相关阅读:
    学习笔记
    核心网概要学习
    python基础知识
    python_基础知识_py运算符
    python_基础知识
    将博客搬至CSDN
    poj1182测试数据过了,但A不了,暂时放在这,以后再看
    score——3354
    杭电1241
    杭电1010(WA)
  • 原文地址:https://www.cnblogs.com/cxy2016/p/6610336.html
Copyright © 2020-2023  润新知