1、Eclipse 导入源码
同tomcat下载地址:https://tomcat.apache.org/ 我的是tomcat9 Download ->Tomcat 9->Source Code Distributions-> zip 下载 保存到本地,记住路径。
Eclipse 中 项目 java Resource ->Libraries -> JRE Sysem Library -> Servelet-api.jar ->javax.servelet.http -> HttpServelet.class -> 点击 Attach Sorce 导入外部刚下载的 源码包即可。
2、Servlet中doget()方法写文件发生中文乱码
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
3、ServletConfig接口
3.1后台采用 @WebServlet注解配置 搭配前台注册页面
package Test;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.WebInitParam;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet(name = "TestServlet003", urlPatterns = "/TestServlet003",
initParams = {@WebInitParam(name = "encoding", value = "UFT-8"),})
public class TestServlet003 extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
// 获得ServletConfig对象
ServletConfig config = this.getServletConfig();
// 获得参数名为encoding对应的参数值
String param = config.getInitParameter("encoding");
out.println("encoding=" + param);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
前台注册页面
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<title>注册会员</title>
</head>
<body>
<h1>会员注册</h1>
<form action="/YunPlay/Register" method="get">
<table bgcolor=#cccccc>
<tr>
<td>邮件地址:</td>
<td><input type='text' name='email' size='25' maxlength='100'>
</td>
</tr>
<tr>
<td>用户名(最大16字符):</td>
<td><input type='text' name='username' size='25'
maxlength='16'>
</td>
</tr>
<tr>
<td>密码(6到16字符):</td>
<td><input type='password' name='password' size='25' maxlength='16'>
</td>
</tr>
<tr>
<td>确认密码:</td>
<td><input type='text' name='confirmedPasswd' size='25' maxlength='16'>
</td>
</tr>
<tr>
<td>专业:</td>
<td><select name="subject" size="1" >
<option value="计算机">计算机</option>
<option value="软件工程">软件工程</option>
<option value="网络工程">网络工程</option>
</select></td>
</tr>
<tr>
<td colspan='2' align='center'><input type='submit' value='注册'>
</td>
</tr>
</table>
</form>
</body>
</html>
3.2后台采用web.xml配置 + 注册前后台
<servlet>
<display-name>myTest03</display-name>
<servlet-name>myTest03</servlet-name>
<servlet-class>Test.myTest03</servlet-class>
<init-param>
<param-name>author</param-name>
<param-value>wla</param-value>
</init-param>
<init-param>
<param-name>encoding</param-name>
<param-value>UFT-8</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>myTest03</servlet-name>
<url-pattern>/myTest03</url-pattern>
</servlet-mapping>
package Test;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.WebInitParam;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class myTest03 extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 获得ServletConfig对象
ServletConfig config = this.getServletConfig();
// 获得参数名为encoding对应的参数值
String param = config.getInitParameter("encoding");
response.getWriter().println("encoding=" + param);
String param1 = config.getInitParameter("author");
response.getWriter().println("author=" + param1);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
4、ServletContext接口
4.1获取引用程序的初始化参数
web.xml 同 3.2
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//PrintWriter out = response.getWriter();
// 获得ServletConfig对象
ServletConfig config = this.getServletConfig();
// 获得参数名为encoding对应的参数值
String param = config.getInitParameter("encoding");
response.getWriter().println("encoding=" + param);
String param1 = config.getInitParameter("author");
response.getWriter().println("author=" + param1);
}
4.2多个Servlet对象的共享
Object | getAttribute(String name) Returns the servlet container attribute with the given name, or null if there is no attribute by that name. |
Enumeration | getAttributeNames() Returns an Enumeration containing the attribute names available within this servlet context. |
void | removeAttribute(String name) Removes the attribute with the given name from the servlet context. |
void | setAttribute(String name, Object object) Binds an object to a given attribute name in this servlet context. |
Test05调用setAttribute(
String
name, Object
object)设置域属性名和值
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doGet(req, resp);
ServletContext context = this.getServletContext();
// 通过setAttribute()方法设置属性值
context.setAttribute("data", "this servlet save data");
context.setAttribute("name", "wuling129");
}
Test06调用getAttributeNames() 显示所有域属性名和值
package firstweb;
import java.io.IOException;
import java.util.Enumeration;
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 Test06 extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doGet(req, resp);
ServletContext context = this.getServletContext();
// 通过setAttribute()方法设置属性值
//String strData = (String) context.getAttribute("data");
//resp.getWriter().println(strData);
resp.getWriter().println("all the AttributeNames are following:<br />");
Enumeration<String> AttributeNames = context.getAttributeNames();
// 遍历所有的初始化参数名,得到相应的参数值并打印
while (AttributeNames.hasMoreElements()) {
String name = AttributeNames.nextElement();
String value = context.getAttribute(name).toString();
resp.getWriter().println(name + ":" + value);
resp.getWriter().println("<br />");
}
}
}
4.3读取Web应用下的资源文件
String | getRealPath(String path) Returns a String containing the real path for a given virtual path. |
URL | getResource(String path) Returns a URL to the resource that is mapped to a specified path. |
InputStream | getResourceAsStream(String path) Returns the resource located at the named path as an InputStream object. |
Set | getResourcePaths(String path) Returns a directory-like listing of all the paths to resources within the web application whose longest sub-path matches the supplied path argument. |
src 右键->New->Other->General->File : WebInfo.propertiesD
Company = itcast
Address = Beijing
读取其内容:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
ServletContext context = this.getServletContext();
PrintWriter out = response.getWriter();
//获取相对路径中的输入流对象
InputStream in = context.getResourceAsStream("/WEB-INF/classes/firstweb/WebInfo.properties");
Properties pros = new Properties();
pros.load(in);
out.println("Company=" + pros.getProperty("Company") + "<br />");
out.println("Address=" + pros.getProperty("Address") + "<br />");
}
4.3.1Java相对路径读取文件问题解决
java 中 getResourceAsStream() 方法总结
注意:需要到项目发布路径下寻找相对路径,否则找不到文件。
5、HttpServletResponse对象
5.1getOutputStream() 和 getWriter()
public ServletOutputStream getOutputStream() throws java.io.IOException
返回适用于在响应中编写二进制数据的 ServletOutputStream
。servlet 容器不会编码二进制数据。
对 ServletOutputStream 调用 flush() 将提交响应。 可调用此方法或 #getWriter
编写正文,而不是两种方法都调用。
return | 用于编写二进制数据的 ServletOutputStream |
Throws | IllegalStateException: 如果已对此响应调用 getWriter 方法 |
Throws | java.io.IOException: 如果发生输入或输出异常 |
See also | getWriter |
String data = "itcast";
// 获取字节输出流对象
OutputStream out = response.getOutputStream();
out.write(data.getBytes());// 输出信息*/
// 获取字符输出流对象
//PrintWriter print = response.getWriter();
// print.write(data); // 输出信息
5.2 请求重定向
WebContent 下新建 login.html 和 welcome.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<!--把表单内容提交到chapter04工程下的LoginServlet-->
<form action="/firstweb/LoginServlet" method="post">
用户名: <input type="text" name="username" /><br />
密 码:<input type="password" name="password"/><br />
<input type="submit" value="登录" />
</form>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>welcome</title>
</head>
<body>
欢迎你,登录成功!
</body>
</html>
LoginServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
// 用HttpServletRequest对象的getParameter()方法获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
// 假设用户名和密码分别为:itcast和123
if ("itcast".equals(username) &&"123".equals(password)) {
// 如果用户名和密码正确,重定向到 welcome.html
response.sendRedirect("/firstweb/welcome.html");
} else {
// 如果用户名和密码错误,重定向到login.html
response.sendRedirect("/firstweb/login.html");
}
}
6、HttpServletRequest对象
6.1 RequestLineServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
// 获取请求行的相关信息
out.println("getMethod : " + request.getMethod() + "<br />");
out.println("getRequestURI : " + request.getRequestURI() + "<br />");
out.println("getQueryString:" + request.getQueryString() + "<br />");
out.println("getProtocol : " + request.getProtocol() + "<br />");
out.println("getContextPath:" + request.getContextPath() + "<br />");
out.println("getPathInfo : " + request.getPathInfo() + "<br />");
out.println("getPathTranslated : " + request.getPathTranslated() + "<br />");
out.println("getServletPath:" + request.getServletPath() + "<br />");
out.println("getRemoteAddr : " + request.getRemoteAddr() + "<br />");
out.println("getRemoteHost : " + request.getRemoteHost() + "<br />");
out.println("getRemotePort : " + request.getRemotePort() + "<br />");
out.println("getLocalAddr : " + request.getLocalAddr() + "<br />");
out.println("getLocalName : " + request.getLocalName() + "<br />");
out.println("getLocalPort : " + request.getLocalPort() + "<br />");
out.println("getServerName : " + request.getServerName() + "<br />");
out.println("getServerPort : " + request.getServerPort() + "<br />");
out.println("getScheme : " + request.getScheme() + "<br />");
out.println("getRequestURL : " + request.getRequestURL() + "<br />");
}
6.2 RequestHeadersServlet
package firstweb;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
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 RequestHeadersServlet
*/
@WebServlet("/RequestHeadersServlet")
public class RequestHeadersServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RequestHeadersServlet() {
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());
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
// 获取请求消息中所有头字段
Enumeration<String> headerNames = request.getHeaderNames();
// 使用循环遍历所有请求头,并通过getHeader()方法获取一个指定名称的头字段
while (headerNames.hasMoreElements()) {
String headerName =headerNames.nextElement().toString();
out.print(headerName + " : "
+ request.getHeader(headerName) + "<br />");
}
}
/**
* @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);
}
}
6.3 getRequestDispatcher(String path) 和 forward()方法实现请求转发
新建html 提交表单到 RequestForwardServlet
//RequestForwardServlet 中响应方法
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
request.setAttribute("username", "张三");// 将数据存储到request对象中
RequestDispatcher dispatcher =
request.getRequestDispatcher("/ResultServlet");
dispatcher.forward(request, response);
}
//ResultServlet 中的方法
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String username = (String) request.getAttribute("username");
if (username != null) {
out.println("用户名:" + username + "<br/>");
}
}