1.http
a.定义:超文本传输协议
b.作用:web服务器与web浏览器之间通信
c.步骤:
①客户端与web服务器建立连接(IP地址与端口号)
②客户端发送http请求(请求资源路径)
③服务器接收客户端的http请求,生成http响应回发
④服务端关闭连接;客户端解析回发响应
2.Web容器:
a.常用:Tomcat、Weblogic、jboss
b.作用:用来管理Servlet
3.Servlet:
a.定义:在服务端运行的Java程序
b.作用:在服务端产生动态内容
c.使用:
①创建Servlet类,继承HttpServlet,重写doGet方法
public class MyFirstServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter out = resp.getWriter(); out.write("<html>"); out.write("<head>"); out.write("</head>"); out.write("<body>"); out.write("<p style=‘color:red‘>this is p</p>"); out.write("</body>"); out.write("</html>"); } }
②配置web.xml文件
<servlet> <servlet-name>myFirst</servlet-name> <servlet-class>com.servlet.MyFirstServlet</servlet-class> </servlet>
③Servlet的映射
<servlet-mapping> <servlet-name>myFirst</servlet-name> <url-pattern>/myfirst</url-pattern> </servlet-mapping>
4.Servlet的生命周期
a.创建与初始化 init()
①默认是在Servlet第一次访问时创建和初始化(单例模式)
②注:在<servlet>标签中的最后加<load-on-startup>1</load-on-startup>以在服务器启动时创建和初始化,其中的1表示优先级,0为默认,数字越小优先级越大
b.服务 doGet()与doPost()
①doGet()对应表单method属性中的get;doPost()对应表单method属性中的post
②注:若重写了service()方法,则不调用doGet()或doPost()
c.销毁 destroy()
①在服务器停止时调用destroy()
d.初始化参数的设定
①设置servlet的初始化参数(在<servlet>标签内书写)
<init-param> <param-name>email</param-name> <param-value>[email protected]</param-value> <init-param>
调用
String email = getServletConfig().getInitParameter("email");
②设置全局上下文的初始化参数(与<servlet>标签平级)
<context-param> <param-name>name</param-name> <param-value>zhangsan</param-value> <context-param>
调用
String name = getServletConfig(). getServletContext().getInitParameter("name");
5.响应
a.错误信息处理
①sendError()方法
response.sendError(500,"服务器内部出现异常");
②配置<error-page>(在<web-app>中书写)
<error-page> <error-code>404</error-code> <location>/404Error.html</location> <error-page>
b.重定向(跳转)
response.sendRedirect("../MyHtml.html");
注:这里实际发送了两次请求
6.请求
a.根据name获取值
String userName = reques.getParameter("userName"); //获取单个元素的value值 String[] favs = reques.getParameterValues("fav"); //获取多个元素的value值(适用于复选框)
b.其他请求的方法
request.getMethod() //获取请求的方法 request.getRequestURI() //获取请求的方法URI request.getRequestURL() //获取请求的URL request.getServletPath() //获取servlet的映射路径 request.getContextPath() //获取servlet中Context的路径 request.getRemoteAddr() //获取请求的IP地址
c.通过url地址传参
<a href="login?userName=zhangsan&userType=1">登陆<a> <!--其中userName和userType都为name的值,zhangsan和1都为value的值-->
d.解决get方式中乱码问题
userName = new String(userName.getBytes("ISO-8859-1"),"utf-8")
e.请求头信息:
Enumeration<String> names = request.getHeadNames(); while(names.hasMoreElements()){ String name = (String)names.nextElement(); String value = request.getHeader(name); }
7.Enum(枚举)
a.作用:规定一定范围的数据取值范围
b.用法:
//申明 public enum WeeK{ Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } //使用 public static void main(String[] args){ test(Week.Sunday); } public void test(Week w){ }
8.文件上传
a.注意:
①表单的提交方式只能是post
②表单必须设置为复合类型表单
<form action="UploadServlet" method="post" ectype="multipart/form-data"> <input type="file" name="photo"/> </form>
③在表单标签中必须要有name属性(<input>中)
b.用法:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //处理文件上传操作 //在硬盘中去创建一个FileItem工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); //文件上传处理类 ServletFileUpload fileUpload = new ServletFileUpload(factory); //设置上传文件的大小,以字节为单位 fileUpload.setFileSizeMax(2*1024*1024); try { List<FileItem> items = fileUpload.parseRequest(request); for(FileItem item : items){ if(!item.isFormField()){ upload(item); }else{ // item.getString(); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void upload(FileItem item){ //将虚拟路径转换为物理路径 // System.out.println(getServletContext().getRealPath("image")); String path = getServletContext().getRealPath("img"); File file = new File(path+"/"+new Date().getTime()+item.getName()); try { item.write(file); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
9.文件下载
String fileName = request.getParameter("file"); response.setHeader("Content-Disposition", "attachment; filename=" +fileName ); String path = getServletContext().getRealPath("img"); File file = new File(path + "\\"+fileName); FileInputStream inputStream = new FileInputStream(file); ServletOutputStream out = response.getOutputStream(); byte[] bytes = new byte[1024]; int b = 0; while(( b = inputStream.read(bytes))!=-1 ){ out.write(bytes,0,b); out.flush(); } out.close();
10.转发
a.语法:
request.getRequestDispatcher("login.html").forward(request,response);
b.与重定向的区别
①转发:整个过程只发送了一次请求;重定向:发送了2次请求
②转发:地址栏不会发生变化;重定向:地址栏会发生变化
c.转发中的request属性
request.setAttribute("msg","hello"); //属性值为Object类型的 String msg = (String) request.getAttribute("msg");