web学习02

获取servletConfig对象

ServletConfig对象(每个servlet都有)

获取方式一:

通过ServletConfig对象  获取servlet的配置信息

还可以获取多个配置信息


public class Demo01 extends HttpServlet {
	private ServletConfig config;
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		this.config = config;
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println(config);
		String value = this.config.getInitParameter("wanglong");
		System.out.println(value);
		Enumeration<String> values = this.config.getInitParameterNames();
		while (values.hasMoreElements()) {
			System.out.println(values.nextElement());
		}
	
}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

获取方式二:

直接调用父类的方法

ServletConfig myConfig = this.getServletConfig();
String value = myConfig.getInitParameter("dahai");

域对象

 域表示一定的范围内 有作用的对象

 ServletContext(作用范围最大的域对象) 域对象

 作用于整个工程(项目) 都能使用该对象

 并且整个项目只有一个该对象 是单例对象

 作用:利用单例的特点 可以进行传值

 该对象 内部维护了一个map集合

 注意:所有的域对象内部都是维护了一个map集合

获取ServletContext对象

先在web-xml添加配置信息:

       <init-param>
  		<param-name>wanglong</param-name>
  		<param-value>znb</param-value>
  	</init-param>
  	<init-param>
  		<param-name>dahai</param-name>
  		<param-value>zsb</param-value>
  	</init-param>
方式1:通过ServletConfig对象来获取

public class Demo02 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletConfig servletConfig = this.getServletConfig();
		ServletContext context = servletConfig.getServletContext();
		context.setAttribute("userName", "wanglong");
		Enumeration<String> attributeNames = context.getAttributeNames();
	    while (attributeNames.hasMoreElements()) {
			System.out.println(attributeNames.nextElement());
		}
}

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

}

方式2: 通过父类来获取 该方法在servletConfig

ServletContext context = this.getServletContext();
String value = context.getInitParameter("kuner");
System.out.println(value);

作用:

 1.存值取值

 2.获取全局配置信息

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

 真实路径(在服务器上的路径)getRealPath()

 4.可以进行请求转发


获取服务器上的资源路径

路径是相对于工程名来填的 文件位置不同路径就不同

读取a文件:a和包同级

	        String contextPath = this.getServletContext().getContextPath();
		String path = this.getServletContext().getRealPath("/WEB-INF/classes/a.properties");
		System.out.println(contextPath);
		System.out.println(path);
		FileInputStream fis = new FileInputStream(path);
		Properties properties = new Properties();
		properties.load(fis);
		System.out.println(properties.getProperty("key"));

b在包下:

String path1 = this.getServletContext().getRealPath("/WEB-INF/classes/com/lanou3g/b.properties");

c在web-inf下:

String path2 = this.getServletContext().getRealPath("/WEB-INF/c.properties");

请求转发

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

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

通过Context对象获取请求转发器

注意:请求转发只能是站内转发 转发的路径是相对于你的工程的

                System.out.println("我是Demo05 借钱");
		RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/demo06");
		dispatcher.forward(request, response);
		System.out.println("钱借到了");
System.out.println("我是Demo06 借给你");

打印:

我是Demo05 借钱

我是Demo06 借给你

钱借到了


响应response

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

响应头

告诉浏览器我要做下载的操作

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

响应体 响应浏览器的内容

tomcat 默认的编码格式 iso-8859-1

response.setCharacterEncoding("utf-8");

设置响应头(告诉浏览器使用什么格式解析数据)

response.setHeader("Content-type", "text/html;charset=UTF-8");

二合一写法(之后再写servlet 第一个就写这个)

response.setContentType("text/html;charset=utf-8");

接到请求后 向浏览器写个字符串

 通过响应对象中的流对象 回写

reponse.getoutputstream  两者只能用一个

                PrintWriter writer = response.getWriter();
		writer.write("aaa");

从服务器下载图片

1.告诉浏览器图片是下载用的(添加响应头)

2.告诉浏览器文件名字 文件类型

public class Demo08 extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doPost(req, resp);
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
		ServletContext application =this. getServletContext();
		String path = application.getRealPath("/WEB-INF/classes/tz.png");
		File file =new File(path);
		String name = file.getName();
		byte[] bs= name.getBytes("iso-8859-1");
		response.setHeader("content-disposition", "attachment;filename="+name);
		response.setHeader("content-type", "image/png");

		FileInputStream fis=new FileInputStream(path);
		ServletOutputStream sos = response.getOutputStream();
		int len=0;
		byte[] b=new byte[1024];
		while ((len=fis.read(b))!=-1) {
			sos.write(b, 0, len);
		}
		sos.close();
	}
}

请求重定向 响应头

参数时重定向的路径(栈内栈外的网址都可以)

站内的路径带上工程名

注意:请求重定向是两次请求 第二次请求是接到了第一次响应头之后发生的

                System.out.println("借钱");
		System.out.println("找demo09");
		resp.setHeader("location", "/sh-web-02/demo10");
		resp.setStatus(302);
		System.out.println("借完了");
System.out.println("haha-demo10");
打印:

借钱

找demo09

借完了

haha-demo10


3秒后跳转一个页面

resp.setHeader("refresh", "3;url=/sh-web-02/demo10");

每隔一秒刷新页面并随机输入数字

                resp.setIntHeader("refresh", 1);
		PrintWriter writer = resp.getWriter();
		writer.write(Math.random()+"");

解决响应乱码

解决请求乱码

response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");

获取请求的方式

String method = request.getMethod();
System.out.println(method);

获取请求的url

StringBuffer url = request.getRequestURL();
System.out.println(url);

获取请求的uri

String uri = request.getRequestURI();
System.out.println(uri);

获取请求网址的相对路径

String contextPath = request.getContextPath();
System.out.println(contextPath);

登录

public class Demo11 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		String name = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println(name);
		System.out.println(password);
		
		String sql="seclect * from users where username=?and password=?";
		Connection connection =null;
		PreparedStatement statement = null;
		 ResultSet resultSet =null;
		try {
			connection= JDBCUtil.getConnection();
		   statement = connection.prepareStatement(sql);
		   statement.setObject(1, name);
		   statement.setObject(2, password);
		   resultSet = statement.executeQuery();
		   while (resultSet.next()) {
			System.out.println("登录成功 欢迎"+name);
		}
		   
		} 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, connection);
		}
	}

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

}

















猜你喜欢

转载自blog.csdn.net/cdd233333/article/details/80784027