创建Servlet对象 响应对象 验证码

来源:互联网 发布:java压缩包文件名乱码 编辑:程序博客网 时间:2024/06/07 00:21
ServletConfig对象:配置对象

在Servlet初始化时 由服务器创建其子类对象给init()
功能:
a.获取Servlet初始参数
String getInitParameter(String name)
Enumeration getInitParameterNames();(迭代器)
b.获取全局域ServletContex对象
ServletContex对象是由服务器创建出来的


可以配置Servlet的创建机,在web.xml的<servlet>标签中配置<load-on-startup>
负整数:默认值-1,在第一次被访问时创建
非负整数:在服务器开启时创建(初始化大量数据时使用),数字越小,优先级越高

import java.io.IOException;import java.util.Enumeration;import javax.servlet.Servlet;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;public class demo1 implements Servlet{public void destroy() {// TODO Auto-generated method stub}public ServletConfig getServletConfig() {// TODO Auto-generated method stubreturn null;}public String getServletInfo() {// TODO Auto-generated method stubreturn null;}public void init(ServletConfig config) throws ServletException {//获取初始化参数 获取姓名 年龄String name = config.getInitParameter("username");String age = config.getInitParameter("age");//迭代器Enumeration<String> names = config.getInitPrameterNames();while(names.hasMoreElements()){String key = names.nextElement();String value = config.getInitParameter(key);System.out.println(value);}}public void service(ServletRequest request, ServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stubSystem.out.println("请求来了");//获取请求者IPString ip = request.getRemoteAddr();response.getWriter().write(ip);}}


<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  <display-name></display-name>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list>    <servlet>  <servlet-name>demo01</servlet-name>  <servlet-class>Servlet.demo1</servlet-class>  <!-- -定义变量 -->  <init-param>  <param-name>username</param-name>  <param-value>zhanngsan</param-value>  </init-param>  <init-param>  <param-name>age</param-name>  <param-value>20</param-value>  </init-param>    <!-- 创建机,启动时初始化 --><load-on-startup>0</load-on-startup>    </servlet>    <servlet-mapping>  <servlet-name>demo01</servlet-name>  <url-pattern>/demo1</url-pattern>  </servlet-mapping>  </web-app>




a.ServletContext:全局域对象
      统管整个资源,在一个资源内可以共享数据
         String getServletName();获取web.xml配置的Servlet的名字

import java.io.IOException;import javax.servlet.Servlet;import javax.servlet.ServletConfig;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;public class ConfigDemo implements Servlet{public void destroy() {// TODO Auto-generated method stub}public ServletConfig getServletConfig() {// TODO Auto-generated method stubreturn null;}public String getServletInfo() {// TODO Auto-generated method stubreturn null;}public void init(ServletConfig config) throws ServletException {//获取全局域对象ServletContext context = config.getServletContext();//设置 context.setAttribute("num", "100");//获取String  value = (String) context.getAttribute("num");System.out.println(value);//获取web.xml中的Servlet名字String servletName = config.getServletName();System.out.println(servletName);}public void service(ServletRequest arg0, ServletResponse arg1)throws ServletException, IOException {// TODO Auto-generated method stub}}


b:HttpSession 会话域
可以包含多次请求和多次响应 并且可以在多次请求和响应间共享数据
C:ServletRequest:请求域
在一次请求中共享数据
d:pageContex:页面域
在一个页面间共享数据




request和response对象都是由服务器创建,管理,销毁,由我们使用


响应对象
处理get请求和post请求
import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class MyServlet_01 extends HttpServlet {// 处理get请求public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println(request);System.out.println(response);}// 处理post请求public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);}}


写一个网页表单信息,请求get方法

<!DOCTYPE html><html>  <head>    <title>MyHtml.html</title>    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="this is my page">    <meta http-equiv="content-type" content="text/html; charset=UTF-8">        <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->  </head>  <!-- -提交链接的虚拟路径 -->>  <form action = "/httpServlet/httpDemo" method="post">  用户名<input type = "text" name = "username" placeholder="请输入用户名"><br>  密码<input type = "password" name = "password" placeholder="请输入密码"><br>  <input type = "submit" value = "提交">  <input type = "reset" value="重置"><br>        </form>    <body>     </body></html>


import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class httpDemo extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("get请求");}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//手动添加this.doGet(request, response);System.out.println("post请求");}}


响应字符串


response.getWriter().writer(String str);
   会产生乱码:浏览器和服务器的编码不一致 网页上显示????
   tomcat的默认编码是ISO-8859-1
response.setContentType("text/html;charset=utf-8");public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//响应一句话//设置响应回去的编码response.setContentType("text/html;charset=utf-8");response.getWriter().write("欢迎进入");//网页上显示????}这样显示出来的就是中文








验证码:
import java.awt.Color;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.IOException;import java.io.PrintWriter;import java.util.Random;import javax.imageio.ImageIO;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.sun.org.apache.commons.digester.rss.Image;public class yanzhengmaDemo extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//验证码边框int width = 150;int height = 75;//创建一个图片对象 参数 类型BufferedImage img = new BufferedImage(width, height,BufferedImage.TYPE_INT_BGR);//美化图片//获取画笔Graphics g = img.getGraphics();//设置画笔的颜色g.setColor(Color.BLUE);//填充背景g.fillRect(0, 0, width, height);//给图片上写字g.setColor(Color.green);String msg = "abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";//随机取Random random = new Random();for(int i = 0 ; i<4 ; i++){//生成随机角标int nextInt = random.nextInt(msg.length());//拿着随机角标去字符串获取四个字符char c = msg.charAt(nextInt);g.drawString(c+"", width/5*i, height/2);}//写出这张图片ImageIO.write(img, "jpg", response.getOutputStream());}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doGet(request, response);}}



<%@ 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>    <!-- 设置一个点击事件 -->    <img src = "/httpServlet/imgDemo" id = "s1" onclick="change()">        <!-- -超链接   表示跳转到本地-->    <a href="javascript:void(0)" onclick="change()">看不清换一张</a>  </body>  <script>    function change(){//实际上地址不发生变化  只是为了骗浏览器 不然的话验证码刷新后 网页也进行刷新 用户体验差  document.getElementById("s1").src = "/httpServlet/imgDemo?imgpath="+new Date().getTime();  }      </script></html>http://localhost:8080/httpServlet/index.jsp






获取文件:
package Servlet;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class GetLujing extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {ServletContext context = this.getServletContext();//服务器路径String realPath = context.getRealPath("/");System.out.println("服务器路径:"+realPath);//D:\笔记\36\20171015-XML和tomcat\tomcat服务器课件\tomcat服务器软件\apache-tomcat-7.0.26\webapps\ServletConfig\//获取a b c 文件 注意:我要获取的是文件  所以需要new  FileFile filea = new File(context.getRealPath("/WEB-INF/a.txt"));//WEB-INF下的文件File fileb = new File(context.getRealPath("/b.txt"));//工程文件File filec = new File(context.getRealPath("/ServletConfig/src/Servlet/c.txt"));//全路径名(包下的文件)System.out.println(filea);System.out.println(fileb);System.out.println(filec);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doGet(request, response);}}











原创粉丝点击