针对客户端请求实现参数封装、页面响应以及数据响应

针对客户端请求实现参数封装、页面响应以及数据响应

一、实现参数封装

1、基本类型参数传递封装
public String getStudentById(Integer id){
        // 服务器处理
        System.out.println("id为:" + id);
        // 给出页面响应
        return INDEX_PAGE;

    }

2、 类类型参数传递封装

public String getStudentById(Student student){
        // 服务器处理
        // 这里的Student就是自己定义的类
        System.out.println("模拟查询 ...... 学生参数"+student.toString);

        // 给出页面响应  INDEX_PAGE是全局常量
        return INDEX_PAGE;

    }

3、数组和集合的传递封装

  • 数组传递封装
public String getStudentById(Integer id[]){
		//页面传参是 id=1&id=2&id=3
        // 服务器处理
        for(int i : id){
        	System.out.println("id为"+i);
        }
        // 给出页面响应
        return INDEX_PAGE;

    }
  • 集合的传递封装
public String getStudentById(Student stulist1){
		//页面传参是 stulist1=1&stulist1=2$stulist1=3
		// 由于基本类型List<String>是不能自动创建一个String类对象的,所以
		// 我们在接收参数里面写上 ArrayList<String> list 是接收不到网页
		// 传递过来的参数的,所以我们就需要在类对象里面私有一个集合
		// 通过里面的集合来接收参数
        // 服务器处理
        	System.out.println(stulist1.getList);
        // 给出页面响应
        return INDEX_PAGE;

    }

相关的Student类

public class Student{
	private List<String> list;
	public List getList(){
		return this.list;
	}
	public void setList(List<String> list){
		this.list = list;
	}
}

二、页面相应以及数据响应

1、页面响应

  • 直接通过ServletAPI中的request和response实现重定向以及转发
public void getStudentById(HttpServletRequest request, HttpServletResponse response){
 try{
       request.getRequestDispatcher("/index.jsp").forward(request,response);
// 这里的请求转发是需要完整路径的而重定向是是按照相对的来的 
//  response.sendRedirect(request.getContextPath()+"/index.jsp");
		} catch (ServletException e) {
		          e.printStackTrace();
		}
    }
  • 直接进行转发和重定向
public String getStudentById(){
	// return "forward:index.jsp";
	return "redirect:/xxxx/index.jsp";
	//  或者直接通过字符串地址进行跳转
	// return "/index.jsp";
}

  • 通过ModelAndView来进行跳转
public ModelAndView getStudentById(){
	ModelAndView mv = new ModelAndView();
	mv.setViewName("forward:/index.jsp")
}

2、数据的响应

  • 通过ServletAPI进行数据的响应
public void getStudentById(HttpServletRequest request, HttpServletResponse response){
	 // 参数的传递
        request.setAttribute("username","zhangsan");
        // 参数的获取
        request.getSession().getAttribute("username");
}
  • 借助ModelAndView进行数据的响应
public ModelAndView getStudentById(){
	ModelAndView mv = new ModelAndView();
	mv.addObject("username","zhangsan");
	mv.setViewName("forward:/index.jsp")
}
  • 借助Model和ModelMap来进行数据的响应
public void getStudentById(Model model,ModelMap modelMap){
	model.addAttribute("username","zhangsan");
	// map就是多了一个put的功能
	mdoelMap.put("usernae2","lisi");
	// map 也可以进行下面的操作
	modelMap.addAttribute("username3","wangwu")}

jsp的话就直接用 ${username}来进行引用就行了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值