Java基础学习之Servlet 运用学习

Servlet 简介

Servlet 是什么?

Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层。

使用 Servlet,您可以收集来自网页表单的用户输入,呈现来自数据库或者其他源的记录,还可以动态创建网页。

servlet 的优势:
  • 性能明显更好。
  • Servlet 在 Web 服务器的地址空间内执行。这样它就没有必要再创建一个单独的进程来处理每个客户端请求。
  • Servlet 是独立于平台的,因为它们是用 Java 编写的。
  • 服务器上的 Java 安全管理器执行了一系列限制,以保护服务器计算机上的资源。因此,Servlet 是可信的。
  • Java 类库的全部功能对 Servlet 来说都是可用的。它可以通过 sockets 和 RMI 机制与 applets、数据库或其他软件进行交互。
servlet 的架构:
Servlet 架构






servlet 的配置对象

一 对象获取方式

方式一:

声明一个成员变量保存该对象

通过init方法获取ServletConfig对象

public class Demo01 extends HttpServlet {
	// 声明一个成员变量保存该对象
	private ServletConfig config;
	//给成员变量赋值
	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		super.init(config);
		this.config=config;}
	}

方式二:

直接调用父类的getServletConfig()方法

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 (直接调用父类的方法)
		ServletConfig config2 = this.getServletConfig();
		String value2 = config2.getInitParameter("weige");
		System.out.println(value2);
	}

作用:

获取Servlet的配置信息 此对象是每个Servlet 都具有的;可通过该对象获取servlet的配置信息

private void fun1() {
		System.out.println(this.config);
		//可以通过ServletConfig对象获取Servlet的配置信息
		String value = this.config.getInitParameter("wanglong");
		System.out.println(value);
		//获取多个配置信息
		Enumeration<String> names = this.config.getInitParameterNames();
		while (names.hasMoreElements()) {
		System.out.println(names.nextElement());
		}

servlet 的域对象 

servletContext :作用范围最大的域对象,作用域整个工程项目,并且此对象是个单例对象;

作用:可以利用单例的特点用来传值.该对象内部维护了一个map集合,而且所有的域对象内部都是维护了一个map集合;

1.存值取值  setAttribute  getAttribute   

2.获取全局配置信息

3.可以获取服务器上所有的资源的真实路径  getrealpath()

4.可以进行请求转发

该对象的获取方法

方式一: 通过ServletConfig 对象获取
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext context = this.getServletConfig().getServletContext();
		//向context 保存一个值
		context.setAttribute("username", "wanglong");
	}

方式二:通过父类获取 该方法在ServletConfig 接口中

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext context = this.getServletContext();
		context.setAttribute("user", "我是王老五");
		//获取ServletContext 配置信息
		String value = context.getInitParameter("kuner");
		System.out.println(value);
		
	}

取值:

public class Demo03 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//取出Context域中的值
		ServletContext context = this.getServletConfig().getServletContext();
		Object obj = context.getAttribute("username");
		System.out.println(obj);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
该域对象作用于整个工程,因此在该工程的任意的一个servlet 都可以获取到设置的值.
2.获取服务器上的资源路径

 

如上图在工程下不同的位置新建 a b c 三个properties文件

public class Demo04 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//fun1();
		//读取b and c.properties文件
		String path2 = this.getServletContext().getRealPath("/WEB-INF/classes/com/lanou3g/b.properties");
		String path3 = this.getServletContext().getRealPath("/WEB-INF/c.properties");
		System.out.println(path2);
		System.out.println(path3);
		//读文件
				FileInputStream fis2 = new FileInputStream(path2);
				Properties properties2 = new Properties();
				properties2.load(fis2);	
		        FileInputStream fis3 = new FileInputStream(path3);
		        Properties properties3 = new Properties();
		        properties3.load(fis3);
		     	System.out.println(properties2.getProperty("key"));
		     	System.out.println(properties3.getProperty("key"));
	}
	private void fun1() throws FileNotFoundException, IOException {
		//读取a.properties 文件
		//参数路径是相对于工程名
		String path = this.getServletContext().getRealPath("/WEB-INF/classes/a.properties");
		System.out.println(path);
		//读文件
		FileInputStream fis = new FileInputStream(path);
		Properties properties = new Properties();
		properties.load(fis);
		System.out.println(properties.getProperty("key"));
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

4.请求转发

1.用户只发起了一次请求

2.用户请求是并不知道 网站内部做了什么

public class Demo05 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("借点钱,萧峰兄弟");
		System.out.println("老兄:我没有 ,你去找坤儿");
		//通过context对象获取请求转发器
		//转发: 请求转发只能是站内转发(本工程) 
		//并且转发的路径是相对于你的工程
		RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/demo06");//转发器
		//请求转发
		dispatcher.forward(request, response);
		System.out.println("钱借到了,人傻好办事");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
public class Demo06 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("我是坤儿,我有随便花");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
打印结果如下:

可以看出demo05 的需求被转发到 demo06 但是浏览器上并没有跳转到demo06;

响应 response

  响应行 响应的状态码  200  http协议 1.1

  响应头  告诉浏览器我要做什么操作 ?

         告诉浏览器你需要使用什么编码格式来解析我的响应

  响应体  响应浏览器的内容

响应头设置应用
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Tomcat默认的编码格式是 ISO-8859-1 不支持中文;
		/*response.setCharacterEncoding("utf-8");
		//设置响应头告诉浏览器你需要使用什么编码格式来解析数据
		response.setHeader("Content-type", "text/html;character=UTF-8");*/
		//合并写法 (写Servlet 是第一句先写编码格式)
		response.setContentType("text/html;charset=UTF-8");
		//接到请求后向浏览器写个字符串
		//通过响应对象中的流对象回写
		//注意:;如果你当前在servlet中使用的字符流
		//那么就不能在写字节流了
		PrintWriter writer = response.getWriter();
		writer.write("wanglong你好啊");
	}

响应浏览器内容 下载一张图片;

添加一张图片到工程内;

package com.lanou3g;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
 * 从服务器中下载图片
 *获取服务器的图片路径
 *读文件
 *通过respose 获取字节流回写
 *
 *告诉浏览器(添加响应头)
 *1.我给的这个图片是下载用的
 *2.文件名 文件类型
 * content-disposition attachment;filename=
   content-type image/jpeg/png...
 */
public class Demo08 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String path = this.getServletContext().getRealPath("/WEB-INF/classes/宝宝心里苦.png");
		File file = new File(path);
		String name = file.getName();
		//修改文件名的编码格式
		name = new String(name.getBytes(), "iso-8859-1");
		//添加响应头
		response.setHeader("content-disposition", "attachment;filename="+name);
		response.setHeader("content-type", "image/png");
		//读文件
		FileInputStream fis = new FileInputStream(path);
		ServletOutputStream out = response.getOutputStream();
		int len = 0;
		byte [] b = new byte [1024];
		while ((len = fis.read(b))!=-1) {
			out.write(b, 0, len);
		}
		fis.close();
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

请求重定向

public class Demo09 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//fun1(response);
		//3秒后 跳转一个页面
		//添加一个刷新头
		//response.setHeader("refresh", "3;url=/sh-web-02/demo10");
		response.setIntHeader("refresh", 1);
		PrintWriter writer = response.getWriter();
		writer.write(Math.random()+"  ");
	}
	private void fun1(HttpServletResponse response) {
		System.out.println("我借钱");
		System.out.println("你去找demo10");
		//添加请求重定向  响应头
		//参数二是重定向的 路径(站内站外网址都可以)  站内路径需要带上工程名
		//response.setHeader("location", "/sh-web-02/demo10");
		response.setHeader("location", "http://baidu.com");
		//添加状态码302
		response.setStatus(302);
		System.out.println("借完了");
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
public class Demo10 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("我是demo10---找我借钱吗,门都没有");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

请求重定向

注意: 请求重定向是两次请求

第二次请求是接到第一次请求的响应头之后发生的 可以看到浏览器中denmo09跳转到了demo10


请求 request

请求中的方法

		//获取请求的方式
		String method = request.getMethod();
		System.out.println(method);
		//获取请求的URL
		StringBuffer requestURL = request.getRequestURL();
		System.out.println(requestURL);
		//获取请求的URI
		String requestURI = request.getRequestURI();
		System.out.println(requestURI);
		//获取请求网址的相对路径
		String contextPath = request.getContextPath();
		System.out.println(contextPath);
	

使用 Servlet 读取表单数据 并连接访问数据库

getParameter()您可以调用 request.getParameter() 方法来获取表单参数的值。

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取表单提交的数据
	//通过表单中 name属性 来获取输入框中的数据
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println(username);
		System.out.println(password);
		
		//连接数据库查询
		Connection conn = null;
		PreparedStatement statement  = null;
		ResultSet resultSet = null;
		
		String sql = "select * from user where username=? and password =?";
		try {
			 conn = JDBCUtil.getConnection();
			 statement = conn.prepareStatement(sql);
			 statement.setObject(1, username);
			 statement.setObject(2, password);
			 resultSet = statement.executeQuery();
			 if (resultSet.next()) {
				System.out.println("登录成功 欢迎" + username);
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//关闭资源
			JDBCUtil.closeAll(resultSet, statement, conn);
		}
		
		
	}


猜你喜欢

转载自blog.csdn.net/vlin_fan/article/details/80766545