springboot跳轉到其它頁面


一、單純跳轉

有時候我們需要將用戶提交的請求跳轉到其它頁面,下面代碼即可實現這個功能

@Controller
@RequestMapping("login")
@Api("模擬登陸")
public class LoginController {
    private final static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @GetMapping("redirect")
    @ApiOperation("跳轉到百度")
    public void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info(request.getPathInfo());
        response.sendRedirect("http://www.baidu.com");
    }
}

 二、模擬登陸

有時候我們需要在后端模擬前端登陸頁面的登陸,登陸成功后跳轉

@GetMapping("redirect2")
    @ApiOperation("跳轉到百度")
    public void doLogin2(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //創建HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //登陸網址
        String loginUrl = "http://xxx.com.cn/api/user/login";
        HttpPost httpPost = new HttpPost(loginUrl);
        //以Post方式請求,設置登錄用戶名和密碼
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("loginName", "xxxxx")); //這里改為自己的用戶名
        nameValuePairs.add(new BasicNameValuePair("loginPwd", "123456"));//這里改為自己的密碼
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        logger.info("statusCode:" + statusCode);
        InputStream inputStream = httpResponse.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = reader.readLine()) != null) {
            logger.info(line);
        }
        inputStream.close();
        reader.close();
        //登陸成功后跳轉到百度
        response.sendRedirect("http://www.baidu.com");
    }

三、模擬登陸后訪問內部頁面

登陸后訪問百度其實沒有什么意義,因為百度本來也不需要登陸;

如果我們登陸后可以去訪問一些本來需要登陸才能訪問的頁面,就可以獲取更多有價值的信息

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM