资讯专栏INFORMATION COLUMN

SpringMVC【开发Controller】详解

Pines_Cheng / 427人阅读

摘要:是使用拦截器来自动帮我们完成中文乱码的问题的。这是我的首页当然了,基于注解和基于来开发,都是通过映射器适配器和视图解析器的。能够控制请求路径和请求方式一个控制器写多个业务方法到目前为止,我们都是一个控制器写一个业务方法,这肯定是不合理的。

前言

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

编码过滤器

使用注解开发

注解@RequestMapping详解

业务方法接收参数

字符串转日期

重定向和转发

返回JSON

SpringMVC过滤编码器

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

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

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

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

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

    
    
        CharacterEncodingFilter
        
            org.springframework.web.filter.CharacterEncodingFilter
        
        
            encoding
            UTF-8
        
    
    
        CharacterEncodingFilter
        /*
    

注解开发SpringMVC

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

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

开发流程

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

@Controller
public  class HelloAction  {
    
}

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

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

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

   


    

在控制器中写业务方法

@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" %>

  
    $Title$
  
  
  这是我的首页 
${message}

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

    
    

    
    

    
    

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

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


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

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

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";
    }
}

分模块开发

当然了,我们在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方式来访问该业务方法。就行不通了!

业务方法写入传统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端带过来名称相同的参数就行了!

用户名:
编号
    @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";
    }

效果:

接收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";
    }

收集数组

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

用户名:
爱好 篮球 足球 排球 羽毛球

业务方法获取参数

    @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";
    }

效果:

收集List集合

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

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

/**
 * 封装多个Emp的对象 
 * @author AdminTC
 */
public class Bean {
    private List empList = new ArrayList();
    public Bean(){}
    public List getEmpList() {
        return empList;
    }
    public void setEmpList(List 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[下表].

批量注册员工

其实这种方法看起来也没有那么难理解,我们就是向上封装了一层【与接收普通的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页面收集的时候,给出对应的类型就行了。

    
姓名
月薪
入职时间 "/>
字符串转日期类型

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

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

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

用户名:
出生日期

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给出类似于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));
        
    }

再次访问:

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

结果重定向和转发

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

而我们的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";
    }

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

    @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";
    }

返回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适配器

    
        
            
                
                        
                            
                        
                
            
    

测试的JSP

    

测试:

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

更新------------------------------------------------------------------

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

总结

使用注解的开发避免了继承多余的类,并且非常简洁高效。

想要中文不乱码,仅仅设置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

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/68798.html

相关文章

  • spring mvc 常用注解标签详解【转载】

    摘要:分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了注解。的作用相当于,只不过按照自动注入。作用该注解用于将的方法返回的对象,通过适当的转换为指定格式后,写入到对象的数据区。用于注解层,在类上面注解。 原文地址 Controller 在SpringMVC中,控制器Controller负责处理由DispatcherServlet分发的请求,它把用户请求的数据经过业务处理层处理...

    Kylin_Mountain 评论0 收藏0
  • 从SpringBoot到SpringMVC

    摘要:概述用久了,深受其约定大于配置的便利性毒害之后,我想回归到时代,看看开发模式中用户是如何参与的。备注当然本文所使用的全是非注解的配置方法,即需要在中进行配置并且需要遵循各种实现原则。而更加通用主流的基于注解的配置方法将在后续文章中详述。 showImg(https://segmentfault.com/img/remote/1460000015244684); 概述 用久了Sprin...

    xavier 评论0 收藏0
  • spring-MVC源码解读(一)

    摘要:处理器是继前端控制器的后端控制器,在的控制下对具体的用户请求进行处理。由于涉及到具体的用户业务请求,所以一般情况需要程序员根据业务需求开发。 1、mcv整体架构和流程 showImg(https://segmentfault.com/img/bV55Qq?w=860&h=406); 用户发送请求至前端控制器 DispatcherServlet DispatcherServlet 收到...

    I_Am 评论0 收藏0
  • springmvc常用注解标签详解

    摘要:分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了注解。作用该注解用于将的方法返回的对象,通过适当的转换为指定格式后,写入到对象的数据区。用于注解层,在类上面注解。使用标记的参数。 1、@Controller 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个M...

    notebin 评论0 收藏0
  • SpringBoot自动配置原理

    摘要:开启自动配置功能后文详解这个注解,学过的同学应该对它不会陌生,就是扫描注解,默认是扫描当前类下的。简单来说,这个注解可以帮助我们自动载入应用程序所需要的所有默认配置。简单理解这二者扫描的对象是不一样的。 前言 只有光头才能变强。 文本已收录至我的GitHub仓库,欢迎Star:https://github.com/ZhongFuCheng3y/3y 回顾前面Spring的文章(以学习...

    Rainie 评论0 收藏0

发表评论

0条评论

Pines_Cheng

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<