首先先做个测试用的基本页面,里面放个表单
"<%@ page language=""java"" contentType=""text/html; charset=utf-8""
pageEncoding=""utf-8""%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + ""://"" + request.getServerName()
+ "":"" + request.getServerPort() + path + ""/"";
%>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%=path %>
<br>
<%=basePath %>
<br>
<form action=""<%=basePath%>LoginSvl"" method= ""post"">
<table align = ""center"">
<tr><td height = 200></td></tr>
<tr><td>用户名:</td><td><input type = ""text"" name = ""uname""></td></tr>
<tr><td>密码:</td><td><input type = ""password"" name = ""pwd""></td></tr>
<tr>
<td colspan = ""2"" align = ""center"">
<input type = ""submit"" value = ""提交""/>${msg}
</td>
</tr>
</table>
</form>"
这边pageEncoding设为utf-8是为了能显示中文。
访问登入页面的网址时,默认会触发Servlet的doGet()方法。
然而在同样的页面送出表单时,会启动一样的Servlet,但触发doPost()方法。
具体设定由页面上的标签进行设定如下:
<form action="<%=basePath%>LoginSvl" method= "post">
可以设定表单的资料要送往哪个Servlet,以及触发的方法。
不过在登入页面通常就送往同一个Servlet,以POST方式送件。
为了得到Servlet的路径,使用以下的request方法先得到网站的路径。
"request.getScheme() + ""://"" + request.getServerName()
+ "":"" + request.getServerPort() + request.getContextPath() + ""/"";"
以上路径再加上Servlet名称,即是完整路径。
新增LoginSvl
在com.aaa.action包下新增LoginSvl。
改写doGet()和doPost()方法如下:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/main/login.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uname = request.getParameter("uname");
String pwd = request.getParameter("pwd");
request.setAttribute("uname", uname);
request.getRequestDispatcher("/main/hello.jsp").forward(request, response);
}
可以看出使用者进入登入页面时,触发doGet(),被转发至login.jsp填表单。
填完之後送出表单,会触发同一个Servlet的doPost(),把表单的参数都存进变数後,设置到request的属性里面。然後把使用者转发到欢迎页面去。
欢迎页面可以新增或直接使用上一章写的hello.jsp,
只要把显示内容改为Hello,${uname}即可。
这边就可以看出,用request即可携带资料在输入页面、後台以及输出页面之间趴趴造。
不过,由於Servlet预设以"ISO-8859-1"去解读资料,因此若你在登入页面输入了中文名字,应该会在输出页面看到乱码。
要修正此情形,需在servlet里面加入以下代码:
request.setCharacterEncoding("UTF-8");
注:在开发过程中,有时候会手残删错档案(就是在下),照以下步骤可以救回来:
以上 就是这次的笔记内容
<<: {CMoney战斗营} 的第三周 #内部类别 及 Lambda
前言 今天来试着用滑鼠事件重现 2021 奥运羽球决胜点! 麟洋配万岁~ 台湾万岁~~ 滑鼠 Eve...
今天是铁人赛最後一天 我把之前所整理的资料来源一并附上 有些功能其实已经想好大概怎麽实现了,但在30...
变换图表折线图颜色样式 「y」:黄色 「--」:虚线 「^」:三角形 绘制两条线的折线图 显示图表的...
本篇同步发文於个人Blog: [读书笔记] Threading in C# - PART 3: US...
在开始写测试的时候因为许多 action 进入前都必须要先登入使用者才能有权限做其他事情,但在测试该...