作业一:servlet技术及应用

servlet技术及应用

  • 1.Servlet将请求转发给另一个Servlet的方法。
    • 1.input.html
    • 2.com.demo.Student类
    • 3.FirstServlet
    • 4.SecondServlet
  • 2.使用ServletConfig检索Servlet的初始化参数。
    • 1.ConfigDemoServlet
  • 3.为ServletContext配置初始化参数
    • 1.在Web.xml中:
  • 4.编写一个名为CountServlet的Servlet程序:
    • 1.CountServlet

1.Servlet将请求转发给另一个Servlet的方法。

【步骤1】创建一个名为input.html的HTML页面,其中包括一个表单,表单中包含两个文本域,分别供用户输入学号和姓名,该页面也包含提交和重置按钮。
【步骤2】 定义一个名为com.demo.Student类,其中包括学号sno和姓名name两个private的成员变量,定义访问和修改sno和name的方法。
【步骤3】编写名为FirstServlet的Servlet,要求当用户在input.html中输入信息后点击“提交”按钮,请求FirstServlet对其处理。在FirstServlet中使用表单请求参数(学号和姓名)创建一个Student对象并将其作为属性存储在请求作用域中,然后通过请求对象的getRequestDispatcher()方法获得RequestDispatcher()对象,将请求转发到SecondServlet。
【步骤4】在SecondServlet中取出请求作用域中存储的Student对象,并显示输出该学生的学号和姓名,5秒钟之后,自动返回input.html页面。

1.input.html

<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="FirstServlet" method="get">
 
学号:<input name="username"><br>
<br>
姓名:<input name="password"><br>
  <br>
<input type="submit" value="登录 "/>   
<input type="submit" value="取消">   
</form>

</body>
</html>

2.com.demo.Student类

package com.demo;

public class Student {
 private String sno;
 private String name;
public Student(String sno, String name) {
	// TODO Auto-generated constructor stub
	this.sno=sno;
	this.name=name;
}
public String getSno() {
	return sno;
}
public void setSno(String sno) {
	this.sno = sno;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
}

3.FirstServlet

package com.demo;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, 
HttpServletResponse response) 
throws ServletException, IOException {
		String sno = request.getParameter("sno");
		String name = request.getParameter("sname");
		Student student = new Student(sno,name);
		request.setAttribute("student", student);
		RequestDispatcher rd = request.getRequestDispatcher("/SecondServlet");
		rd.forward(request, response);
	  }
}

4.SecondServlet

package com.demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/SecondServlet")
public class SecondServlet extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {
		Student student= (Student)request.getAttribute("student");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();	
		out.println("学生信息");
		out.println("学号:"+student.getSno()+"
"
); out.println("姓名:"+new String( student.getName().getBytes("iso-8859-1"),"UTF-8")+"
"
); //out.println("返回输入页面"); response.setHeader("Refresh","5;url=input.html"); } }

2.使用ServletConfig检索Servlet的初始化参数。

【步骤1】编写ConfigDemoServlet程序,通过注释为其添加初始化参数email、telephone,在Servlet中读取该servlet的名称和初始化参数email、telephone,并将这两个参数的值在响应的HTML文本中输出。
【步骤3】在浏览器的地址栏中输入下面URL请求该Servlet:
http://localhost:8080/ homework01/configDemo.do

1.ConfigDemoServlet

package com.demo;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

@WebServlet(name="ConfigDemoServlet",
		urlPatterns = {"/config-demo"}, 
		initParams = { 
			@WebInitParam(name = "email", value = "[email protected]"), 
			@WebInitParam(name = "telephone", value = "8899123")
		})
public class ConfigDemoServlet extends HttpServlet{
String servletName = null;
ServletConfig config = null;
String email = null;
String telephone = null;
String admin_email=null;
String admin_tel=null;
private ServletContext servletContext;

public void init(ServletConfig config) {
this.config = config;
servletName = config.getServletName();
email = config.getInitParameter("email");
telephone = config.getInitParameter("telephone");
}
public void doGet(HttpServletRequest request, 
HttpServletResponse response)
                           throws ServletException,IOException{  
response.setContentType("text/html;charset=UTF-8");
//写入日志文件
this.servletContext=config.getServletContext();
String admin_email = servletContext.getInitParameter("admin-email");//利用名字获取值
String admin_tel = servletContext.getInitParameter("admin-tel");//利用名字获取值

PrintWriter out = response.getWriter();
out.println("");
out.println("配置对象");
out.println("Servlet名称:"+servletName+"
"
); out.println("Email地址:"+email+"
"
); out.println("电话:"+telephone); out.println(""); out.println("

"
); out.println("web.xml文件中的初始化参数值admin-email: " + admin_email); out.println("

"
); out.println("web.xml文件中的初始化参数值admin-tel: " + admin_tel); } }

3.为ServletContext配置初始化参数

在web.xml文件中为当前web应用添加两个名为admin-email和admin-tel的ServletContext初始化参数,在ConfigDemoServlet中获取这两个参数的参数值,使用ServletContext对象将admin-email和admin-tel的参数值写入日志文件中,并查看日志文件。

1.在Web.xml中:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>homework1</display-name>
  
  <!-- 配置初始化参数 -->
  <context-param>
  	<param-name>admin-email</param-name>
  	<param-value>hacker@163.com</param-value>
  </context-param>
  
  <context-param>
  	<param-name>admin-tel</param-name>
  	<param-value>8899123</param-value>
  </context-param>
  
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

4.编写一个名为CountServlet的Servlet程序:

1)使用成员变量保存该Servlet被访问的次数,试打开多个浏览器窗口模拟多个用户同时访问该Servlet,观察该Servlet被访问次数的变化。
2)修改该Servlet,通过ServletContext属性保存被多用户同时访问的次数,体会用ServletContext在应用作用域共享数据的方法。

1.CountServlet

package com.demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class countServlet1
 */
@WebServlet("/CountServlet")
public class CountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public CountServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置字符编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		
		
		//获取全局的共享数据
		ServletContext servletContext = this.getServletContext();
		
		//获取计数器count
		Integer count = (Integer) servletContext.getAttribute("count");
		
		//如果获取的计算器对象为空 ,说明是第一次访问,并将count,放入servletCount
		if( servletContext.getAttribute("count") == null) {
			count = 1;
			servletContext.setAttribute("count", count);
		}else {
			//否则就不是第一次访问,将登陆的计数器进行加1的数据更新
			servletContext.setAttribute("count", count+1);
		}
		
		//将登陆的次数显示在页面上
		PrintWriter out =response.getWriter();
		out.print("\r\n" + 
				  "\r\n" + 
				  "\r\n" + 
				  "\r\n" + 
				  "登陆网页次数统计\r\n" + 
				  "\r\n" + 
				  "");
		out.print("

"); out.print("您是第 "+ servletContext.getAttribute("count")+"位访客"); out.print("

"); out.print("\r\n" + ""); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

你可能感兴趣的:(Web程序开发与设计)