LoginSignup
0
0

More than 3 years have passed since last update.

【自分用】サーブレットクラスの処理の転送

Posted at

【課題】乱数を発生させて、偶数が生成された場合はフォワードに、
奇数が生成された場合はリダイレクトに処理を転送する

【サーブレットクラス】


package p185;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
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("/P185")
public class P185 extends HttpServlet {
    private static final long serialVersionUID = 1L;
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        int Ran=(int)(Math.random()*10);
        if(Ran%2==1) {
            response.sendRedirect("/example/redirected62.jsp");
        }else{
            RequestDispatcher dispatcher =request.getRequestDispatcher("/forwarded62.jsp");
            dispatcher.forward(request,response);
        }
    }
}


a

【リダイレクト(jspファイル)】


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>リダイレクトサンプル</title>
</head>
<body>
<h1>リダイレクトのサンプルを表示</h1>
</body>
</html>

【フォワード(jspファイル)】


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>フォワードサンプル</title>
</head>
<body>
<h1>フォワードのサンプルを表示</h1>
</body>
</html>

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0