SpringMVC -- 处理模型数据之ModelAndView / 处理模型数据之Map / 处理模型数据之SessionAttribute (4)

本文详细介绍了Spring MVC框架的配置、控制器类编写、视图解析、模型数据传递及会话属性应用,并通过示例代码展示了如何在实际项目中进行部署与运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

再重新贴一次项目结构吧...



web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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">

    <!--配置DispatcherServlet-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--配置DispatcherServlet配置文件的路径和文件名-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

springmvc配置文件

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<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"
       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">

       <context:component-scan base-package="com.springmvc.handlers"/>

       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="prefix" value="/WEB-INF/views/"></property>
              <property name="suffix" value=".jsp"></property>
       </bean>

</beans>

handler

控制器代码

package com.springmvc.handlers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by cyx on 2016/4/5.
 */

@RequestMapping("/springmvc")
@Controller
public class Main {

    private static final String SUCCESS = "success";


    /**
     * 目标方法的返回值,可以使ModelAndView类型,
     * 其中可以包含,视图和模型信息.
     * SpringMVC会把ModelAndView 的model 中的数据,存放到request域对象中.
     * @return
     */
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView() {
        String viewName = SUCCESS;
        ModelAndView modelAndView = new ModelAndView(viewName);

        //添加模型数据到ModelAndView中
        modelAndView.addObject("time",new Date());
        return modelAndView;
    }




    /**
     * 使用Servlet原生API 作为目标方法参数,具体可以支持以下类型.
     * 1.HttpServletRequest
     * 2.HttpServletResponse
     * 3.HttpSession
     * 4.java.security.Principal
     * 5.Local
     * 6.InputStream
     * 7.OutputStream
     * 8.Reader
     * 9.Writer
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/testServletAPI")
    public String testServletAPI(HttpServletRequest request,HttpServletResponse response) {
        System.out.println("testServletAPI request: "+request +" response: "+response);
        return SUCCESS;
    }



    /**
     * 测试
     * @return
     */
    @RequestMapping("/hello")
    public String hello() {
        System.out.println("hello");
        return SUCCESS;
    }

}


success.jsp

<%--
  Created by IntelliJ IDEA.
  User: cyx
  Date: 2016/4/5
  Time: 13:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>
</head>
<body>
  <h4>Success Page</h4>

  time:${requestScope.time}
</body>
</html>


然后部署运行就OK....




//----------------------------------------------------------------------------------------------------------------------------


继续沿用上一个的Demo....

Handler

Main.java

一些无关的,我就直接删除了..

package com.springmvc.handlers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * Created by cyx on 2016/4/5.
 */

@RequestMapping("/springmvc")
@Controller
public class Main {

    private static final String SUCCESS = "success";


    /**
     * 目标方法可以添加Map参数
     * 实际上也可以是Model类型,或者 ModelMap类型.
     * @param map
     * @return
     */
    @RequestMapping("/testMap")
    public String testMap(Map<String, Object> map) {
        System.out.println(map.getClass().getName());
        map.put("names", Arrays.asList("Tom","Jerry","Mike"));
        return SUCCESS;
    }




    /**
     * 目标方法的返回值,可以使ModelAndView类型,
     * 其中可以包含,视图和模型信息.
     * SpringMVC会把ModelAndView 的model 中的数据,存放到request域对象中.
     * @return
     */
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView() {
        String viewName = SUCCESS;
        ModelAndView modelAndView = new ModelAndView(viewName);

        //添加模型数据到ModelAndView中
        modelAndView.addObject("time",new Date());
        return modelAndView;
    }

}


index.jsp

<%--
  Created by IntelliJ IDEA.
  User: cyx
  Date: 2016/4/5
  Time: 13:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title></title>
  </head>
  <body>

  <a href="springmvc/testMap">Test Map</a>
  <br><br>

  <a href="springmvc/testModelAndView">Test ModelAndView</a>

  <br><br>

  <a href="springmvc/testServletAPI">Test ServletAPI</a>

  <br><br>

  <a href="springmvc/hello">Hello</a>
  </body>
</html>

success.jsp

<%--
  Created by IntelliJ IDEA.
  User: cyx
  Date: 2016/4/5
  Time: 13:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>
</head>
<body>
  <h4>Success Page</h4>

  time:${requestScope.time}
  <br><br>

  names:${requestScope.names}

  <br><br>

</body>
</html>

部署运行即可.....







//---------------------------------------------------------------------------------------------------------------------------------------------


沿用之前的Demo....

Handler

Main.java

package com.springmvc.handlers;

import com.springmvc.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * Created by cyx on 2016/4/5.
 */

@SessionAttributes(value = {"user"} ,types = {String.class})
@RequestMapping("/springmvc")
@Controller
public class Main {

    private static final String SUCCESS = "success";


    /**
     * @SessionAttributes除了可以通过属性名指定需要方法会话中的属性外(value属性值),
     * 还可以通过模型属性的对象类型 指定哪些模型属性需要放到会话中(type属性值).
     *
     * @SessionAttributes 这个注解中,既放了键,又放了类型,如果向Map中添加String类型,也会将String 放入session中
     *
     * 注意: @SessionAttributes 注解 只能放在类上面,而不能放在方法上面.
     *
     * @param map
     * @return
     */
    @RequestMapping("/testSessionAttributes")
    public String testSessionAttributes(Map<String ,Object> map) {
        User user = new User("Tom","123456","Tom@163.com",22);
        map.put("user", user);
        map.put("school", "Wisedu");
        return SUCCESS;
    }



    /**
     * 目标方法可以添加Map参数
     * 实际上也可以是Model类型,或者 ModelMap类型.
     * @param map
     * @return
     */
    @RequestMapping("/testMap")
    public String testMap(Map<String, Object> map) {
        System.out.println(map.getClass().getName());
        map.put("names", Arrays.asList("Tom","Jerry","Mike"));
        return SUCCESS;
    }




    /**
     * 目标方法的返回值,可以使ModelAndView类型,
     * 其中可以包含,视图和模型信息.
     * SpringMVC会把ModelAndView 的model 中的数据,存放到request域对象中.
     * @return
     */
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView() {
        String viewName = SUCCESS;
        ModelAndView modelAndView = new ModelAndView(viewName);

        //添加模型数据到ModelAndView中
        modelAndView.addObject("time",new Date());
        return modelAndView;
    }

}

success.jsp

<%--
  Created by IntelliJ IDEA.
  User: cyx
  Date: 2016/4/5
  Time: 13:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>
</head>
<body>
  <h4>Success Page</h4>

  time:${requestScope.time}
  <br><br>

  names:${requestScope.names}
  <br><br>

  request user :${requestScope.user}
  <br><br>

  session user :${sessionScope.user}
  <br><br>

  request school :${requestScope.school}
  <br><br>

  session school :${sessionScope.school}
  <br><br>

</body>
</html>

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: cyx
  Date: 2016/4/5
  Time: 13:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title></title>
  </head>
  <body>

  <a href="springmvc/testSessionAttributes">Test SessionAttributes</a>
  <br><br>

  <a href="springmvc/testMap">Test Map</a>
  <br><br>

  <a href="springmvc/testModelAndView">Test ModelAndView</a>

  <br><br>

  <a href="springmvc/testServletAPI">Test ServletAPI</a>

  <br><br>

  <a href="springmvc/hello">Hello</a>
  </body>
</html>


然后部署运行即可....

这个是不用SessionAttribute注解标签....说明,user并没有存放在session中.




使用sessionAttribute注解,将User添加至Session中......





这个是在SessionAttribute注解中,使用类型 这个属性....

设置SessionAttribute标签中的Types属性为String之后......

如果向Map中添加String类型,也会将String 放入session中






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值