「Servlet」GetメソッドでURLのパラメータの値を取得するサンプル
書式
request.getParameter(“name")
request.getParameter(“url")
使用例
package com.arkgame.study; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class StudyForm */ @WebServlet("/StudyForm") public class StudyForm extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public HelloForm() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // コンテンツタイプの設定 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "Getメソッドでフォームのデータを取得"; // 文字化け String name =new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8"); String docType = "<!DOCTYPE html> \n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" + " <li><b>SiteName</b>:" + name + "\n" + " <li><b>HomePage</b>:" + request.getParameter("url") + "\n" + "</ul>\n" + "</body></html>"); } // postメソッドでリクエストを受ける public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
web.xmlの定義
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>StudyForm</servlet-name> <servlet-class>com.arkgame.study.StudyForm</servlet-class> </servlet> <servlet-mapping> <servlet-name>StudyForm</servlet-name> <url-pattern>/TomcatTest/StudyForm</url-pattern> </servlet-mapping> </web-app>
確認URL
http://localhost:8080/TomcatTest/HelloForm?name=info&url=www.arkgame.com