html与后台之间数据的传递
在讲html与servlet进行数据互传之间,有必要先了解传统的html与servlet之间参数的传统,为了能够更好地说明,此种传统之间的特点,现在用一个登录的案例来说明此种之间参数的传递。
1)首先建立一个用于登录的login.html页面,代码如下:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录界面</title> <style> body{width:300px; height:200px; margin:0 auto;} fieldset{ width:300px; } table{ width:300px; height:100px;} </style> </head> <body> <fieldset> <legend>登录界面</legend> <form action="../LoginServlet" method="post"> <table> <tr><td>姓名:</td><td><input type="text" name="name"/></td></tr> <tr><td>密码:</td><td><input type="text" name="password"/></td></tr> </table> <input type="submit" value="提交" style="margin-left:66px; width:70px;"> <input type="reset" value="重置" style="width:70px;"/> </form> </fieldset> </body> </html> |
需要注意的是表单中的name属性必须填写
2)建立一个用于接收参数的LoginServlet.java,具体代码如下:
package zjh.javaee.servlet;
import java.io.IOException; 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("/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L;
public LoginServlet() { super(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解决乱码问题 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); //接收请求的参数 String userName = request.getParameter("name"); //这里的name指的是标签中的name属性 String userPassword = request.getParameter("password"); //这里的password指的也是标签中的name属性 System.out.println("姓名为:"+userName+":"+"密码为:"+userPassword); //判断输入的姓名、密码是否为空,如果不为空则跳转到显示结果的show.html页面 if(userName.equals("")||userName==null||userPassword.equals("")||userPassword==null){ System.out.println("error"); }else{ //服务器端跳转 request.getRequestDispatcher("/html/show.html").forward(request, response); } }
}
|
3)用于显示登录成功的show.html页面
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录成功</title> </head> <body> <h1>登录成功</h1> </body> </html> |
由上面的案例不难看出,如果用html与servlet进行参数的传递,有一个明显的问题,就是只能将html中的参数传到servlet后台中,却不能从后台将数据传回到前端的html页面中,另外,如果用html与servlet进行数据传递,在html页面中只能通过表单的形式来传递参数到后台中,这就在一定程度上限制了html的功能。