Servlet共享变量:
存:使用Context、Session、或Request类型的实例调用setAttribute("varName",object)方法,将共享的变量存储到对象中。
取:通过实例 的getAttribute("varName")方法来获得变量。
注意:
在servlet的dopost方法(传入参数[HttpServletRequest request,HttpServletResponse])中
利用
this.getServletContext()获取 ServletContex类型的引用
this.getSession() 获取 HttpSession类型的引用
request 是HttpServletRequest类型的引用
这三个引用指向同一个实例
可利用setAttribute、getAttribute方法存取变量。
Servlet转发:
在dopost方法中 利用request.getRequestDispatcher("/dispatch").forward(request,response);
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
//操作代码
/***************重点*************/
request.getRequestDispatcher("/dispatch").forward(request,response);
}
Servlet跳转:
利用response.sendRedirect("/dispatch"); 新的页面有新请求,
新产生了一个HttpServletRequest,先前的对象无了,先前存储的Attribute也没有了。
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
//操作代码
/***************重点*************/
response.sendRedirect("/dispatch");
}
注:
【/dispatch是一个url】
【/是指webcontent目录为根】
Servlet连接数据库使用JDBC
包:数据库驱动加载需要导入mysql-connector-java-版本号-bin.jar包
位置:将此包放在 WEB-INF/lib下即可
经典代码段。以下不代表逻辑关系,也不能直接运行,只是一个示意,注意双引号内的内容。
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");
html提交到servlet
web.xml配置的url是"/XXX"
假如我们的项目名叫做“ABC”
html中:
form标签 需要用action="XXX" --------相对路径的方法
或者action=“/ABC/XXX” ----------------绝对路径的方法