zoukankan      html  css  js  c++  java
  • Spring MVC框架:第三章:获取请求参数和页面跳转控制

    获取请求参数
    1.什么是请求参数?

    <a href="emp/remove?empId=3">删除</a>
    
    <form action="emp/save" method="post">
        姓名:<input type="text" name="empName"/><br/>
        年龄:<input type="text" name="empAge"/><br/>
        工资:<input type="text" name="empSalary"/><br/>
        <input type="submit" value="保存"/>
    </form>
    

    2.请求参数的四种情况
    ①一名一值
    <a href=“emp/remove?empId=3”>删除</a>

    在handler方法的参数上使用@RequestParam注解。

    @RequestMapping("/caseOne")
    public String caseOne(@RequestParam("empId") Integer empId) {
        System.out.println("empId="+empId);
        return "result";
    }
    

    SpringMVC会自动帮我们进行类型转换。如果请求参数的名字和handler方法中对应形参的名字一致那么可以省略@RequestParam注解。

    @RequestMapping("/caseOne")
    public String caseOne(Integer empId) {
        System.out.println("empId="+empId);
        return "result";
    }
    

    ②一名多值

    <form action="team" method="post">
        请选择你最喜欢的球队:
        <input type="checkbox" name="team" value="Brazil"/>巴西
        <input type="checkbox" name="team" value="German"/>德国
        <input type="checkbox" name="team" value="French"/>法国
        <input type="checkbox" name="team" value="Holland"/>荷兰
        <input type="checkbox" name="team" value="Italian"/>意大利
        <input type="checkbox" name="team" value="China"/>中国
        <br/>
        <input type="submit" value="保存"/>
    </form>
    

    使用List或数组来接收。

    @RequestMapping("/caseTwo")
    public String caseTwo(@RequestParam("team") List<String> teams) {
        System.out.println(teams);
        return "result";
    }
    @RequestMapping("/caseTwo")
    public String caseTwo(@RequestParam("team") String[] teams) {
        System.out.println(Arrays.asList(teams));
        return "result";
    }
    

    ③表单数据正好对应一个实体类

    <form action="emp/save" method="post">
        姓名:<input type="text" name="empName"/><br/>
        年龄:<input type="text" name="empAge"/><br/>
        工资:<input type="text" name="empSalary"/><br/>
        <input type="submit" value="保存"/>
    </form>
    

    实体类:

    public class Employee {
        private Integer empId;
        private String empName;
        private int empAge;
        private double empSalary;
        ……
    

    直接使用和表单对应的实体类类型接收

    @RequestMapping("/caseThree")
    public String caseThree(Employee employee) {
        System.out.println(employee);
        return "result";
    }
    

    ④表单对应的实体类包含级联属性

    public class Student {
    	
    	private Integer studentId;
    	private String studentName;
    	private School school;
    	private List<Subject> subjectList;
    	private Subject[] subjectArray;    
    	private Set<Teacher> teacherSet;    	
    	private Map<String,String> scoreMap;
    	
    	{
    	 //在各种常用数据类型中,只有Set类型需要提前初始化
            //并且要按照表单将要提交的对象数量进行初始化
            //Set类型使用非常不便,要尽可能避免使用Set
    		teacherSet = new HashSet<>();
    		teacherSet.add(new Teacher());
    		teacherSet.add(new Teacher());
    		teacherSet.add(new Teacher());
    	}
    

    handler方法

    @RequestMapping("/get/param/multi/value")
    	public String getParamOneNameMultiValue(@RequestParam("team") List<String> teamList) {    		
    		for (String team : teamList) {
    			System.out.println(team);
    		}    		
    		return "target";
    	}
    	
    	@RequestMapping("/get/param/entity")
    	public String getParamEntity(Employee employee) {    		
    		System.out.println(employee);    		
    		return "target";
    	}
    	
    	//@RequestMapping("/get/param/entity")
    	public String getParamEntityParam(@RequestParam("empName") String empName) {    		
    		System.out.println("empName="+empName);    		
    		return "target";
    	}
    	
    	@RequestMapping("/get/param/fuza")
    	public String getParamFuza(Student student) {
    		System.out.println("StudentId="+student.getStudentId());
    		System.out.println("StudentName="+student.getStudentName());
    		System.out.println("SchoolId="+student.getSchool().getSchoolId());
    		System.out.println("SchoolName="+student.getSchool().getSchoolName());
    		List<Subject> subjectList = student.getSubjectList();
    		for (Subject subject : subjectList) {
    			System.out.println("科目名称="+subject.getSubjectName());
    		}
    		
    		Subject[] subjectArray = student.getSubjectArray();
    		for (Subject subject : subjectArray) {
    			System.out.println("科目名称="+subject.getSubjectName());
    		}
    		
    		Set<Teacher> teacherSet = student.getTeacherSet();
    		for (Teacher teacher : teacherSet) {
    			System.out.println("老师姓名="+teacher.getTeacherName());
    		}
    		
    		Map<String, String> scoreMap = student.getScoreMap();
    		Set<String> keySet = scoreMap.keySet();
    		for (String key : keySet) {
    			String value = scoreMap.get(key);
    			System.out.println(key+":"+value);
    		}
    		
    		return "target";
    	}
    

    提交数据的表单

    <form action="${pageContext.request.contextPath }/get/param/fuza" method="post">
    		学生编号:<input type="text" name="studentId" value="22" /><br/>
    		学生姓名:<input type="text" name="studentName" value="tom" /><br/>
    		
    		<!-- getSchool().setSchoolId() -->
    		学校编号:<input type="text" name="school.schoolId" value="33" /><br/>
    		学校名称:<input type="text" name="school.schoolName" value="at" /><br/>
    		
    		科目1名称:<input type="text" name="subjectList[0].subjectName" value="理论" /><br/>
    		科目2名称:<input type="text" name="subjectList[1].subjectName" value="倒库"/><br/>
    		科目3名称:<input type="text" name="subjectList[2].subjectName" value="路考"/><br/>
    		
    		科目4名称:<input type="text" name="subjectArray[0].subjectName" value="撞人"/><br/>
    		科目5名称:<input type="text" name="subjectArray[1].subjectName" value="防碰瓷"/><br/>
    		科目6名称:<input type="text" name="subjectArray[2].subjectName" value="追尾"/><br/>
    		
    		老师姓名:<input type="text" name="teacherSet[0].teacherName" value="卡卡西"/><br/>
    		老师姓名:<input type="text" name="teacherSet[1].teacherName" value="伊鲁卡"/><br/>
    		老师姓名:<input type="text" name="teacherSet[2].teacherName" value="大蛇丸"/><br/>
    		
    		考试成绩:<input type="text" name="scoreMap['shuxue']" value="25" /><br/>
    		考试成绩:<input type="text" name="scoreMap['yuwen']" value="16" /><br/>
    		考试成绩:<input type="text" name="scoreMap['yingyu']" value="7" /><br/>
    		考试成绩:<input type="text" name="scoreMap['lol']" value="100" /><br/>
    		考试成绩:<input type="text" name="scoreMap['dota']" value="300" /><br/>
    		
    		<input type="submit" value="提交"/>
    	</form>
    
    	<br/><br/>
    	
    	<form action="${pageContext.request.contextPath }/get/param/entity" method="post">
    		<!-- private Integer empId; -->
    		编号:<input type="text" name="empId"/><br/>
    		
    		<!-- private String empName; -->
    		姓名:<input type="text" name="empName"/><br/>
    		
    		<!-- private Integer empAge; -->
    		年龄:<input type="text" name="empAge"/><br/>
    		
    		<!-- private Double empSalary; -->
    		工资:<input type="text" name="empSalary"/><br/>
    		
    		<input type="submit" value="提交"/>
    	</form>
    
    	<br/><br/>
    
    	<form action="${pageContext.request.contextPath }/get/param/multi/value" method="post">
    		请选择你最喜欢的球队:<br/>
    		<input type="checkbox" name="team" value="German"/>德国<br/>
    		<input type="checkbox" name="team" value="Brazil"/>巴西<br/>
    		<input type="checkbox" name="team" value="Italian"/>意大利<br/>
    		<input type="checkbox" name="team" value="China"/>中国<br/>
    		<input type="checkbox" name="team" value="Korea"/>韩国<br/>
    		<input type="submit" value="提交"/>
    	</form>
    

    web.xml配置,解决字符乱码

    <!-- 在SpringMVC环境下对请求和响应过程强制使用UTF-8字符集进行编码、解码 -->
    	<filter>
    		<filter-name>CharacterEncodingFilter</filter-name>
    		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    		<init-param>
    			<param-name>encoding</param-name>
    			<param-value>UTF-8</param-value>
    		</init-param>
    		<init-param>
    			<param-name>forceEncoding</param-name>
    			<param-value>true</param-value>
    		</init-param>
    	</filter>
    	<filter-mapping>
    		<filter-name>CharacterEncodingFilter</filter-name>
    		<url-pattern>/*</url-pattern>
    	</filter-mapping>
    

    页面跳转控制
    1.转发指令

    @RequestMapping("/testForward")
    public String testForward() {
        return "forward:/target.jsp";
    }
    

    forward:/target.jsp
    表示方法执行完成后转发到/target.jsp。想一想有了视图解析器拼接字符串指定转发页面之后forward是否多余呢?

    2.重定向指令

    @RequestMapping("/testRedirect")
    public String testRedirect() {
        return "redirect:/target.jsp";
    }
    

    redirect:/target.jsp
    表示方法执行完成后重定向到/target.jsp。这里重定向中使用的路径和我们以前的写法不同,没有以Web应用名称开头,这是因为SpringMVC会替我们加上。

    3.使用原生对象完成转发

    @RequestMapping("/testForward")
    public void testForward2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/target.jsp").forward(request, response);
    }
    

    你看,使用原生request对象执行转发后,handler方法的返回值就必须是void,意思是我们自己指定了响应方式,不需要SpringMVC再进行处理了。一个请求只能有一个响应,不能在handler方法里面给一个,然后SpringMVC框架再给一个。

    4.使用原生对象完成重定向

    @RequestMapping("/testRedirect")
    public void testRedirect2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect(request.getContextPath()+"/target.jsp");
    }
    

    使用原生response对象执行重定向后,handler方法的返回值同样需要设置为void,原因同上。

  • 相关阅读:
    第六十三篇 用户权限、pymysql模块
    第六十二篇 视图、触发器、事务、存储过程
    第六十一篇 SQL查询语句
    第六十篇 约束、表关系
    第五十九篇 数据库配置文件以及数据类型
    第五十八篇 epoll模型、数据库
    第五十七篇 IO模型
    第五十六篇 并发之协程
    第五十五篇 死锁、GIL锁以及Pool
    第五十四篇 并发之线程
  • 原文地址:https://www.cnblogs.com/javawxid/p/12812073.html
Copyright © 2011-2022 走看看