Servlet获取URL地址。在HttpServletRequest类里,有以下六个取URL的函数:
getContextPath 取得项目名 getServletPath 取得Servlet名 getPathInfo 取得Servlet后的URL名,不包括URL参数 getRequestURL 取得不包括参数的URL getRequestURI 取得不包括参数的URI,即去掉协议和服务器名的URL
相对应的函数的值如下:
getContextPath:/ServletTest getServletPath:/main getPathInfo:/index/testpage/test getRequestURL:http://localhost:8080/ServletTest/main/index/testpage/test getRequestURI:/ServletTest/main/index/testpage/test
验证用户名
package com.glut.demo;import java.io.IOException;import java.util.Arrays;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ValidateUserName extends HttpServlet { private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("aa"); Listusernames = Arrays.asList("AAA","BBB","CCC"); String username = request.getParameter("username"); System.out.println("aa"); String result = null; if(usernames.contains(username)){ result = " 该用户名已经被使用"; }else{ result = " 该用户名可以使用"; } response.setContentType("text/html"); response.getWriter().print(result); }}
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>Ajax请求demo