我们都知道客户端与服务器之前的数据传输格式有html、xml以及json等。这些客户端需求的数据很少情况下会是直接访问现成的文件,大多情况下是需要我们服务器对客户端request信息进行分析处理,然后准备好对应的数据发给浏览器客户端。下面就结合一个小案例,浅谈servlet吧(基本配置
),还请各位大佬扶正。流程如下:(这篇博客的gif很直接)
客户端发送请求至服务器
服务器启动并调用Servlet,Servlet根据客户端请求生成响应内容并将其传给服务器
服务器将响应返回客户端
案例:当输入文本提示信息提示有没有被注册(Ajax局部刷新当前网页)
1.web工程首先是需要的,结构如下
HelloForm是servlet文件(是java文件,右键src->new->servlet快速创建),编译生成的HelloForm.class放在classes中。
//APP1网页:http://localhost:8080/Ajax/APP1.html
<script>
$(function () {
$(":text[name='username']").change(function () {
var val = $(this).val();
val = $.trim(val);
alert(val);
if (val != "") {
var url = "HelloForm";//这是servlet的虚拟url即http://localhost:8080/Ajax/HelloForm 对应唯一servlet请求处理
var args = {"userName": val, "time": new Date()};
$.post(url, args, function (data) {
$("#msg").html(data);
});
}
})
})
</script>
//表单请求,对应虚拟路径(http://localhost:8080/Ajax/HelloForm)的servlet可获取处理表单内容
<form action="HelloForm" method="GET">
//使用web应用根目录的绝对路径似乎更安全<form action="<%= request.getContextPath() %>/HelloForm" method="post">
UserName:<input type="text" name="username"/>
<div id="msg"></div>
<input type="submit" value="nameSubmit"> //submit后会触发默认行为跳转。
</form>
体会一下html中的post请求与get请求的区别:post有请求正文,而get将请求数据放在参数中(同url后面)而不是请求正文。
虽servlet处理程序都可以获得,但"隐私"数据还是不要放url后面太暴露了。
servlet文件HelloForm
@WebServlet("/HelloForm") //注解方式设置servlet处理程序的虚拟地址
public class HelloForm extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
System.out.println(userName); //输出到server控制台
List<String> names = Arrays.asList("AAA", "BBB", "CCC");
String result = null;
if (names.contains(userName)) {
result = "<font style='color:red'>该用户已经被注册</font>";
} else {
result = "<font style='color:green'>该用户可注册</font>";
}
response.setContentType("text/html;charset=UTF-8"); //设置响应内容类型
PrintWriter writer = response.getWriter();
writer.print(result); //返回响应内容
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username"); //获取表单内容
System.out.println(username);
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.print("跳转的网页"); //返回响应内容至跳转后的网页
}
}
web.xml方式设置servlet的映射关系
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>HelloForm</servlet-name> <!--注册的自定义的servlet名-->
<!--servlet处理程序(源文件)于src的相对路径,即servlet全类名-->
<servlet-class>xu.servlet.HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name> <!--需要和某个已注册名一致-->
<!--映射具体的访问路径: /代表当前WEB应用的根目录即http://localhost:8080/Ajax/-->
<url-pattern>/Form</url-pattern> <!--自定义虚拟url为http://localhost:8080/Ajax/Form-->
</servlet-mapping>
</web-app>
PS:两种servlet的虚拟url配置,选择一种即可(如果这两种配置方式同时存在且同名那tomcat就启动不了)
服务器控制台输出: