SSM框架(二)四种控制器请求【前端->值->后端】

目录

  • 一、请求接收
  • 二、接收请求参数
    • 1.字符串格式
    • 2.对象封装
  • 三、将某些值/某些对象放在session中
  • 四、跳转到目标视图/下一个Servlet
      • 情景1:response直接访问
      • 情景2:控制跳转
      • 情景3:{id}记录
  • 五、接收特殊参数
    • (一)文件参数

承接上一篇文章:SSM框架(一) 基于eclipseJee搭建SpingMVC框架
本文主讲在:controller类下的四种控制请求

一、请求接收

大致是如图流程,图中也不是很明白,详细讲述一下:
SSM框架(二)四种控制器请求【前端->值->后端】_第1张图片

  • 搭建:参考前面一章 SSM框架(一) 基于eclipseJee搭建SpingMVC框架
  • 主要目录:
    SSM框架(二)四种控制器请求【前端->值->后端】_第2张图片SSM框架(二)四种控制器请求【前端->值->后端】_第3张图片

二、接收请求参数

1.字符串格式

Controller类的方法中加入形参String userName ,String userPassword
(注意jsp和controller类命名一致)

  • index.jsp主要代码:index.do

    <form action="index.do" method="post">
    	<input type="text" name="userName"/><br/>
    	<input type="text" name="userPassword"/><br/>
    	<input type="submit" value="添加"/>
    form>
    
  • Controller.java:

    package com.cungudafa.spingmvc01.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    @RequestMapping("/")
    public class UserInfoController {
    	
    		@RequestMapping(value="index")
    		public String userIndex(String userName,String userPassword){
    		System.out.println("添加操作的业务逻辑:"+userName+" "+userPassword);
    		return "success";
    	}
    }
    
  • 浏览器查看到:
    SSM框架(二)四种控制器请求【前端->值->后端】_第4张图片
    在这里插入图片描述
    控制台打印:
    在这里插入图片描述

2.对象封装

如果请求中userName=xxx,自定义类

  • index.jsp主要代码:dologin.do

    <form action="dologin.do" method="post">
    	<input type="text" name="userName"/><br/>
    	<input type="text" name="userPassword"/><br/>
    	<input type="submit" value="添加"/>
    form>
    
  • 创建bean目录和 UserInfo.java:
    SSM框架(二)四种控制器请求【前端->值->后端】_第5张图片
    UserInfo.java:
    注意在jsp调用时,标签的name要与实体里的private后名称相同,同理controller调用时get方法名称方法名也要一致

    package com.cungudafa.spingmvc01.bean;
    
    public class UserInfo {
    	private Integer userId;
    	private String userName;
    	private String userPassword;
    	
    	public Integer getUserId() {
    		return userId;
    	}
    
    	public void setUserId(Integer userId) {
    		this.userId = userId;
    	}
    	
    	public String getUserName() {
    	  return userName;
    	}
    
    	public void setUserName(String userName) {
    	  this.userName = userName;
    	}
    
    	public String getUserPassword() {
    		return userPassword;
    	}
    
    	public void setUserPassword(String userPassword) {
    		this.userPassword = userPassword;
    	}
    	public UserInfo(String name, String password) {
    		super();
    		this.userName = name;
    		this.userPassword = password;
    	}
    	@Override
    	public String toString() {
    		return "User [用户=" + userName + ", 密码=" + userPassword + "]";
    	}
    }
    
    
  • 调用实体前必须更新一下配置,这里再贴一遍更新后的pom.xml、web.xml和sping-mvc.xml
    pom.xml 增加了文件上传部分:

    	
    	<dependency>
    	    <groupId>commons-fileuploadgroupId>
    	    <artifactId>commons-fileuploadartifactId>
    	    <version>1.3.3version>
    	dependency>
    

    web.xml 增加了浏览器url解析
    SSM框架(二)四种控制器请求【前端->值->后端】_第6张图片
    web.xml:

    
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
           version="3.1" metadata-complete="true">
    
    	
    	<context-param>
    		<param-name>contextConfigLocationparam-name>
    		<param-value>classpath:config/*.xmlparam-value>
    	context-param>
    	
    	<listener>
    		<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    	listener>
    	
    	
    	<filter>
    		<filter-name>characterEncodingFilterfilter-name>
    		<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    		<init-param>
    			<param-name>encodingparam-name>
    			<param-value>UTF-8param-value>
    		init-param>
    		<init-param>
    			<param-name>forceEncodingparam-name>
    			<param-value>trueparam-value>
    		init-param>
    	filter>
    	<filter-mapping>
    		<filter-name>characterEncodingFilterfilter-name>
    		<url-pattern>/*url-pattern>
    	filter-mapping>
    	
    	
    	<servlet>
    		<servlet-name>backservlet-name>
    		<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    		<init-param>
    			<param-name>contextConfigLocationparam-name>
    			<param-value>classpath:config/spring-mvc.xmlparam-value>
    		init-param>
    	servlet>
    	<servlet-mapping>
    		<servlet-name>backservlet-name>
    		<url-pattern>*.dourl-pattern>
    	servlet-mapping>
    
    web-app>
    
    

    sping-mvc.xml: 相对之前增加了上传文件部分,解析包改为到最大目录com.cungudafa.spingmvc01
    在这里插入图片描述
    SSM框架(二)四种控制器请求【前端->值->后端】_第7张图片
    sping-mvc.xml:

    
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    	
    	
    	<mvc:annotation-driven>mvc:annotation-driven>
    	
        
          
    	<context:component-scan base-package="com.cungudafa.spingmvc01" use-default-filters="false">
    		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    	context:component-scan>
    	
    	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">bean>
    	
    	
    	 
    	<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    	
    		<property name="prefix" value="/WEB-INF/">property>
    		<property name="suffix" value=".jsp">property>
    	bean>
    beans>
    
  • Controller.java:

    package com.cungudafa.spingmvc01.controller;
    
    import javax.servlet.http.HttpSession;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import com.cungudafa.spingmvc01.bean.UserInfo;
    
    @Controller
    @RequestMapping("/")
    public class UserInfoController {
    	
    	@RequestMapping(value="index")
    	public String userIndex(String userName,String userPassword){//直接同命名
    	System.out.println("添加操作的业务逻辑:"+userName+" "+userPassword);
    	return "success";
    	}
    
    	@RequestMapping("login")
    	public String login(){
    		return "login";
    	}
    	@RequestMapping(value="dologin")
    	public String login(UserInfo a,HttpSession session){//UserInfo a 封装对象,实例化;HttpSession session传值
    		System.out.println("用户:"+a.getUserName()+"\t密码:"+a.getUserPassword());
    		session.setAttribute("user", a);//从后台controller再传回前端页面,可调用user打印出来
    		return "success";
    	}
    }
    
    
  • 封装对象结果–浏览器查看到:
    SSM框架(二)四种控制器请求【前端->值->后端】_第8张图片
    SSM框架(二)四种控制器请求【前端->值->后端】_第9张图片
    控制台打印出:
    在这里插入图片描述

三、将某些值/某些对象放在session中

具体代码参考第二部分

四、跳转到目标视图/下一个Servlet

  • 在controller中加入关键代码:
    package com.cungudafa.spingmvc01.controller;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import com.cungudafa.spingmvc01.bean.UserInfo;
    
    /*
     * 一个控制器
     * @author Administrator 
     * 
     */
    @Controller
    @RequestMapping("/")
    public class UserInfoController {
    	
    	@RequestMapping(value="index")
    	public String userIndex(String userName,String userPassword){
    	System.out.println("添加操作的业务逻辑:"+userName+" "+userPassword);
    	return "success";
    	}
    
    	@RequestMapping("login")
    	public String login(){
    		return "login";
    	}
    	@RequestMapping(value="dologin")
    	public String login(UserInfo a,HttpSession session){
    		System.out.println("用户:"+a.getUserName()+"\t密码:"+a.getUserPassword());
    		session.setAttribute("user", a);
    		return "success";
    	}
    	@RequestMapping("index1")
    	public void index1(HttpServletResponse response){
    		try {
    			response.sendRedirect("/SpingMVC01/index.jsp");
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	
    	@RequestMapping("index2")
    	public void index2(HttpServletResponse response){
    		try {
    			PrintWriter out = response.getWriter();
    			out.println("hello");
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	
    	@RequestMapping("index301")
    	public String index301(){
    		return "login";
    	}
    	@RequestMapping("index302")
    	public @ResponseBody String index302(){
    		return "login";
    	}
    	
    	@RequestMapping("student/{id}")
    	public String find(@PathVariable("id") Integer id,HttpSession session){
    		System.out.println("id = " + id);
    		session.setAttribute("id", id);
    		return "index";
    	}
    	
    }
    
    

情景1:response直接访问

SSM框架(二)四种控制器请求【前端->值->后端】_第10张图片

  • 浏览器输入:http://localhost:8080/SpingMVC01/index2.do查看:
    SSM框架(二)四种控制器请求【前端->值->后端】_第11张图片

情景2:控制跳转

SSM框架(二)四种控制器请求【前端->值->后端】_第12张图片

  • 浏览器分别输入:http://localhost:8080/SpingMVC01/index301.dohttp://localhost:8080/SpingMVC01/index302.do查看:
    SSM框架(二)四种控制器请求【前端->值->后端】_第13张图片
    SSM框架(二)四种控制器请求【前端->值->后端】_第14张图片

情景3:{id}记录

SSM框架(二)四种控制器请求【前端->值->后端】_第15张图片

  • 浏览器输入:http://localhost:8080/SpingMVC01/student/1.do查看:
    SSM框架(二)四种控制器请求【前端->值->后端】_第16张图片
    控制台打印出:
    在这里插入图片描述

  • -> 在这里我们在success.jsp设置一个打印符:
    success.jsp关键代码:

      <body>
      	<h1>successh1>
          ${id}
     body>
    
  • -> 将return的index页面换为success页面:
    controller关键代码:

    	@RequestMapping("student/{id}")
    	public String find(@PathVariable("id") Integer id,HttpSession session){
    		System.out.println("id = " + id);
    		session.setAttribute("id", id);
    		return "success";
    	}
    
  • 运行结果:
    浏览器输入:http://localhost:8080/SpingMVC01/student/1.do查看:
    SSM框架(二)四种控制器请求【前端->值->后端】_第17张图片
    控制台打印出:
    在这里插入图片描述

五、接收特殊参数

(一)文件参数

  • 配置spring-mvc.xml,上传文件的处理器
    在这里插入图片描述
    完整spring-mvc.xml:

    
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    	
    	
    	<mvc:annotation-driven>mvc:annotation-driven>
    	
        
          
    	<context:component-scan base-package="com.cungudafa.spingmvc01" use-default-filters="false">
    		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    	context:component-scan>
    	
    	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">bean>
    	
    	
    	 
    	<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    	
    		<property name="prefix" value="/WEB-INF/">property>
    		<property name="suffix" value=".jsp">property>
    	bean>
    beans>
    
  • pom.xml中:(前面有添加,这里不贴源码,注意添加完pom.xml文件后,项目右键Maven-》update Project)
    SSM框架(二)四种控制器请求【前端->值->后端】_第18张图片

  • 修改index.jsp: (form action=“file/upload.do”)
    SSM框架(二)四种控制器请求【前端->值->后端】_第19张图片
    index.jsp:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title heretitle>
    head>
    <body>
    	<h1>Helloworldh1>
    	<form action="dologin.do" method="post">
    		<input type="text" name="userName"/><br/>
    		<input type="text" name="userPassword"/><br/>
    		<input type="submit" value="添加"/>
    	form>
    	<h1>文件上传h1>
    	<form action="file/upload.do" enctype="multipart/form-data" method="post">
    	<input type="file" name="uploadFile">
    	<button type="submit">上传button>
    	form>
    body>
    html>
    
    
  • 创建FileController.java: (路径为 /file/upload.do )
    在这里插入图片描述
    FileController.java:

    package com.cungudafa.spingmvc01.controller;
    
    import java.io.IOException;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.multipart.MultipartFile;
    
    @Controller
    @RequestMapping("/file")
    public class FileController {
    	
    	@RequestMapping("/upload")
    	public String upload(MultipartFile uploadFile) throws IOException{
    		System.out.println("uploadFile = " + uploadFile);
    		//获得上传字节数
    		byte[] buf = uploadFile.getBytes();
    		System.out.println("上传文件大小:" + buf.length);
    		//获得上传文件名称
    		System.out.println("上传文件名称getName = " + uploadFile.getName());
    		System.out.println("上传文件名称getOriginalFilename = " 
    		+ uploadFile.getOriginalFilename());
    		return "index";
    	}
    }
    
    • 运行结果:浏览器输入http://localhost:8080/SpingMVC01/index.jsp查看:
      SSM框架(二)四种控制器请求【前端->值->后端】_第20张图片 SSM框架(二)四种控制器请求【前端->值->后端】_第21张图片
      控制台打印出:(getOriginalFilename才是上传前的文件名)
      SSM框架(二)四种控制器请求【前端->值->后端】_第22张图片

你可能感兴趣的:(SSM,Java前后端开发学习)