SpringMVC【开发Controller】详解

前言

本文主要是讲解在Controller中的开发,主要的知识点有如下:

  • 编码过滤器
  • 使用注解开发
  • 注解@RequestMapping详解
  • 业务方法接收参数
  • 字符串转日期
  • 重定向和转发
  • 返回JSON

SpringMVC过滤编码器

在SpringMVC的控制器中,如果没有对编码进行任何的操作,那么获取到的中文数据是乱码!

《SpringMVC【开发Controller】详解》

即使我们在handle()方法中,使用request对象设置编码也不行!原因也非常简单,我们SpringMVC接收参数是通过控制器中的无参构造方法,再经过handle()方法的object对象来得到具体的参数类型的

Struts2是使用拦截器来自动帮我们完成中文乱码的问题的。那么SpringMVC作为一个更加强大的框架,肯定也有对应的方法来帮我们完成中文乱码问题!

值得注意的是:该过滤编码器只能解决POST的乱码问题

我们只需要在web.xml配置文件中设置过滤编码器就行了


    <!-- 编码过滤器 -->
    <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>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

《SpringMVC【开发Controller】详解》

注解开发SpringMVC

我们在快速入门的例子中使用的是XML配置的方式来使用SpringMVC的,SpringMVC也能够支持注解。【个人非常喜欢注解的方式】

我们在使用Action的时候,要么继承着AbstractCommandController类,要么显示使用注解Controller接口。当我们使用了注解以后就不用显示地继承或实现任何类了

开发流程

使用@Controller这个注解,就表明这是一个SpringMVC的控制器!


@Controller
public  class HelloAction  {
    
}

当然了,现在Spring是不知道有这么一个注解的,因此我们需要在配置文件中配置扫描注解

值得注意的是:在配置扫描路径的时候,后面不要加.*

不然扫描不了,我不知道学Struts2还是其他的地方时候,习惯加了.*,于是就搞了很久!

   <!--扫描注解,后面不要加.*-->


    <context:component-scan base-package="zhongfucheng"/>

在控制器中写业务方法

@Controller
public class HelloAction {

    /**
     *
     * @RequestMapping 表示只要是/hello.action的请求,就交由该方法处理。当然了.action可以去掉
     * @param model 它和ModelAndView类似,它这个Model就是把数据封装到request对象中,我们就可以获取出来
     * @return 返回跳转的页面【真实路径,就不用配置视图解析器了】
     * @throws Exception
     */
    @RequestMapping(value="/hello.action")

    public String hello(Model model) throws Exception{
        System.out.println("HelloAction::hello()");
        model.addAttribute("message","你好");
        return "/index.jsp";
    }

}

跳转到index页面,首页得到对应的值。


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  这是我的首页 <br>
  ${message}
  </body>
</html>

《SpringMVC【开发Controller】详解》

当然了,基于注解和基于XML来开发SpringMVC,都是通过映射器、适配器和视图解析器的。 只是映射器、适配器略有不同。但是都是可以省略的!


    <!-- 基于注解的映射器(可选) -->
    <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"/>

更新:上边的适配器和映射器只是Spring3.1版本之前使用的、3.1版本之后现在一般用以下的两个


映射器:
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping


适配器:
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter

当然了,这上面两个配置也可以使用<mvc:annotation-driven>>替代注解处理器和适配器的配置。

RequestMapping

@RequestMapping能够控制请求路径和请求方式!

一个控制器写多个业务方法

到目前为止,我们都是一个控制器写一个业务方法,这肯定是不合理的。我们在Struts2中一个Action就对应多个业务方法了。那么我们在SpringMVC中又怎么写呢???

其实我们可以推理出来,@RequestMapping就是用于配置哪个请求对应哪个业务方法的!


public @interface RequestMapping {
    String[] value() default {};

    RequestMethod[] method() default {};

    String[] params() default {};

    String[] headers() default {};
}

当我们请求hello.action的时候,处理的业务方法是hello()…..当我们请求bye.action的时候,处理的业务方法是bye()


@Controller
public class HelloAction {

    /**
     *
     * @RequestMapping 表示只要是/hello.action的请求,就交由该方法处理。当然了.action可以去掉
     * @param model 它和ModelAndView类似,它这个Model就是把数据封装到request对象中,我们就可以获取出来
     * @return 返回跳转的页面【真实路径,就不用配置视图解析器了】
     * @throws Exception
     */
    @RequestMapping(value="/hello.action")
    public String hello(Model model) throws Exception{
        System.out.println("HelloAction::hello()");
        model.addAttribute("message","你好");
        return "/index.jsp";
    }
    @RequestMapping(value = "/bye.action")
    public String bye(Model model) throws Exception {
        model.addAttribute("message","再见");
        return "/index.jsp";
    }
}

《SpringMVC【开发Controller】详解》

分模块开发

当然了,我们在Struts2常常使用namespace来进行分模块开发,在SpringMVC中我们也可以这样干,并且我们又是使用的是@RequestMapping这个注解!

只要把@RequestMapping这个注解写到类上面去,就代表了分模块。



@Controller
//我们知道,如果是value属性上的注解,我们可以把value省略掉的
@RequestMapping("/zhongfucheng")
public class HelloAction {

    /**
     * @param model 它和ModelAndView类似,它这个Model就是把数据封装到request对象中,我们就可以获取出来
     * @return 返回跳转的页面【真实路径,就不用配置视图解析器了】
     * @throws Exception
     * @RequestMapping 表示只要是/hello.action的请求,就交由该方法处理。当然了.action可以去掉
     */
    @RequestMapping(value = "/hello.action")
    public String hello(Model model) throws Exception {
        System.out.println("HelloAction::hello()");
        model.addAttribute("message", "你好");
        return "/index.jsp";
    }

    @RequestMapping(value = "/bye.action")
    public String bye(Model model) throws Exception {
        model.addAttribute("message", "再见");
        return "/index.jsp";
    }
}

那么我们想要HelloAction该控制器处理我们的请求,访问的地址要么是:http://localhost:8080/zhongfucheng/hello.action,或者要么是http://localhost:8080/zhongfucheng/bye.action

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

我们如果想要限定某个业务控制方法,只允许GET或POST请求方式访问。还是通过@RequestMapping来实现。只要设定它的method属性就行了


    @RequestMapping(value = "/bye.action",method = RequestMethod.POST)
    public String bye(Model model) throws Exception {
        model.addAttribute("message", "再见");
        return "/index.jsp";
    }

当我把业务方法的请求设置为POST以后,我想要通过GET方式来访问该业务方法。就行不通了!

《SpringMVC【开发Controller】详解》

业务方法写入传统web参数

我们的业务方法除了可以写Model这个参数以外,如果有需要我们还可以写request,response等传统Servlet的参数。这是一样可以使用的….

但是呢,我们并不建议使用传统的web参数,因为会耦合


@RequestMapping(method=RequestMethod.POST,value="/register")
    public String registerMethod(HttpServletRequest request,HttpServletResponse response) throws Exception{
        
        //获取用户名和薪水
        String username = request.getParameter("username");
        String salary = request.getParameter("salary");
        System.out.println("用户注册-->" + username + ":" + salary);
        
        //绑定到session域对象中
        request.getSession().setAttribute("username",username);
        request.getSession().setAttribute("salary",salary);
        
        //重定向/jsp/success.jsp页面
        //response.sendRedirect(request.getContextPath()+"/jsp/success.jsp");
        
        //转发/jsp/ok.jsp页面
        request.getRequestDispatcher("/jsp/ok.jsp").forward(request,response);
        
        //转发(提倡)
        return "/jsp/success.jsp";
    }

小细节:如果我们的返回值是返回一个真实路径,而我们在程序中又使用了转发或重定向。。。那么具体跳转的位置就是按我们程序中跳转的路径为准

业务方法收集参数

我们在Struts2中收集web端带过来的参数是在控制器中定义成员变量,该成员变量的名字与web端带过来的名称是要一致的…并且,给出该成员变量的set方法,那么Struts2的拦截器就会帮我们自动把web端带过来的参数赋值给我们的成员变量….

那么在SpringMVC中是怎么收集参数的呢????我们SpringMVC是不可能跟Struts2一样定义成员变量的,因为SpringMVC是单例的,而Struts2是多例的。因此SpringMVC是这样干的:

  • 业务方法写上参数
  • 参数的名称要和web端带过来的数据名称要一致

接收普通参数

如果是普通参数的话,我们直接在方法上写上与web端带过来名称相同的参数就行了!


<form action="${pageContext.request.contextPath}/hello.action" method="post">
    <table align="center">
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>编号</td>
            <td><input type="text" name="id"></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="提交">
            </td>
        </tr>
    </table>

</form>

    @RequestMapping(value = "/hello.action")
    public String hello(Model model, String username, int id) throws Exception {

        System.out.println("用户名是:" + username);
        System.out.println("编号是:" + id);

        model.addAttribute("message", "你好");
        return "/index.jsp";
    }

效果:

《SpringMVC【开发Controller】详解》

接收JavaBean

我们处理表单的参数,如果表单带过来的数据较多,我们都是用JavaBean对其进行封装的。那么我们在SpringMVC也是可以这么做的。

  • 创建Javabean
  • javaBean属性与表单带过来的名称相同
  • 在业务方法上写上Javabean的名称

创建JavaBean,javaBean属性与表单带过来的名称相同


public class User {

    private String id;
    private String username;

    public User() {
    }
    public User(String id, String username) {
        this.id = id;
        this.username = username;
    }
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", username='" + username + '\'' +
                '}';
    }
}

在业务方法参数上写入Javabean


    @RequestMapping(value = "/hello.action")
    public String hello(Model model,User user) throws Exception {

        System.out.println(user);
        model.addAttribute("message", "你好");
        return "/index.jsp";
    }

《SpringMVC【开发Controller】详解》

收集数组

收集数组和收集普通的参数是类似的,看了以下的代码就懂了。


<form action="${pageContext.request.contextPath}/hello.action" method="post">
    <table align="center">
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>爱好</td>
            <td><input type="checkbox" name="hobby" value="1">篮球</td>
            <td><input type="checkbox" name="hobby" value="2">足球</td>
            <td><input type="checkbox" name="hobby" value="3">排球</td>
            <td><input type="checkbox" name="hobby" value="4">羽毛球</td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="提交">
            </td>
        </tr>
    </table>

</form>

业务方法获取参数


    @RequestMapping(value = "/hello.action")
    public String hello(Model model,int[] hobby) throws Exception {


        for (int i : hobby) {
            System.out.println("喜欢运动的编号是:" + i);

        }

        model.addAttribute("message", "你好");
        return "/index.jsp";
    }

效果:

《SpringMVC【开发Controller】详解》

收集List<JavaBean>集合

我们在Spring的业务方法中是不可以用List<JavaBean>这样的参数来接收的,SpringMVC给了我们另一种方案!

我们使用一个JavaBean把集合封装起来,给出对应的set和get方法。那么我们在接收参数的时候,接收的是JavaBean


/**
 * 封装多个Emp的对象 
 * @author AdminTC
 */
public class Bean {
    private List<Emp> empList = new ArrayList<Emp>();
    public Bean(){}
    public List<Emp> getEmpList() {
        return empList;
    }
    public void setEmpList(List<Emp> empList) {
        this.empList = empList;
    }
}

业务方法接收JavaBean对象


    /**
     * 批量添加员工
     */
    @RequestMapping(value="/addAll",method=RequestMethod.POST)
    public String addAll(Model model,Bean bean) throws Exception{
        for(Emp emp:bean.getEmpList()){
            System.out.println(emp.getUsername()+":"+emp.getSalary());
        }
        model.addAttribute("message","批量增加员工成功");
        return "/jsp/ok.jsp";
    }

在JSP页面直接写上empList[下表].


<form action="${pageContext.request.contextPath}/emp/addAll.action" method="POST">
        <table border="2" align="center">
            <caption><h2>批量注册员工</h2></caption>
            <tr>
                <td><input type="text" name="empList[0].username" value="哈哈"/></td>
                <td><input type="text" name="empList[0].salary" value="7000"/></td>
            </tr>
            <tr>
                <td><input type="text" name="empList[1].username" value="呵呵"/></td>
                <td><input type="text" name="empList[1].salary" value="7500"/></td>
            </tr>
            <tr>
                <td><input type="text" name="empList[2].username" value="班长"/></td>
                <td><input type="text" name="empList[2].salary" value="8000"/></td>
            </tr>
            <tr>
                <td><input type="text" name="empList[3].username" value="键状哥"/></td>
                <td><input type="text" name="empList[3].salary" value="8000"/></td>
            </tr>
            <tr>
                <td><input type="text" name="empList[4].username" value="绿同学"/></td>
                <td><input type="text" name="empList[4].salary" value="9000"/></td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <input type="submit" value="批量注册"/>
                </td>
            </tr>
        </table>
    </form>

其实这种方法看起来也没有那么难理解,我们就是向上封装了一层【与接收普通的JavaBean类似的】

收集多个模型

我们有可能在JSP页面上即有User模型的数据要收集,又有Emp模型的数据要收集….并且User模型的属性和Emp模型的属性一模一样….此时我们该怎么办呢???

我们也是可以在User模型和Emp模型上向上抽象出一个Bean,该Bean有Emp和User对象

/**
 * 封装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;
    }
}

在JSP页面收集的时候,给出对应的类型就行了。


    <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>    

字符串转日期类型

我们在Struts2中,如果web端传过来的字符串类型是yyyy-mm-dd hh:MM:ss这种类型的话,那么Struts2默认是可以自动解析成日期的,如果是别的字符串类型的话,Struts2是不能自动解析的。要么使用自定义转换器来解析,要么就自己使用Java程序来解析….

而在SpringMVC中,即使是yyyy-mm-dd hh:MM:ss这种类型SpringMVC也是不能自动帮我们解析的。我们看如下的例子:

JSP传递关于日期格式的字符串给控制器…

<form action="${pageContext.request.contextPath}/hello.action" method="post">
    <table align="center">
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>出生日期</td>
            <td><input type="text" name="date" value="1996-05-24"></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="提交">
            </td>
        </tr>
    </table>

</form>

User对象定义Date成员变量接收


 public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }

业务方法获取Date值


    @RequestMapping(value = "/hello.action")
    public String hello(Model model, User user) throws Exception {

        System.out.println(user.getUsername() + "的出生日期是:" + user.getDate());


        model.addAttribute("message", "你好");
        return "/index.jsp";
    }

结果出问题了,SpringMVC不支持这种类型的参数:

《SpringMVC【开发Controller】详解》

现在问题就抛出来了,那我们要怎么解决呢????

SpringMVC给出类似于Struts2类型转换器这么一个方法给我们使用:如果我们使用的是继承AbstractCommandController类来进行开发的话,我们就可以重写initBinder()方法了….

具体的实现是这样子的:


    @Override
    protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {
        binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
    }

那我们现在用的是注解的方式来进行开发,是没有重写方法的。因此我们需要用到的是一个注解,表明我要重写该方法


    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        binder.registerCustomEditor(
                Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
        
    }

再次访问:

《SpringMVC【开发Controller】详解》

值得注意的是:如果我们使用的是Oracle插入时间的话,那么我们在SQL语句就要写TimeStrap时间戳插入进去,否则就行不通

结果重定向和转发

我们一般做开发的时候,经常编辑完数据就返回到显示列表中。我们在Struts2是使用配置文件进行重定向或转发的:

《SpringMVC【开发Controller】详解》

而我们的SpringMVC就非常简单了,只要在跳转前写上关键字就行了!



    public String hello(Model model, User user) throws Exception {

        System.out.println(user.getUsername() + "的出生日期是:" + user.getDate());
        model.addAttribute("message", user.getDate());
        return "redirect:/index.jsp";
    }

《SpringMVC【开发Controller】详解》

以此类推,如果是想要再次请求的话,那么我们只要写上对应的请求路径就行了!


    @RequestMapping(value = "/hello.action")
    public String hello(Model model, User user) throws Exception {

        return "redirect:/bye.action";
    }

    @RequestMapping("/bye.action")
    public String bye() throws Exception {

        System.out.println("我进来了bye方法");
        return "/index.jsp";
    }

《SpringMVC【开发Controller】详解》

返回JSON文本

回顾一下Struts2返回JSON文本是怎么操作的:

  • 导入jar包
  • 要返回JSON文本的对象给出get方法
  • 在配置文件中继承json-default包
  • result标签的返回值类型是json

那么我们在SpringMVC又怎么操作呢???

导入两个JSON开发包

  • jackson-core-asl-1.9.11.jar
  • jackson-mapper-asl-1.9.11.jar

在要返回JSON的业务方法上给上注解:


    @RequestMapping(value = "/hello.action")
    public
    @ResponseBody
    User hello() throws Exception {

        User user = new User("1", "zhongfucheng");
        return user;
    }

配置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>
    

测试的JSP


    <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:first").click(function(){
            var url = "${pageContext.request.contextPath}/hello.action";
            var sendData = null;
            $.post(url,sendData,function(backData,textStaut,ajax){
                alert(ajax.responseText);
            });
        });
    </script>

测试:

《SpringMVC【开发Controller】详解》

Map测试:


    @RequestMapping(value = "/hello.action")
    public
    @ResponseBody
    Map hello() throws Exception {

        Map map = new HashMap();

        User user = new User("1", "zhongfucheng");
        User user2 = new User("12", "zhongfucheng2");
        map.put("total", user);
        map.put("rows", user2);


        return map;
    }

《SpringMVC【开发Controller】详解》

更新——————————————————————

如果传递进来的数据就是JSON格式的话,我们我们需要使用到另外一个注解@RequestBody,将请求的json数据转成java对象

《SpringMVC【开发Controller】详解》

《SpringMVC【开发Controller】详解》

总结

  • 使用注解的开发避免了继承多余的类,并且非常简洁高效。
  • 想要中文不乱码,仅仅设置request的编码格式是不行的。因为SpringMVC是通过无参的构造器将数据进行封装的。我们可以使用SpringMVC提供的过滤器来解决中文乱码问题。
  • RequestMapping可以设置我们具体的访问路径,还可以分模块开发。基于这么两个原因,我们就可以在一个Action中写多个业务方法了。
  • RequestMapping还能够限制该请求方法是GET还是POST。
  • 在我们的业务方法中,还可以使用传统的request和response等对象,只不过如果不是非要使用的话,最好就别使用了。
  • 对于SpringMVC自己帮我们封装参数,也是需要使用与request带过来的名称是相同的。如果不相同的话,我们需要使用注解来帮我们解决的。
  • 如果是需要封装成集合,或者封装多个Bean的话,那么我们后台的JavaBean就需要再向上一层封装,在业务方法上写上Bean进行了。当然了,在web页面上要指定对应Bean属性的属性
  • 字符串转日期对象用到 @InitBinder注解来重写方法。
  • 返回JSON对象,我们就需要用到@ResponseBody注解,如果接收JSON数据封装成JavaBean的话,我们就需要用到@RequestBody注解。随后在配置文件上创建对应的bean即可。

如果文章有错的地方欢迎指正,大家互相交流。
习惯在微信看技术文章,想要获取更多的Java资源的同学,可以关注微信公众号:Java3y

    原文作者:Java3y
    原文地址: https://segmentfault.com/a/1190000013770006
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞