Java Servlet :是用Java编写的服务器端程序。其主要功能在于交互式地浏览和修改数据,生成动态Web内容。狭义的Servlet是指Java语言实现的一个接口,广义的Servlet是指任何实现了这个Servlet接口的类,一般情况下,人们将Servlet理解为后者。
Servlet运行于支持Java的应用服务器中。从实现上讲,Servlet可以响应任何类型的请求,但绝大多数情况下Servlet只用来扩展基于HTTP协议的Web服务器。

工作流程图:

一,使用xml配置的方式

1.HelloWrold HelloWorld.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
package com.devnp.servlet;

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

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

public class HelloWorld extends HttpServlet{

/**
* @author duliu
*/
private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
throws ServletException, IOException {
// TODO Auto-generated method stub
servletResponse.setContentType("text/html;charset=UTF-8");

PrintWriter out = servletResponse.getWriter();

// Write the response message, in an HTML page
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>devnp.com</title></head>");
out.println("<body>");
out.println("


<h1>Hello, world! This is Servlet.</h1>



");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}

@Override
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
throws ServletException, IOException {
// TODO Auto-generated method stub
//doGet(servletRequest, servletResponse);
}

@Override
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
}

@Override
public void init(ServletConfig servletConfig) throws ServletException {
// TODO Auto-generated method stub
super.init(servletConfig);
}
}

web.xml

1
2
3
4
5
6
7
8
9
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>com.devnp.servlet.HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>

访问:http://localhost:7002/JavaServlet/HelloWorld

2.表单提交的例子
form_input.html

[code lang=”html”]

first_form_input
Name:
Languages
        <input type="checkbox" name="language" value="java" checked />Java
        <input type="checkbox" name="language" value="c" />C/C++
        <input type="checkbox" name="language" value="cs" />C#
     </fieldset>




     <input type="submit" value="提交" />
</form>
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

<em>InputServlet.java</em>

```java
package com.devnp.servlet;

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

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

public class InputServlet extends HttpServlet{

/**
* @author duliu
*/
private static final long serialVersionUID = 1L;

@Override
public void init(ServletConfig servletConfig) throws ServletException {
// TODO Auto-generated method stub
System.out.println("Servlet init.");
}

@Override
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {

String nameStr = httpServletRequest.getParameter("name");

String [] languages = httpServletRequest.getParameterValues("language");

StringBuilder stringBuilder = new StringBuilder() ;
if(languages != null){
for (int i = 0; i < languages.length; i++) {
String language = languages[i];

stringBuilder.append(language + " ");
}
}

httpServletResponse.setContentType("text/html;charset=UTF-8");

PrintWriter out = httpServletResponse.getWriter();

// Write the response message, in an HTML page
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>first_form_input</title></head>");
out.println("<body>");
out.println("


<h1>Hello, " +nameStr + ", like " + stringBuilder.toString() + "</h1>



"); // says Hello
out.println("</body>");
out.println("</html>");
} finally {
out.close(); // Always close the output writer
}
}


@Override
public void destroy() {
System.out.println("Servlet destroy.");
}

}

web.xml

1
2
3
4
5
6
7
8
9
10
<!-- input -->
<servlet>
<servlet-name>InputServlet</servlet-name>
<servlet-class>com.devnp.servlet.InputServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>InputServlet</servlet-name>
<url-pattern>/InputServlet</url-pattern>
</servlet-mapping>

测试:http://localhost:7002/JavaServlet/form_input.html

提交

3.文件的上传
本例中,使用apache common-io,commom-upload 来完成文件的上传。
使用的版本在pom.xml的配置

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

fileUpload_form.html

[code lang=”html”]

FileUpload
    <input type="file" name="file" size="50" /> 


    <input type="submit" value="上传文件" />

</form>
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

<em>FileUploadServlet.java</em>

```java
package com.devnp.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet{

/**
* @author duliu
*/
private static final long serialVersionUID = 1L;

private static final String UPLOAD_DIRECTORY = "D:\\Person-Test" ;

@Override
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
// TODO Auto-generated method stub

String message = null ;

if(ServletFileUpload.isMultipartContent(httpServletRequest)){
try {
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(httpServletRequest);

for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
}
}

//File uploaded successfully
message = "File Uploaded Successfully";
} catch (Exception ex) {
message = "File Upload Failed due to " + ex;
}

}else{
message = "Sorry this Servlet only handles file upload request";
}

PrintWriter out = httpServletResponse.getWriter();
out.print(message);

out.close();
}

}

web.xml

1
2
3
4
5
6
7
8
9
10
<!-- file upload -->
<servlet>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>com.devnp.servlet.FileUploadServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/FileUploadServlet</url-pattern>
</servlet-mapping>

测试:http://localhost:7002/JavaServlet/fileUpload_form.html

上传文件

二、注解的方式

1.HelloWolrd 在servlet 3.0之后引用注解的方式,减少xml配置的方式,轻松完成配置 HelloWorldAnnotation.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
package com.devnp.servlet3;

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(name = "HelloWorldAnnotation", urlPatterns = {"/HelloWorldAnnotation"})
public class HelloWorldAnnotation extends HttpServlet{

/**
* @author duliu
*/
private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
// TODO Auto-generated method stub
httpServletResponse.setContentType("text/html;charset=UTF-8");

PrintWriter out = httpServletResponse.getWriter();

// Write the response message, in an HTML page
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>devnp.com</title></head>");
out.println("<body>");
out.println("


<h1>Hello, world! This is Servlet 3.0.</h1>



");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}

}
}

访问:http://localhost:7002/JavaServlet/HelloWorldAnnotation

2.文件的上传
fileUpload_form2.html

[code lang=”html”]

FileUpload
    <input type="file" name="file" size="50" /> 


    <input type="submit" value="上传文件" />

</form>
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

<em>FileUploadServletAnnotation.java</em>

```java
package com.devnp.servlet3;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

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

@WebServlet(name = "FileUploadServletAnnotation", urlPatterns = {"/FileUploadServletAnnotation"})
@MultipartConfig
public class FileUploadServletAnnotation extends HttpServlet{

/**
* @author duliu
*/
private static final long serialVersionUID = 1L;

@Override
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
// TODO Auto-generated method stub

Part filePart = httpServletRequest.getPart("file");

String fileName = getFileName(filePart);

OutputStream out = null;
InputStream filecontent = null;
PrintWriter writer = httpServletResponse.getWriter();

try {
File file = new File("D:\\Person-Test" + File.separator + fileName);

out = new FileOutputStream(file);
filecontent = filePart.getInputStream();

int read = 0;
final byte[] bytes = new byte[1024];

while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}

writer.println("New file " + fileName + " created at " + "D:\\Person-Test");

} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("
ERROR: " + fne.getMessage());

} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}

private String getFileName(Part part) {
for (String content : part.getHeader("Content-Disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}

return null;
}
}

测试:http://localhost:7002/JavaServlet/FileUploadServletAnnotation

上传文件

三、代码下载
d-logo JavaServlet.zip