tonglin0325的个人主页

JavaWeb学习笔记——HelloWord Servlet

  1. 1.实现servlet打印日志
    1. 1.编写一个Java类,实现Servlet接口
    2. 2.把开发好的Java类部署到web服务器中
  2. 2.实现servlet打印HelloWorld
  3. 3.实现servlet打印当前时间
    1. 1.编写一个Java类,实现Servlet接口
    2. 2.把开发好的Java类部署到web服务器中
  4. 3.实现servlet打印header
  5. 请求头信息列表 “);# out.print(" <table border=1> "); out.print(" |名字|值 “); //返回头消息名字集合,返回的是一个枚举 Enumeration enums = request.getHeaderNames(); //遍历获取所有头信息名和值 while(enums.hasMoreElements()){ //获取每一个头消息的名字 String headName = (String)enums.nextElement(); out.println(“ “); out.println(“ | “ + headName + “ “); //getHeader(java.lang.String name) //Returns the value of the specified request header as a String. //返回这个名字的头信息的值 out.println(“ | “ + request.getHeaders(headName) + “ “); out.println(“ “); } out.println(“ “); out.println(" <hr> "); //测试HttpServletRequest的方法 out.println("Method: " + request.getMethod() + "<br>"); out.println("Request URI: " + request.getRequestURI() + "<br>"); out.println("Protocol: " + request.getProtocol() + "<br>"); out.println("PathInfo: " + request.getPathInfo() + "<br>"); out.println("Remote Address: " + request.getRemoteAddr() + "<br>"); out.println("ContextPath: " + request.getContextPath() + "<br>"); out.println("getScheme: " + request.getScheme() + "<br>"); out.println("getServerName: " + request.getServerName() + "<br>"); out.println("getServerPort: " + request.getServerPort() + "<br>"); out.println("getRequestURI: " + request.getRequestURI() + "<br>"); String path = request.getContextPath(); //请求全路径 String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI(); out.println(" path: " + path + "<br>"); out.println(" basePath: " + basePath + "<br>"); //out.print(this.getClass()); //out.println(", using the GET method"); out.print("</center>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //调用doGet方法 this.doGet(request, response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } } 然后部署并启动Tomcat服务器,在浏览器中输入 http://127.0.0.1:8080/testhttp/servlet/TestHttpServlet 4.使用servlet实现简单的login 本工程的功能是实现Javaweb的servlet身份验证   一下是login.html文件中的代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 <!DOCTYPE html> <html> <head> <title>login.html</title> <meta name="keywords" content="keyword1,keyword2,keyword3"> <meta name="description" content="this is my page"> <meta name="content-type" content="text/html; charset=GBK"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> <script type="text/javascript"> function check(){ //获取控件内容 var loginname = document.getElementById("loginname").value; if(loginname == ""){ alert("用户名不能为空"); document.getElementById("loginname").focus();//获取焦点 return false; } var password = document.getElementById("password").value; if(password == ""){ alert("密码不能为空"); document.getElementById("password").focus(); return false; } //验证成功 document.loginform.submit(); } </script> </head> <body> <center> <h2>登陆页面</h2> <br> <!-- html数据由两种传输方式 1.get 从地址栏传递 2.form表单传输 form代表表单 --action属性代表提交的url action="login.do",那么在web.xml里面定义<servlet-mapping>的<url-pattern> 的时候也是login.do --method属性代表提交表单的方式,http里面重点是get和post,默认get方式提交 --name属性给表单其名字 --id属性代表唯一标示该表单的名字,主要是javascript脚本使用 --> <form action="login.do" method="get" name="loginform" id="loginform"> <table> <tr> <td>登录名:</td> <td><input type="text" name="loginname" id="loginname"/></td> </tr> <tr> <td>密码:</td> <td><input type="password" name="password" id="password"/></td> </tr> </table> <table> <tr> <td><input type="button" value="提交" onclick="check();"></td> &nbsp;&nbsp; <td><input type="reset" value="重置"></td> </tr> </table> </form> </center> </body> </html>   以下代码是LoginServlet.java中的代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 package org.common.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { /** * Constructor of the object. */ public LoginServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("执行 doGet 方法..."); // //1.接收前台传递过来的参数 // Enumeration enums = request.getParameterNames(); // while(enums.hasMoreElements()){ // System.out.println(enums.nextElement()); // // } //转换编码的第2种方式,配合doPost()方法使用 request.setCharacterEncoding("GBK"); //提交的name可以在后台使用request.getParameter("loginname")获取值 String loginname = request.getParameter("loginname"); System.out.println("转换前loginname:" + loginname); //String password = request.getParameter("password"); //把loginname这个字符串转成GBK,前提你要确定编码 loginname = new String(loginname.getBytes("iso-8859-1"),"GBK"); System.out.println("转换后loginname:" + loginname); String password = request.getParameter("password"); //properties文件是java的默认配置文件,以key-value的形式存储数据 //增加了一个user.properties文件存储用户名密码 Properties pro = new Properties(); //load方法从输入流中读取属性列表(键和元素对) pro.load(this.getClass().getResourceAsStream("/user.properties")); //System.out.print(pro); response.setContentType("text/html;charset=GBK"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); //out.print(" loginname: " + loginname); //out.print(" password: " + password); if(loginname.equals(pro.getProperty("loginname")) && password.equals(pro.getProperty("password"))){ out.println(" 欢迎["+pro.getProperty("username")+"]登陆"); }else{ out.println("用户名密码错误"); } out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }   doGet()方法不安全,所以尽量使用doPost()方法 #
  6. “);
  7. 4.使用servlet实现简单的login 本工程的功能是实现Javaweb的servlet身份验证   一下是login.html文件中的代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 <!DOCTYPE html> <html> <head> <title>login.html</title> <meta name="keywords" content="keyword1,keyword2,keyword3"> <meta name="description" content="this is my page"> <meta name="content-type" content="text/html; charset=GBK"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> <script type="text/javascript"> function check(){ //获取控件内容 var loginname = document.getElementById("loginname").value; if(loginname == ""){ alert("用户名不能为空"); document.getElementById("loginname").focus();//获取焦点 return false; } var password = document.getElementById("password").value; if(password == ""){ alert("密码不能为空"); document.getElementById("password").focus(); return false; } //验证成功 document.loginform.submit(); } </script> </head> <body> <center> <h2>登陆页面</h2> <br> <!-- html数据由两种传输方式 1.get 从地址栏传递 2.form表单传输 form代表表单 --action属性代表提交的url action="login.do",那么在web.xml里面定义<servlet-mapping>的<url-pattern> 的时候也是login.do --method属性代表提交表单的方式,http里面重点是get和post,默认get方式提交 --name属性给表单其名字 --id属性代表唯一标示该表单的名字,主要是javascript脚本使用 --> <form action="login.do" method="get" name="loginform" id="loginform"> <table> <tr> <td>登录名:</td> <td><input type="text" name="loginname" id="loginname"/></td> </tr> <tr> <td>密码:</td> <td><input type="password" name="password" id="password"/></td> </tr> </table> <table> <tr> <td><input type="button" value="提交" onclick="check();"></td> &nbsp;&nbsp; <td><input type="reset" value="重置"></td> </tr> </table> </form> </center> </body> </html>   以下代码是LoginServlet.java中的代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 package org.common.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { /** * Constructor of the object. */ public LoginServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("执行 doGet 方法..."); // //1.接收前台传递过来的参数 // Enumeration enums = request.getParameterNames(); // while(enums.hasMoreElements()){ // System.out.println(enums.nextElement()); // // } //转换编码的第2种方式,配合doPost()方法使用 request.setCharacterEncoding("GBK"); //提交的name可以在后台使用request.getParameter("loginname")获取值 String loginname = request.getParameter("loginname"); System.out.println("转换前loginname:" + loginname); //String password = request.getParameter("password"); //把loginname这个字符串转成GBK,前提你要确定编码 loginname = new String(loginname.getBytes("iso-8859-1"),"GBK"); System.out.println("转换后loginname:" + loginname); String password = request.getParameter("password"); //properties文件是java的默认配置文件,以key-value的形式存储数据 //增加了一个user.properties文件存储用户名密码 Properties pro = new Properties(); //load方法从输入流中读取属性列表(键和元素对) pro.load(this.getClass().getResourceAsStream("/user.properties")); //System.out.print(pro); response.setContentType("text/html;charset=GBK"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); //out.print(" loginname: " + loginname); //out.print(" password: " + password); if(loginname.equals(pro.getProperty("loginname")) && password.equals(pro.getProperty("password"))){ out.println(" 欢迎["+pro.getProperty("username")+"]登陆"); }else{ out.println("用户名密码错误"); } out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }   doGet()方法不安全,所以尽量使用doPost()方法

1.实现servlet打印日志#

开发一个动态web资源,即开发一个Java程序向浏览器输出数据,需要完成以下2个步骤:

1.编写一个Java类,实现Servlet接口#

开发一个动态web资源必须实现javax.servlet.Servlet接口,Servlet接口定义了Servlet引擎与Servlet程序之间通信的协议约定

以下是MyServlet.java文件中的代码(写的这个类的名字叫做MyServlet):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package org.MyServlet.MyServlet;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

//开发一个动态web资源必须实现javax.servlet.Servlet接口
//Servlet接口定义了Servlet引擎与Servlet程序之间通信的协议约定

//Q:MyServlet完成了一个动态网页程序,或者说是一个功能,如何让客户端能否准确得找到我们得这个Servlet服务
//A:服务器需要预先为我们预留出扩展接口,我们只需要按照一定的规则去提供相应的扩展功能

//Q:如何和服务器进行通讯
//A:web.xml就是服务器提供给我们的完成功能的地方
public class MyServlet implements Servlet{

@Override
public void destroy() {
// TODO Auto-generated method stub

}

@Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}

@Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}

@Override
public void init(ServletConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}

//所有客户端请求会自动调用Service方法进行处理
//ServletRequest 是一个对象,封装所有HTTP请求信息
//ServletResponse 是一个对象,封装所有HTTP响应信息
//这两个对象是Tomcat服务器给我们的
@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub

System.out.println("执行 MyServlet 的 service() 方法。。。。。");
}

}

关于其中的Service方法的一些Tip:  

1
2
3
4
5
6
7
//所有客户端请求会自动调用Service方法进行处理
//ServletRequest 是一个对象,封装所有HTTP请求信息
//ServletResponse 是一个对象,封装所有HTTP响应信息
//这两个对象是Tomcat服务器给我们的

此外,如果是只实现service方法,则称为适配器模式

以下是web.xml文件中的代码:



MyServlet

index.html
index.htm
index.jsp
default.html
default.htm
default.jsp


//定义一个Servlet服务
//Servlet服务的名字叫做aaa

aaa
org.MyServlet.MyServlet.MyServlet


//定义一个Servlet服务的映射关系
//Servlet服务的名字叫做aaa
//请求的路径是/myServlet.do

//1.服务器启动模式加载webapps下面所有的应用,加载web应用的时候会读取每个应用的web。xml文件
//2.客户单发送请求http://127.0.0.1:8080/MyServlet/myServlet.do
//3.请求就找到http://127.0.0.1:8080,找到MyServlet(Context)
//去mapping里面查找/myServlet.do,如果找到,定位到aaa
//4.去Servlet的定义里面查找Servlet-name是aaa的Servlet服务
//然后定位到org.MyServlet.MyServlet.MyServlet,执行该class的service方法

aaa
/myServlet.do

然后在浏览器中输入

1
2
http://127.0.0.1:8080/MyServlet/myServlet.do

便可以在Tomcat中看到

1
2
执行 MyServlet 的 service() 方法。。。。。

2.把开发好的Java类部署到web服务器中#

 

2.实现servlet打印HelloWorld#

该工程的功能是在页面上输出一段话

首先在src里面新建一个class,在interface里面添加javax.servlet.Servlet

以下是HelloServlet.java中的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package org.common.Servlet;

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

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class HelloServlet implements Servlet {

@Override
public void destroy() {
// TODO Auto-generated method stub

}

@Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}

@Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}

@Override
public void init(ServletConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}

//开发完成之后要告诉服务器我的存在,就要在web。xml里面继续写代码
@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub
//获取一个输出流,就可以对页面写出内容
PrintWriter pw = arg1.getWriter();
pw.println("终于成功了!");
pw.close();
}

}

以下是web.xml文件中的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>HelloApp</display-name>
<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>

<!-- 定义Servlet服务 -->
<servlet>
<servlet-name>hello</servlet-name> <!--随便取-->
<servlet-class>org.common.Servlet.HelloServlet</servlet-class> <!--取包名。类名-->
</servlet>

<!-- 定义映射关系 -->
<servlet-mapping>
<!-- 注意:mapping里面的servlet-name在Servlet的定义里面一定要有匹配的,否则启动报错 -->
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>&nbsp;

访问的网址是

1
2
http://127.0.0.1:8080/Helloapp/hello

其中Helloapp是Tomcat里面的文件夹的名字,hello是url-pattern里面写的名字

 

3.实现servlet打印当前时间#

该工程的功能是实现在页面中显示当前的时间

1.编写一个Java类,实现Servlet接口#

以下的代码是HelloServlet.java中的代码

package helloapp2;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class HelloServlet extends GenericServlet {

@Override<br />    public void service(ServletRequest arg0, ServletResponse arg1)<br />            throws ServletException, IOException {<br />        // TODO Auto-generated method stub

    PrintWriter pw = arg1.getWriter();<br />        pw.println("Hello");<br />        pw.println(new Date().toLocaleString());<br />        pw.close();<br />    }

}

以下的代码是web.xml中的代码



helloapp2

index.html
index.htm
index.jsp
default.html
default.htm
default.jsp



Hello
helloapp2.HelloServlet



Hello
/Hello

2.把开发好的Java类部署到web服务器中#

使用myeclipse自动部署的方法(使用myeclipse 2015自动部署有问题,待解决)(换成2014的便可以自动部署):

  1.Window->preferences->Myeclipse->Servers->Runtime Ecvironment->add->Tomcat 6.0,要选中添加local的那个选项

  2.在manage deployment的module里面选择要部署的工程

  3.重新安装Tomcat出现的问题解决,但是还是要手动部署

 

自动部署设置,参考:Eclipse中的Web项目自动部署到Tomcat

自动部署后要把网页的文件放在根目录下

 

该工程的名称是testhttp,功能是在页面中表格打印浏览过程中的相关头信息。

   新建一个工程,然后在这个工程里面新建一个servlet,这样便可以省去编写web.xml的过程

 

3.实现servlet打印header#

以下是TestHttpServlet.java中的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package org.common.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

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

public class TestHttpServlet extends HttpServlet {

/**
* Constructor of the object.
*/
public TestHttpServlet() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/

//Servlet接口的参数service(ServletRequest arg0, ServletResponse arg1)

//HttpServletRequest封装了所有的请求信息,其实就是Tomcat将请求信息按照JAVA EE的Servlet的规范
//封装好给我们

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

//设置返回类型
//response.setContentType("text/html;charset=GBK");
response.setContentType("text/html");
response.setCharacterEncoding("GBK");

//获取输出流
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>testhttp Servlet</TITLE></HEAD>");
out.println(" <BODY>");

out.print("<center>");
out.print(" <h2>请求头信息列表<h2> ");

out.print(" <table border=1> ");
out.print(" |名字|值
");
//返回头消息名字集合,返回的是一个枚举
Enumeration enums = request.getHeaderNames();
//遍历获取所有头信息名和值
while(enums.hasMoreElements()){
//获取每一个头消息的名字
String headName = (String)enums.nextElement();
out.println(" <tr> ");
out.println(" | " + headName + " ");
//getHeader(java.lang.String name)
//Returns the value of the specified request header as a String.
//返回这个名字的头信息的值
out.println(" | " + request.getHeaders(headName) + " ");
out.println(" </tr> ");
}
out.println(" </table> ");

out.println(" <hr> ");
//测试HttpServletRequest的方法
out.println("Method: " + request.getMethod() + "<br>");
out.println("Request URI: " + request.getRequestURI() + "<br>");
out.println("Protocol: " + request.getProtocol() + "<br>");
out.println("PathInfo: " + request.getPathInfo() + "<br>");
out.println("Remote Address: " + request.getRemoteAddr() + "<br>");
out.println("ContextPath: " + request.getContextPath() + "<br>");
out.println("getScheme: " + request.getScheme() + "<br>");
out.println("getServerName: " + request.getServerName() + "<br>");
out.println("getServerPort: " + request.getServerPort() + "<br>");
out.println("getRequestURI: " + request.getRequestURI() + "<br>");
String path = request.getContextPath();
//请求全路径
String basePath
= request.getScheme() + "://" + request.getServerName() + ":"
+ request.getServerPort() + request.getRequestURI();
out.println(" path: " + path + "<br>");
out.println(" basePath: " + basePath + "<br>");

//out.print(this.getClass());
//out.println(", using the GET method");

out.print("</center>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

//调用doGet方法
this.doGet(request, response);
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}

请求头信息列表

“);#

    out.print(" <table border=1> ");
    out.print(" |名字|值

“);
//返回头消息名字集合,返回的是一个枚举
Enumeration enums = request.getHeaderNames();
//遍历获取所有头信息名和值
while(enums.hasMoreElements()){
//获取每一个头消息的名字
String headName = (String)enums.nextElement();
out.println(“ “);
out.println(“ | “ + headName + “ “);
//getHeader(java.lang.String name)
//Returns the value of the specified request header as a String.
//返回这个名字的头信息的值
out.println(“ | “ + request.getHeaders(headName) + “ “);
out.println(“ “);
}
out.println(“ “);

    out.println(" <hr> ");
    //测试HttpServletRequest的方法
    out.println("Method: " + request.getMethod() + "<br>");
    out.println("Request URI: " + request.getRequestURI() + "<br>");
    out.println("Protocol: " + request.getProtocol() + "<br>");
    out.println("PathInfo: " + request.getPathInfo() + "<br>");
    out.println("Remote Address: " + request.getRemoteAddr() + "<br>");
    out.println("ContextPath: " + request.getContextPath() + "<br>");
    out.println("getScheme: " + request.getScheme() + "<br>");
    out.println("getServerName: " + request.getServerName() + "<br>");
    out.println("getServerPort: " + request.getServerPort() + "<br>");
    out.println("getRequestURI: " + request.getRequestURI() + "<br>");
    String path = request.getContextPath();
    //请求全路径
    String basePath
        = request.getScheme() + "://" + request.getServerName() + ":"
        + request.getServerPort() + request.getRequestURI();
    out.println(" path: " + path + "<br>");
    out.println(" basePath: " + basePath + "<br>");
    
    //out.print(this.getClass());
    //out.println(", using the GET method");
    
    out.print("</center>");
    out.println("  </BODY>");
    out.println("</HTML>");
    out.flush();
    out.close();
}

/**
 * The doPost method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request the request send by the client to the server
 * @param response the response send by the server to the client
 * @throws ServletException if an error occurred
 * @throws IOException if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    
    //调用doGet方法
    this.doGet(request, response);
}

/**
 * Initialization of the servlet. <br>
 *
 * @throws ServletException if an error occurs
 */
public void init() throws ServletException {
    // Put your code here
}

}

然后部署并启动Tomcat服务器,在浏览器中输入

http://127.0.0.1:8080/testhttp/servlet/TestHttpServlet

4.使用servlet实现简单的login

本工程的功能是实现Javaweb的servlet身份验证

 

一下是login.html文件中的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<!DOCTYPE html>
<html>
<head>
<title>login.html</title>

<meta name="keywords" content="keyword1,keyword2,keyword3">
<meta name="description" content="this is my page">
<meta name="content-type" content="text/html; charset=GBK">

<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

<script type="text/javascript">
function check(){
//获取控件内容
var loginname = document.getElementById("loginname").value;
if(loginname == ""){
alert("用户名不能为空");
document.getElementById("loginname").focus();//获取焦点
return false;
}

var password = document.getElementById("password").value;
if(password == ""){
alert("密码不能为空");
document.getElementById("password").focus();
return false;
}

//验证成功
document.loginform.submit();
}
</script>

</head>

<body>
<center>
<h2>登陆页面</h2>
<br>
<!-- html数据由两种传输方式 1.get 从地址栏传递 2.form表单传输
form代表表单
--action属性代表提交的url
action="login.do",那么在web.xml里面定义<servlet-mapping>的<url-pattern>
的时候也是login.do
--method属性代表提交表单的方式,http里面重点是get和post,默认get方式提交
--name属性给表单其名字
--id属性代表唯一标示该表单的名字,主要是javascript脚本使用
-->
<form action="login.do" method="get" name="loginform" id="loginform">
<table>
<tr>
<td>登录名:</td>
<td><input type="text" name="loginname" id="loginname"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password" id="password"/></td>
</tr>
</table>
<table>
<tr>
<td><input type="button" value="提交" onclick="check();"></td>
&amp;nbsp;&amp;nbsp;
<td><input type="reset" value="重置"></td>
</tr>
</table>
</form>

</center>
</body>
</html>

 

以下代码是LoginServlet.java中的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package org.common.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Properties;

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

public class LoginServlet extends HttpServlet {

/**
* Constructor of the object.
*/
public LoginServlet() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

System.out.println("执行 doGet 方法...");
// //1.接收前台传递过来的参数
// Enumeration enums = request.getParameterNames();
// while(enums.hasMoreElements()){
// System.out.println(enums.nextElement());
//
// }

//转换编码的第2种方式,配合doPost()方法使用
request.setCharacterEncoding("GBK");

//提交的name可以在后台使用request.getParameter("loginname")获取值
String loginname = request.getParameter("loginname");
System.out.println("转换前loginname:" + loginname);
//String password = request.getParameter("password");

//把loginname这个字符串转成GBK,前提你要确定编码
loginname = new String(loginname.getBytes("iso-8859-1"),"GBK");
System.out.println("转换后loginname:" + loginname);
String password = request.getParameter("password");

//properties文件是java的默认配置文件,以key-value的形式存储数据
//增加了一个user.properties文件存储用户名密码
Properties pro = new Properties();
//load方法从输入流中读取属性列表(键和元素对)
pro.load(this.getClass().getResourceAsStream("/user.properties"));
//System.out.print(pro);

response.setContentType("text/html;charset=GBK");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");

//out.print(" loginname: " + loginname);
//out.print(" password: " + password);
if(loginname.equals(pro.getProperty("loginname"))
&amp;&amp; password.equals(pro.getProperty("password"))){
out.println(" 欢迎["+pro.getProperty("username")+"]登陆");
}else{
out.println("用户名密码错误");
}

out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

this.doGet(request, response);
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}

 

doGet()方法不安全,所以尽量使用doPost()方法

#

#