最近做了一个javabean+servlet+jsp的web开发联系,其中解决了一些问题;
1.在src文件下写的一些类,要在servlet中调用,其中有两个问题需要注意;
1.1想得到一个类结果,要使用try-catch语句控制。
1.2想把类作为对象存进request,一点要保证对象存在。
Student stu=newStudent(id,name,sex,age,weight,hight);
studentDAO s=newstudentDAO();
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 map = new HashMap();这样取出来就方便多了