Spring MVC(二)

spring mvc工作流

1A)客户端发出http请求,只要请求形式符合web.xml
文件中配置的*.action的话,就由DispatcherServlet
来处理。

1B)DispatcherServlet再将http请求委托给映射器
的对象来将http请求交给对应的Action来处理

2)映射器根据客户的http请求,再对比<bean name="/hello.action
如果匹配正确,再将http请求交给程序员写的Action

3)执行Action中的业务方法,最终返回一个名叫ModelAndView
的对象,其中封装了向视图发送的数据和视图的逻辑名

4)ModelAndView对象随着响应到到DispatcherServlet中了

5)这时DispatcherServlet收到了ModelAndView对象,
它也不知道视图逻辑名是何意,又得委托一个名叫
视图解析器的对象去具体解析ModelAndView对象
中的内容

6)将视图解析器解析后的内容,再次交由DispatcherServlet
核心控制器,这时核心控制器再将请求转发到具体的
视图页面,取出数据,再显示给用户

Spring MVC(二)

Spring MVC(二)

springmvc快速入门(注解版本)

步骤一:创建springmvc-day02这么一个web应用

步骤二:导入springioc,springweb和springmvc相关的jar包

   ------------------------------------------------------springWEB模块
   org.springframework.web-3.0.5.RELEASE.jar
   org.springframework.web.servlet-3.0.5.RELEASE.jar(mvc专用)
   ------------------------------------------------------springIOC模块
   org.springframework.asm-3.0.5.RELEASE.jar
   org.springframework.beans-3.0.5.RELEASE.jar
   org.springframework.context-3.0.5.RELEASE.jar
   org.springframework.core-3.0.5.RELEASE.jar
   org.springframework.expression-3.0.5.RELEASE.jar

步骤三:在/WEB-INF/下创建web.xml文件

<servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>  注意:不在这配置初始化参数的话,默认是去/WEB-INF/ 目录下查找DispatcherServlet-serlvet.xml的配置文件,且是固定的文件名。
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring.xml</param-value>  一般是在src下的spring.xml配置文件中引入其他的springmvc.xml
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

步骤四:创建HelloAction.java控制器类

传统方式是实现Controller接口的方法,由于是重新了handRequest方法,因此一个action只能有一个handRequest方法。

注解方式没有实现接口或者继承类,所以可以有很多方法,方法名任意,而且方法的返回值不再是ModelAndView,这类似struts2

但是方法可以带参数,也可以不带,这点不同struts2,struts2的方法不能有参数。

@Controller
public class HelloAction{
    @RequestMapping(value="/hello")   路径为/hello的请求交给该方法处理。   注意:(value={"/a.action","/b.action"})表示多个路径都交给该方法处理
                                其中value=可以省略,直接{..},因为如果注解的属性是value,value可以省略 public String helloMethod(Model model) throws Exception{ System.out.println("HelloAction::helloMethod()"); model.addAttribute("message","这是我的第二个springmvc应用程序"); return "/success.jsp";注意:如果配置了视图解析器,前缀,后缀等,可以直接return "success"; 类似struts2,
如果不配置视图解析器,直接return "success";会报404错误。 } }
注意:Model是spring ui中的一个实体模型,放到model中的数据可以在jsp中取出来。

步骤五:在/WebRoot/下创建success.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>这是我的第二个springmvc应用程序</title>
  </head>
  <body>
    success.jsp<br/>
    ${message}
  </body>
</html>

步骤六:在/src/目录下创建spring.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"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xmlns:tx="http://www.springframework.org/schema/tx"
      xmlns:mvc="http://www.springframework.org/schema/mvc"

      xsi:schemaLocation="

      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd

      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

      ">

      <!-- Action控制器 -->  让spring ioc容器去扫描带有@Controller的类
      <context:component-scan base-package="cn.itcast.javaee.springmvc.helloannotation"/>      

      <!-- 基于注解的映射器(可选) -->
      <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>

      <!-- 基于注解的适配器(可选) -->
      <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

      <!-- 视图解析器(可选) -->
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/>

</beans>

步骤七:部署web应用到tomcat中,通过浏览器访问如下URL:

http://127.0.0.1:8080/springmvc-day02/hello.action

一个Action中,可以写多个类似的业务控制方法

通过模块根路径 + 功能子路径 = 访问模块下子功能的路径

@Controller
@RequestMapping(value="/user")  这里类似配置Struts2的namespace
public class UserAction{
    @RequestMapping(value="/add")
    public String add(Model model) throws Exception{
        System.out.println("HelloAction::add()");
        model.addAttribute("message","增加用户");
        return "/success.jsp";
    }
    @RequestMapping(value="/find")
    public String find(Model model) throws Exception{
        System.out.println("HelloAction::find()");
        model.addAttribute("message","查询用户");
        return "/success.jsp";
    }
}

增加用户:http://127.0.0.1:8080/myspringmvc-day02/user/add.action

查询用户:http://127.0.0.1:8080/myspringmvc-day02/user/find.action

在业务控制方法中写入普通变量收集表单提交的数据

可以在业务控制方法中,以参数形式收集客户端参数,springmvc采用方法参数形式的

/**
 *  控制器
 * @author AdminTC
 */
@Controller
@RequestMapping(value="/user")
public class UserAction {
    /**
     * 用户注册,只能接收POST请求
     */
    @RequestMapping(method=RequestMethod.POST,value="/register")
    public String registerMethod(Model model,String username,String salary) throws Exception{
        System.out.println("用户注册-->" + username + ":" + salary);  会自动的去扫描jsp页面提交的数据是否包含同名的参数,如果有,用该值
        model.addAttribute("message","员工注册成功");
        return "/jsp/success.jsp";//视图是真实路径,可以不配做视图解析器
    }
    /**
     * 用户登录,即能接收POST请求,又能接收GET请求
     */
    @RequestMapping(value="/login")
    public String loginMethod(Model model,String username) throws Exception{

        System.out.println("用户登录-->" + username);
        model.addAttribute("message","员工登录成功");
        return "/jsp/success.jsp";
    }
}

注意:原则:

1.  javabean中的属性一般用包装类型,Integer,Double

2.  普通方法中的参数类型一般用基础类型,int,double

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>

    <form action="${pageContext.request.contextPath}/user/register.action" method="POST">
        <table border="2" align="center">
            <caption><h2>用户注册</h2></caption>
            <tr>
                <th>姓名</th>
                <td><input type="text" name="username"/></td>
            </tr>
            <tr>
                <th>月薪</th>
                <td><input type="text" name="salary" value="7000"/></td>
            </tr>
            <tr>
                <th>入职时间</th>
                <td><input type="text" name="hiredate" value="2015-5-11 12:12:12"/></td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <input type="submit" value="注册" style="width:111px"/>
                </td>
            </tr>
        </table>
    </form>    

    <hr/>

    <form action="${pageContext.request.contextPath}/user/login.action" method="POST">
        <table border="2" align="center">
            <caption><h2>用户登录</h2></caption>
            <tr>
                <th>姓名</th>
                <td><input type="text" name="username"/></td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <input type="submit" value="登录" style="width:111px"/>
                </td>
            </tr>
        </table>
    </form>    

  </body>
</html>
@Controller
@RequestMapping(value="/user")
public class UserAction{
    @RequestMapping(value="/add")
    public String add(Model model,int id,String name,Double sal) throws Exception{
        System.out.println("HelloAction::add()");
        System.out.println(id + ":" + name + ":" + sal);
        model.addAttribute("message","增加用户");
        return "/success.jsp";
    }
}

http://127.0.0.1:8080/myspringmvc-day02/user/add.action?id=1&name=zhaojun&sal=5000

限定某个业务控制方法,只允许GET或POST请求方式访问

可以在业务控制方法前,指明该业务控制方法只能接收GET或POST的请求

@Controller
@RequestMapping(value="/user")
public class UserAction{
    @RequestMapping(value="/add",method=RequestMethod.POST)
    public String add(Model model,int id,String name,double sal) throws Exception{
        System.out.println("HelloAction::add()::POST");
        System.out.println(id + ":" + name + ":" + sal);
        model.addAttribute("message","增加用户");
        return "/success.jsp";
    }
}

如果不书写method=RequestMethod.POST的话,GET和POST请求都支持

在业务控制方法中写入Request,Response,Model等传统web参数

可以在业务控制方法中书写传统web参数,这种方式我们不提倡,耦合了

@Controller
@RequestMapping(value="/user")
public class UserAction{
    @RequestMapping(value="/add",method=RequestMethod.POST)
    public void add(HttpServletRequest request,HttpServletResponse response) throws Exception{
        System.out.println("HelloAction::add()::POST");
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        double sal = Double.parseDouble(request.getParameter("sal"));
        System.out.println(id + ":" + name + ":" + sal);
        request.getSession().setAttribute("id",id);
        request.getSession().setAttribute("name",name);
        request.getSession().setAttribute("sal",sal);
        response.sendRedirect(request.getContextPath()+"/register.jsp");
    }
}

返回值可以是void,String      struts2只能返回String

在业务控制方法中写入模型变量收集参数,且使用@InitBind来解决字符串转日期类型

1)  在默认情况下,springmvc不能将String类型转成java.util.Date类型,所有我们只能在Action

中自定义类型转换器

    <form action="${pageContext.request.contextPath}/user/add.action" method="POST">
        编号:<input type="text" name="id" value="${id}"/><br/>
        姓名:<input type="text" name="name" value="${name}"/><br/>
        薪水:<input type="text" name="sal" value="${sal}"/><br/>
        入职时间:<input type="text" name="hiredate" value='<fmt:formatDate value="${hiredate}" type="date"/>'/><br/>
        <input type="submit" value="注册"/>
    </form>
@Controller
@RequestMapping(value = "/user")
public class UserAction {
    @InitBinder
    protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {
        binder.registerCustomEditor(
                Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
    }
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(int id, String name, double sal, Date hiredate,
            Model model) throws Exception {
        System.out.println("HelloAction::add()::POST");
        model.addAttribute("id", id);
        model.addAttribute("name", name);
        model.addAttribute("sal", sal);
        model.addAttribute("hiredate", hiredate);
        return "/register.jsp";
    }
}

在业务控制方法中写入User,Admin多个模型收集参数

1)  可以在业务控制方法中书写1个模型来收集客户端的参数

2)  模型中的属性名必须和客户端参数名一一对应

3)  这里说的模型不是Model对象,Model是向视图中封装的数据

@Controller
@RequestMapping(value = "/user")
public class UserAction {
    @InitBinder
    protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {
        binder.registerCustomEditor(
                Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
    }
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(User user,Model model) throws Exception {
        System.out.println("HelloAction::add()::POST");
        model.addAttribute("user",user);
        return "/register.jsp";
    }
}

在业务控制方法中写入包装User的模型来收集参数

如果多个模型含有一些相同的字段,同时又都交给同一个action处理,该如何做。

可以在业务控制方法中书写0个或多个模型来收集客户端的参数

1)  如果多个模型中有相同的属性时,可以用user.name或admin.name来收集客户端参数

2)  用一个新的模型将User和Admin再封装一次

/**
 * 普通用户
 * @author AdminTC
 */
public class User {
    private String username;
    private Double salary;
    private Date hiredate;
    public User(){}
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public Double getSalary() {
        return salary;
    }
    public void setSalary(Double salary) {
        this.salary = salary;
    }
    public Date getHiredate() {
        return hiredate;
    }
    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }
    @Override
    public String toString() {
        return this.username+":"+this.salary+":"+this.hiredate.toLocaleString();
    }
}
/**
 * 管理员
 * @author AdminTC
 */
public class Admin {
    private String username;
    private Double salary;
    private Date hiredate;
    public Admin(){}
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public Double getSalary() {
        return salary;
    }
    public void setSalary(Double salary) {
        this.salary = salary;
    }
    public Date getHiredate() {
        return hiredate;
    }
    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }
    @Override
    public String toString() {
        return this.username+":"+this.salary+":"+this.hiredate.toLocaleString();
    }
}
/**
 * 封装User和Admin的对象
 * @author AdminTC
 */
public class Bean {
    private User user;
    private Admin admin;
    public Bean(){}
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public Admin getAdmin() {
        return admin;
    }
    public void setAdmin(Admin admin) {
        this.admin = admin;
    }
}
/**
 * 控制器
 * @author AdminTC
 */
@Controller
@RequestMapping(value="/person")
public class PersonAction {
    @InitBinder
    public void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {
        binder.registerCustomEditor(
                Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
    }

    /**
     * 业务方法
     */
    @RequestMapping(value="/register")
    public String registerMethod(Bean bean,Model model) throws Exception{   也可以使用参数(User user,Admin admin,Model,model)来处理
        System.out.println("普通用户:" + bean.getUser());
        System.out.println("管理员:" + bean.getAdmin());
        //将user和admin都绑定到Model                            注意:spring mvc中一般使用Model传值,不用request,session了
        model.addAttribute("user",bean.getUser());
        model.addAttribute("admin",bean.getAdmin());
        //转发
        return "/02_person.jsp";
    }
}
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
    普通用户
    <form action="${pageContext.request.contextPath}/person/register.action" method="POST">
        <table border="2" align="center">
            <tr>
                <th>姓名</th>
                <td><input type="text" name="user.username" value="${user.username}"/></td>
            </tr>
            <tr>
                <th>月薪</th>
                <td><input type="text" name="user.salary" value="${user.salary}"></td>
            </tr>
            <tr>
                <th>入职时间</th>
                <td><input
                        type="text"
                        name="user.hiredate"
                        value='<fmt:formatDate value="${user.hiredate}" type="date" dateStyle="default"/>'/></td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <input type="submit" value="普通用户注册" style="width:111px"/>
                </td>
            </tr>
        </table>
    </form>    

    <hr/>

    管理员
    <form action="${pageContext.request.contextPath}/person/register.action" method="POST">
        <table border="2" align="center">
            <tr>
                <th>姓名</th>
                <td><input type="text" name="admin.username" value="${admin.username}"/></td>
            </tr>
            <tr>
                <th>月薪</th>
                <td><input type="text" name="admin.salary" value="${admin.salary}"/></td>
            </tr>
            <tr>
                <th>入职时间</th>
                <td><input type="text" name="admin.hiredate" value='<fmt:formatDate value="${admin.hiredate}" type="date" dateStyle="default"/>'/></td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <input type="submit" value="管理员注册" style="width:111px"/>
                </td>
            </tr>
        </table>
    </form>    

  </body>
</html>

在业务控制方法中收集数组参数

如批量删除,类似struts2  用数组来收集

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
    <form action="${pageContext.request.contextPath}/emp/deleteAll.action" method="POST">
        <table border="2" align="center">
            <tr>
                <th>编号</th>
                <th>姓名</th>
            </tr>
            <tr>
                <td><input type="checkbox" name="ids" value="1"/></td>
                <td>哈哈</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="ids" value="2"/></td>
                <td>呵呵</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="ids" value="3"/></td>
                <td>嘻嘻</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="ids" value="4"/></td>
                <td>笨笨</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="ids" value="5"/></td>
                <td>聪聪</td>
            </tr>
            <tr>
                <td>
                    <input type="submit" value="删除"/>
                </td>
            </tr>
        </table>
    </form>
  </body>
</html>
package cn.itcast.javaee.springmvc.app22;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value="/emp")
public class EmpAction {
    @RequestMapping(value="/deleteAll",method=RequestMethod.POST)
    public String deleteAll(Model model,int[] ids) throws Exception{
        System.out.println("需要删除的员工编号分别是:");
        for(int id : ids){
            System.out.print(id+" ");
        }

        model.addAttribute("message","批量删除员工成功");
        return "/jsp/ok.jsp";
    }
}

在业务控制方法中收集List<JavaBean>参数

如批量注册用户等

registerAll.java

<form action="${pageContext.request.contextPath}/user/addAll.action" method="POST"> 

        姓名:<input type="text" name="userList[0].name" value="哈哈"/>
        性别:<input type="text" name="userList[0].gender" value="男"/>
        <hr/>

        姓名:<input type="text" name="userList[1].name" value="呵呵"/>
        性别:<input type="text" name="userList[1].gender" value="男"/>
        <hr/>

        姓名:<input type="text" name="userList[2].name" value="嘻嘻"/>
        性别:<input type="text" name="userList[2].gender" value="女"/>
        <hr/>

        <input type="submit" value="批量注册"/>

    </form>

Bean.java

public class Bean {
    private List<User> userList = new ArrayList<User>();
    public Bean(){}
    public List<User> getUserList() {
        return userList;
    }
    public void setUserList(List<User> userList) {
        this.userList = userList;
    }
}

UserAction.java

@Controller
@RequestMapping(value="/user")
public class UserAction {
    @RequestMapping(value="/addAll")
    public String addAll(Bean bean,Model model) throws Exception{
        for(User user : bean.getUserList()){
            System.out.println(user.getName()+":"+user.getGender());
        }
        model.addAttribute("message","批量增加用户成功");
        return "/success.jsp";
    }
}

 结果的转发和重定向

删除id=10号的用户,再查询用户

@Controller
@RequestMapping(value="/user")
public class UserAction {

    @RequestMapping(value="/delete")
    public String delete(int id) throws Exception{
        System.out.println("删除用户->" + id);
        //转发到find() 注意:转发的时候,从delete(int id)   转发到find(int id),可以不在find.action?id=10后面跟上id=10,会自动传入。
        return "forward:/user/find.action";
        //重定向到find()
        //return "redirect:/user/find.action";
    }

    @RequestMapping(value="/find")
    public String find(int id) throws Exception{
        System.out.println("查询用户->" + id);
        return "/success.jsp";
    }

}

异步发送表单数据,并响应JSON文本返回 

  1)  导入两个包

    jackson-core-asl-1.9.11.jar

    jackson-mapper-asl-1.9.11.jar

  2)在业务方法的返回值和权限之间使用@ResponseBody注解表示返回值对象需要转成JSON文本
  3)在spring.xml配置文件中编写如下代码:
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
      <property name="messageConverters">
        <list>
          <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
        </list>
      </property>
    </bean>

  4)  提交表单后,将JavaBean/list/Map 信息以JSON文本形式返回到浏览器

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
      <script type="text/javascript" src="js/jquery-1.8.2.js"></script>
  </head>
  <body> 

   <input type="button" value="Emp转JSON"/><p>

   <input type="button" value="List<Emp>转JSON"/><p>

   <input type="button" value="Map<String,Object>转JSON"/><p>

   <!-- Map<String,Object>转JSON -->
   <script type="text/javascript">
           $(":button:last").click(function(){
               var url = "${pageContext.request.contextPath}/emp/map2json.action";
               var sendData = null;
            $.post(url,sendData,function(backData,textStaut,ajax){
                alert(ajax.responseText);
            });
           });
   </script>

   <!-- List<Emp>转JSON -->
   <script type="text/javascript">
           $(":button:eq(1)").click(function(){
               var url = "${pageContext.request.contextPath}/emp/listbean2json.action";
               var sendData = null;
            $.post(url,sendData,function(backData,textStaut,ajax){
                alert(ajax.responseText);
            });
           });
   </script>

   <!-- Emp转JSON -->
   <script type="text/javascript">
           $(":button:first").click(function(){
               var url = "${pageContext.request.contextPath}/emp/bean2json.action";
               var sendData = null;//表示发送的数据,不发送数据,为null
            $.post(url,sendData,function(backData,textStaut,ajax){
                //alert(ajax.responseText);获取json对象值
                var hiredate = backData.hiredate;
                var date = new Date(hiredate);
                alert(date.getFullYear()+"年"+(date.getMonth()+1)+"月"+(date.getDate())+"日");
            });
           });
   </script>

  </body>
</html>
public class Emp {
    private Integer id;
    private String username;
    private Double salary;
    private Date hiredate;
    public Emp(){}
    public Emp(Integer id, String username, Double salary, Date hiredate) {
        this.id = id;
        this.username = username;
        this.salary = salary;
        this.hiredate = hiredate;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public Double getSalary() {
        return salary;
    }
    public void setSalary(Double salary) {
        this.salary = salary;
    }
    public Date getHiredate() {
        return hiredate;
    }
    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }
}
@Controller
@RequestMapping(value="/emp")
public class EmpAction {
    /**
     * @ResponseBody Emp 表示让springmvc将Emp对象转成json文本
     */
    @RequestMapping(value="/bean2json")
    public @ResponseBody Emp bean2json() throws Exception{
        //创建Emp对象
        Emp emp = new Emp();
        emp.setId();
        emp.setUsername("哈哈");
        emp.setSalary(7000D);
        emp.setHiredate(new Date());
        return emp;
    }

    @RequestMapping(value="/listbean2json")
    public @ResponseBody List<Emp> listbean2json() throws Exception{
        //创建List对象
        List<Emp> empList = new ArrayList<Emp>();
        //向List对象中添加三个Emp对象
        empList.add(,"哈哈",7000D,new Date()));
        empList.add(,"呵呵",8000D,new Date()));
        empList.add(,"嘻嘻",9000D,new Date()));
        //返回需要转JSON文本的对象
        return empList;
    }

    @RequestMapping(value="/map2json")
    public @ResponseBody Map<String,Object> map2json() throws Exception{
        //创建List对象
        List<Emp> empList = new ArrayList<Emp>();
        //向List对象中添加三个Emp对象
        empList.add(,"哈哈",7000D,new Date()));
        empList.add(,"呵呵",8000D,new Date()));
        empList.add(,"嘻嘻",9000D,new Date()));
        //创建Map对象
        Map<String,Object> map = new LinkedHashMap<String,Object>();
        //向Map对象中绑定二个变量
        map.put("total",empList.size());
        map.put("rows",empList);
        //返回需要转JSON文本的对象
        return map;
    }

}

spring.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:mvc="http://www.springframework.org/schema/mvc"
      xmlns:context="http://www.springframework.org/schema/context"

      xsi:schemaLocation="

      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd

      ">

        <!-- EmpAction类  -->
        <context:component-scan base-package="cn.itcast.javaee.springmvc.app25"/>

        <!-- 注册适配器 -->
        <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
                <property name="messageConverters">
                        <list>
                            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
                        </list>
                </property>
        </bean>

        <!--
            1)导入jackson-core-asl-1.9.11.jar和jackson-mapper-asl-1.9.11.jar
            2)在业务方法的返回值和权限之间使用@ResponseBody注解表示返回值对象需要转成JSON文本
            3)在spring.xml配置文件中编写如下代码:
            <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
                <property name="messageConverters">
                        <list>
                            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
                        </list>
                </property>
            </bean>
        -->
</beans>      

bean2json.jsp

<form>
        编号:<input type="text" name="id" value="1"/><br/>
        姓名:<input type="text" name="name" value="哈哈"/><br/>
        薪水:<input type="text" name="sal" value="5000"/><br/>
        <input type="button" value="异步提交注册"/>
    </form>

    <script type="text/javascript">
        $(":button").click(function(){
            var url = "${pageContext.request.contextPath}/user/add.action";
            var sendData = {
                "id":1,
                "name":"哈哈",
                "sal":5000
            };
            $.post(url,sendData,function(backData,textStatus,ajax){
                alert(ajax.responseText);
            });
        });
    </script>

User.java

public class User {
    private Integer id;
    private String name;
    private Double sal;
    public User(){}
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Double getSal() {
        return sal;
    }
    public void setSal(Double sal) {
        this.sal = sal;
    }
}

UserAction.java

@Controller
@RequestMapping(value="/user")
public class UserAction {

    @RequestMapping(value="/add")
    public @ResponseBody User add(User user) throws Exception{
        System.out.println(user.getId()+":"+user.getName()+":"+user.getSal());
        return user;
    }

}

spring.xml

  <!-- Action控制器 -->
      <context:component-scan base-package="cn.itcast.javaee.springmvc.app25"/>
        <!-- 配适器 -->
      <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
              <property name="messageConverters">
                     <list>
                      <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
                     </list>
              </property>
      </bean>
上一篇:嵌入式C快速翻转一个任何类型的数的二进制位


下一篇:【AngularJs】---表单验证