14SpringMvc_在業務控制方法中寫入HttpServletRequest,HttpServletResponse等傳統web參數(這個知識點知道就好了,不推薦這么去做)


這篇文章解決的問題是怎么在業務方法里面引入我們熟悉的HttpServletRequest和HttpServletRespon?

答案:這種引入傳統的web參數的做法不推薦去做,因為這么做會實行高度耦合。

但還是說一下這種做法:

在Action修改代碼如下:

package com.guigu.shen.Action7;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
 * 
 * 
請求路徑可以拆分為:根模塊的名字+分模塊的名字
就是相當於當訪問http://127.0.0.1:8080:項目名/user/register時就會進入到
registerMethod方法。

 */
@Controller
@RequestMapping(value="/user")//根模塊的請求名字
public class UserAction {
    /*
     * 員工注冊
     * 
     */
@RequestMapping(method=RequestMethod.POST,value="/register")//分模塊的請求名字

public String registerMethod(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse)
{/*

通過HttpServletRequest和HttpServletRespon得到數據。
*/
    
    String username=httpServletRequest.getParameter("username");
    String salery=httpServletRequest.getParameter("salary");
     //保存到Session會話級別
    httpServletRequest.getSession().setAttribute("username", username);
    httpServletRequest.getSession().setAttribute("salary", salery);
//重定向
  try {
    httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/jsp/success.jsp");

  System.out.println("l路徑是"+httpServletRequest.getContextPath());
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
  return null;

}

}

success.jsp代碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
    Success. <br>
 <%--   輸出上一個頁面輸入的值 --%>
    ${username}
    ${salary}   
     
  </body>
</html>

結果如下:

Success.
aaa 1000


免責聲明!

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



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