这篇文章解决的问题是怎么在业务方法里面引入我们熟悉的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
时间: 2024-10-09 09:39:44