概述
一、实验目的:
理解 Servlet 的工作原理,掌握 Servlet 的应用开发方法;掌握常见 Servlet ;
二、实验环境:
1.理解 Servlet 的应用。
2.掌握 Servlet 的编程技术。
3.熟练使用 Eclipse 开发 Servlet 应用
三、实验内容:
(一)用 Servlet 获取表单数据
1. 建立一个 Servlet 文件 accept.java 和一个 register.jsp 文件,实现用 Servlet 实现获取表单数据的功能。
Accept.java
package com.yiibai;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Servlet implementation class accept
*/
@WebServlet("/accept")
public class accept extends HttpServlet {
public String codeToString(String str)
{//处理中文字符串的函数
String s=str;
try
{
byte tempB[]=s.getBytes("ISO-8859-1");
s=new String(tempB);
return s;
}
catch(Exception e)
{
return s;
}
}
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
//设置mime
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println("<HTML><head><title>接收新用户注册</title></head><BODY>");
out.println("这是新用户注册所提交的数据:<br>");
out.println("用户名是:"+codeToString(request.getParameter("username"))+"<br>");
out.println("密码是:"+codeToString(request.getParameter("userpassword"))+"<br>");
out.println("性别是:"+codeToString(request.getParameter("sex"))+"<br>");
out.println("出生年月是:"+request.getParameter("year")+request.getParameter("month")+request.getParameter("day")+"<br>");
out.println("电子邮箱是:"+request.getParameter("email")+"<br>");
out.println("家庭住址是:"+codeToString(request.getParameter("address"))+"<br>");
out.println("</body> </html>");
}
/**
* @see HttpServlet#HttpServlet()
*/
public accept() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Register.jsp
<%@ page contentType="text/html;charset=utf-8"%>
<script language="javascript"> function on_submit()
{//验证数据的合法性
if (form1.username.value == "")
{
alert("用户名不能为空,请输入用户名!");
form1.username.focus(); return false;
} if (form1.userpassword.value == "")
{
alert("用户密码不能为空,请输入密码!");
form1.userpassword.focus(); return false;
} if (form1.reuserpassword.value == "")
{
alert("用户确认密码不能为空,请输入密码!");
form1.reuserpassword.focus(); return false;
} if (form1.userpassword.value != form1.reuserpassword.value)
{
alert("密码与确认密码不同");
form1.userpassword.focus();
return false;
} if (form1.email.value.length!= 0)
{ for (i=0; i<form1.email.value.length; i++)
if (form1.email.value.charAt(i)=="@") break;
if (i==form1.email.value.length)
{ alert("非法EMail地址!"); form1.email.focus(); return false;
}
} else
{
alert("请输入Email!"); form1.email.focus(); return false;
}
}
</script>
<html>
<head>
<title>新用户注册</title>
</head>
<body>
<form method="POST" action="accept" name="form1" onsubmit="return on_submit()">
新用户注册<br>
用户名(*):<input type="text" name="username" size="20"><br>
密 码(*):<input type="password" name="userpassword" size="20"><br>
再输一次密码(*):<input type="password"name="reuserpassword"size="20"><br>
性别:<input type="radio" value="男"checked name="sex">男<input type="radio" name="sex" value="女">女<br>
出生年月:<input name="year" size="4" maxlength=4>年 <select name="month">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>月<input name="day" size="3" maxlength=4>日<br>
电子邮箱(*):<input name="email" maxlength=28><br>
家庭住址:<input type="text" name="address" size="20"><br>
<input type="submit" value="提交" name="B1"><input type="reset" value="全部重写" name="B2"><br>
</form>
</body>
</html>
过滤器
【步骤 1】编写一个过滤器改变请求编码:
loginform.html
<html>
<head>
<title>使用过滤器改变请求编码</title>
<meta http-equiv="Content-Type" content="text/html;charset=GB2312">
</head>
<body>
<center>
<h2>请输入用户名和口令:</h2>
<form method="post" action="CheckParamServlet">
<table>
<tr>
<td>用户名:</td>
<td><input name="name" type="text"></td>
</tr>
<tr>
<td>口 令:</td>
<td><input name="pass" type="password"></td>
</tr>
<tr>
<td></td>
<td>
<input name="ok" type="submit" value="提交">
<input name="cancel" type="reset" value="重置">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
【步骤 2】编写处理请求参数的 Servlet,代码如
package com.yiibai;
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;
/**
* Servlet implementation class CheckParamServlet
*/
@WebServlet("/CheckParamServlet")
public class CheckParamServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public CheckParamServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
String name = request.getParameter("name");
String pass = request.getParameter("pass");
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Param Test</title></head>");
out.println("<h3 align=center>你的用户名为:"+name+"</h3>");
out.println("<h3 align=center>你的口令为:"+pass+"</h3>");
out.println("</body></html>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
【步骤 3】修改 web.xml 文件,加入下面代码:
<servlet>
<servlet-name>CheckParamServlet</servlet-name>
<servlet-class>CheckParamServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckParamServlet</servlet-name>
<url-pattern>/CheckParamServlet</url-pattern>
</servlet-mapping>
【步骤 5】过滤器代码如下:
package filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
@WebFilter("/*")
public class EncodingFilter implements Filter {
protected String encoding = null;
protected FilterConfig config;
public EncodingFilter() {
// TODO Auto-generated constructor stub
}
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (request.getCharacterEncoding() == null) {
// 得到指定的编码
String encode = getEncoding();
if (encode != null) {
//设置 request 的编码
request.setCharacterEncoding(encode);
response.setCharacterEncoding(encode);
}
}
chain.doFilter(request, response);
}
protected String getEncoding() {
return encoding;
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
this.config = fConfig;
// 得到在 web.xml 中配置的编码
this.encoding = fConfig.getInitParameter("Encoding");
}
}
【步骤 6】在 web.xml 文件中配置过滤器,加入下面代码:
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>filter.EncodingFilter</filter-class>
<init-param>
<param-name>Encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
1.试简述过滤器有哪些功能?
过滤器对客户和资源之间的请求和响应进行过滤。请求经过一个过滤器到达servlet,servlet产生响应再经过过滤器到达客户,这就在请求和响应到达目的地之前对它们进行监视。过滤器的存在对servlet和客户都是透明的。
2. 如何理解过滤器链。
客户与资源之间建立多个过滤器,从而形成过滤器链。在过滤器链中每个过滤器都是请求处理,然后将请求交给链中的下一个过滤器(如果它是链中的最后一个,将交给实际的资源。)类似的,在响应到达客户之前,每个过滤器以相反的顺序对响应处理。
四、附加练习实现一个查询天气的 web 程序;
使用表单完成城市的输入,提交使用 ajax 完成查询显示;
Weather forecast.html
<!DOCTYPE html>
<html>
<head>
<meta charset="GB2312">
<title></title>
</head>
<body>
<input type="text" name="" id="numb" value="" />
<button type="button"onclick="loadXMLDoc()">获取天气</button>
<p id="text"></p>
</body>
<script type="text/javascript">
function loadXMLDoc(){
document.getElementById("text").innerHTML="请填写城市";
var x,url;
//获取id="numb"的值
x=document.getElementById("numb").value;
console.log(x);
//得到对象
var xhr=new XMLHttpRequest();
url="http://api.seniverse.com/v3/weather/now.json?key=WNEUXAAE2G&language=zh-Hans&unit=c&location="+encodeURI(x)
console.log(url);
//打开请求
xhr.open("get",url,false);//同步
//发送请求
xhr.send(null);
//判断响应状态
if(xhr.status==200){
//获取响应结果
obj=JSON.parse(xhr.responseText);
document.getElementById("text").innerHTML=obj.results[0].location.name+" "+obj.results[0].now.text+" "+obj.results[0].now.temperature;
// document.getElementById("text").innerHTML=xhr.responseText;
// console.log(xhr.responseText);
}else{
console.log("状态码:"+xhr.status+",原因:"+xhr.responseText)
}
}
</script>
</html>
五、心得体会:
能够理解 Servlet 的应用,并掌握 Servlet 的编程技术,以及熟练使用 Eclipse 开发 Servlet 应用;而且能够熟悉了解过滤器的作用,并掌握过滤器的开发与部署的步骤和了解过滤器链。
最后
以上就是怕孤独蜻蜓为你收集整理的实验三 Servlet 相关技术的全部内容,希望文章能够帮你解决实验三 Servlet 相关技术所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复