1 Servlet 简绍
Servlet(Server Applet)是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,主要功能在于交互式地浏览和修改数据,生成动态Web内容。
Servlet的架构图如下所示:
Servlet特点:
- Servlet运行于服务端。
- Servelet没有main方法。
- Servlet的创建,销毁由Servlet容器管理,如Tomcat,Jetty等。
2 使用Eclipse新建一个Servlet小程序
使用Eclipse新建一个Servlet小程序, HelloServlet。
生成一个HelloServlet.java,如下图所示:
新建 HelloServlet.java
package com.bank.study.controller;
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;
public class HelloServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setCharacterEncoding("utf-8");
response.addHeader("Content-type", "text/html;charset=utf-8");
PrintWriter pw = response.getWriter();
pw.println("你好 ,Servlet ....");
pw.flush();
pw.close();
pw = null;
}
@Override
public void destroy()
{
System.out.println("===== serlet destory() ====== ");
super.destroy();
}
@Override
public void init() throws ServletException
{
System.out.println("===== serlet init() ====== ");
super.init();
}
@Override
public void init(ServletConfig config) throws ServletException
{
System.out.println("===== serlet init(config) ====== ");
String name = config.getInitParameter("name");
System.out.println("name=" + name);
super.init(config);
}
}
在web.xml新建如下内容:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.bank.study.controller.HelloServlet</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>lisi</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
然后访问这个Servlet,加入Web工程名为DynaWeb,这个Servlet的访问地址为:
http://127.0.0.1:8888/DynaWeb/HelloServlet
注意:确认下 Eclipse使用的JDK ,是否和本机安装JDK一致,如果不一致,即使web.xml 配置正常了,也无法正常显示Servlet。
查看打印消息,参考 Maven学习笔记-04-Eclipse下maven项目在Tomcat7和Jetty6中部署调试 , 配置Tomcat的用户权限。
然后访问这个Servlet,如果一切正常如下图所示:
没有打印出Servlet的destory() 方法,进行下一步实验,从Tomcat管理控制平台,移除这个应用。如下图所示:
然后再查看Tomcat console打印信息,是否打印出這个Servlet的destory方法里的调试信息。
url-partten中的路径也可以使用*通配符,但是只能有两种固定的格式:一种格式是“*.扩展名”,另一种格式是以正斜杠(/)开头并以“/*”结尾。
第一种: *.扩展名
把 web.xml配置映射路径改为如下:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.bank.study.controller.HelloServlet</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>lisi</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
那么以下地址都是合法的:
http://localhost/studyweb/abc/hello.action
http://localhost/studyweb/aaa.action
第二种: 以正斜杠(/)开头并以“/*”结尾。
把 web.xml配置映射路径改为如下:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.bank.study.controller.HelloServlet</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>lisi</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
那么以下地址都是合法的:
http://localhost/studyweb/hello
http://localhost/studyweb/hello/1
http://localhost/studyweb/hello/1/2/3
3 Tomcat服务器的执行流程
Tomcat服务器的执行流程
第一次执行:
- 客户端通过电脑连接服务器,因为是请求是动态的,所以所有的请求交给WEB容器来处理
- 在容器中找到需要执行的*.jsp文件
- 之后*.jsp文件通过转换变为*.java文件
- *.java文件经过编译后,形成*.class文件
- 最终服务器要执行形成的*.class文件
第二次执行:
- 因为已经存在了*.class文件,所以不在需要转换和编译的过程
修改后执行:
- 源文件已经被修改过了,所以需要重新转换,重新编译。
4 Servlet输出中文乱码
1 新建一个Servlet, MainServlet.java
package com.bank.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MainServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public MainServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.addHeader("Content-type", "text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");;
PrintWriter pw = response.getWriter();
pw.println("<h1>你好</h1>" + new Date() +"中文乱码111");
pw.close();
pw = null;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
注意 response.setCharacter() ,response.addHeader() 要告知浏览器的编码方式,返回的响应信息是 html网页格式。
2 web.xml
<servlet>
<servlet-name>MainServlet</servlet-name>
<servlet-class>com.bank.controller.MainServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MainServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
3 然后访问这个MainServlet,查看页面是否显示正常。
参考资料: JavaWeb学习总结-07 Filter 学习和使用
5 Servlet获得表单数据
1 新建 form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Insert title here</title>
</head>
<body>
<form method="post" action="/studyweb/GetFormServlet">
用户名:<input type="text" name="username" maxlength="5"/> <br />
密码:<input type="password" name="pwd" /> <br />
性别: <input type="radio" name="gender" value="male"/>男
<input type="radio" name="gender" value="female" checked />女 <br/>
爱好:<input type="checkbox" name="interest" value="football" />足球
<input type="checkbox" name="interest" value="basketball" />篮球
<br>
城市: <select name="city">
<option value="beijing">北京</option>
<option value="xian" selected >西安</option>
</select>
<br />
简绍:<textarea name="desc" rows="9" cols="20" ></textarea>
<br />
<input type="submit" value="提交表单内容" />
<input type="reset" />
<button onclick="alert('click the button')" >点击按钮</button>
</form>
</body>
</html>
2 新建 GetFormServlet.java
GetFormServlet的参考代码
package com.bank.study.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetFormServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("--- doPost --- ");
//设置请求的字符集为utf-8
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
System.out.println("username=" + username);
String password = request.getParameter("pwd");
System.out.println("password=" + password);
String gender = request.getParameter("gender");
System.out.println("gender=" + gender);
String[] interests = request.getParameterValues("interest");
System.out.println("interests=" + interests);
StringBuffer selInterest = new StringBuffer();
if(null != interests){
for(int i=0, j= interests.length;i < j ;i++){
selInterest.append(interests[i]);
if( i < j - 1){
selInterest.append(",");
}
}
}
String city = request.getParameter("city");
System.out.println("city=" + city);
String desc = request.getParameter("desc");
System.out.println("desc=" + desc);
//设置响应的字符集为utf-8
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("获得以下的参数值");
out.println("username=" + username);
out.println("<br/>");
out.println("password=" + password);
out.println("<br/>");
out.println("gender=" + gender);
out.println("<br/>");
out.println("selInterest=" + selInterest);
out.println("<br/>");
out.println("city=" + city);
out.println("<br/>");
out.println("desc=" + desc);
out.println("<br/>");
String path = request.getContextPath();
out.println("<a href='" + path + "/form.html'>返回表单</a>");
out.flush();
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
3 web.xml
<servlet>
<servlet-name>GetFormServlet</servlet-name>
<servlet-class>com.bank.study.controller.GetFormServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetFormServlet</servlet-name>
<url-pattern>/GetFormServlet</url-pattern>
</servlet-mapping>