HTML表单标签:<form></form>
属性:
actoion: 提交到的地址,默认为当前页面
method: 表单提交方式 有get和post两种方式,默认为get
enctype: 文件上传时需要设置为multipart/form-data
Get:
以get方式提交数据时,浏览器会把表单内容组织成一个查询字符串,变量间以&连接,然后以servlrt路径加"?"加查询字符串的形式获取服务器内容
如:向某个Servlet提交两个参数a,b,组织后的URL为http://servltname/ServlrtTest?a=aValue&b=bValue
然后Servlet中用HttpServletRequest对象通过方法getParameter("a")获取到aValue,b同理
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String flag = request.getParameter("flag"); //从HttpServletRequest对象中获取传递过来的值,queryAll或者delete
BookService bs = new BookService();
if("queryAll".equals(flag)) {
List<Book> books = bs.queryAll();
request.setAttribute("books", books);
request.getRequestDispatcher("LibraryJsp/borrow.jsp").forward(request, response);
}else if("delete".equals(flag)) {
String id = request.getParameter("Id");
Book book = bs.queryOne(id);
bs.deleteBook(book);
List<Book> books = bs.queryAll();
request.setAttribute("books", books);
request.getRequestDispatcher("LibraryJsp/borrow.jsp").forward(request, response);
}
}
Post:
以post方式提交时,表单内容不会显示在浏览器中。
在doPost()中用getParameter()获取表单信息。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8"); String flag = request.getParameter("flag");
BookService bs = new BookService();
if("queryByItem".equals(flag)) {
String item = request.getParameter("item");
String value = request.getParameter("value");
List<Book> books = bs.queryByItem(item, value);
request.setAttribute("books", books);
request.getRequestDispatcher("LibraryJsp/borrow.jsp").forward(request, response);
}
}
Servlet之间的跳转:
分为转向Forward、重定向Redirect、刷新Refresh
转向:可以跳转到另一个Servlet,JSP,甚至WEB-INF下的另一个文件
重定向:通过服务器端返回状态码来实现,客户端请求了两次服务器。
301,302都表示重定向,301表示永久性重定向,302表示临时性重定向
刷新:可以实现一段时间后跳转到另一界面,也可以刷新本页面。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8"); String id = request.getParameter("username");
String password = request.getParameter("password");
LoginService ls = new LoginService();
User user = ls.Login(id, password);
if(!user.getUserId().isEmpty()) {
//登录成功后,请求转向
request.setAttribute("name", user.getUserId());
request.getRequestDispatcher("LibraryJsp/index.jsp").forward(request, response);
}else {
//登陆失败,重定向
response.sendRedirect("LibraryJsp/Login.jsp");
}
}