Servlet生命周期
Servlet生命周期基本上是和项目开发是一样的。从项目成立、开发、运维、消亡四个过程,servlet也是一样的 ,区别只在于servlet生命周期只有三个阶段,即:初始化、服务、销毁 ,以下为servlets生命周期代码,仅为参考:
//此时的Servlet要继承 javax.servlet.http.HttpServlet 下的HttpServlet
public class Servlet extends HttpServlet{
//初始化
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
}
//服务
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.service(arg0, arg1);
}
//最后销毁 销毁之后的Destory会被JVM中的垃圾回收器回收
@Override
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
}
}
do Get 方法 和do Post 方法有啥区别?
do Get方法和do Post方法的大体的作用是一致的;使用表单提交数据到服务器的时候会调用这两个方法,区别就在于:
区别一:
doGet方法提交的数据大小是有一定的限制的,他只能提交1M左右的数据;如果想提交较大的数据或者提交文件则会受到限制,此时我们应调用do Post方法,达成目的;
区别二:
get传递数据,是将传递的数据按照”key,value”的方式跟在URL的后面来达到传送的目的;在网页的跳转过程中是有显示的,而post传递数据是通过http请求的附件进行的,在URL中并没有显示。
部署Servlet
部署servlet , 我们可以将SQL ,Java脚本以及jsp结合起来,做一个完整的登录网页 , 实现请求服务器的流程
代码如下:
附图: 通过Servlet实现页面的登录和注册
注册页面(脚本)
注册对应jsp代码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="loginServlet" method="post">
用户名:<input type="text" name = "userName" ><br>
密码:<input type="text" name="pwd" ><br>
姓名:<input type="text" name="name" ><br>
年龄:<input type="text" name="age" ><br>
<input type="submit" name="sub" value="注册">
<input type="reset" name="res" value="重置">
</form>
</body>
</html>
登录页面如下
其实登录代码也注册代码基本原理相似,重要的是JDBC这块内容不同,注册执行的是一个数据库INSERT语句,而登录则是执行的一个SELECT操作
代码如下
jsp代码只需保留用户名和密码即可