SpringMVC进阶

1.springmvc(注解版本)

注解扫描

<?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-3.0.xsd">

    <!--让spring容器去扫描注释-->
    <context:component-scan base-package="com.juaner.app14"/>

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

Action类

@Controller
public class HelloAction {
    public HelloAction(){
        System.out.println(this .hashCode() );
    }
    @RequestMapping(value = "/hello.action")
    public String hello(Model model)throws Exception{
        System.out.println("hello");
        model.addAttribute("message","this is the first....");
        return "success";
    }

    @RequestMapping(value = "/bye.action")
    public String bye(Model model)throws Exception{
        System.out.println("bye");
        model.addAttribute("message","bye");
        return "success";
    }
}

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

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

    @RequestMapping(value = "/register")
    public String register(Model model)throws Exception{
        model.addAttribute("message","注册成功");
        return "/jsp/success.jsp";
    }
    @RequestMapping(value = "/login")
    public String login(Model model)throws Exception{
        model.addAttribute("message","登录成功");
        return "/jsp/success.jsp";
    }
}

3.在业务控制方法中写入普通变量收集参数,限定某个业务控制方法,只允许GET或POST请求方式访问

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

    @RequestMapping(method= RequestMethod.POST,value = "/register")
    public String register(Model model,String username,double salary)throws Exception{
        System.out.println(username+salary);
        model.addAttribute("message","注册成功");
        return "/jsp/success.jsp";
    }
    @RequestMapping(value = "/login", method= {RequestMethod.POST,RequestMethod.GET})
    public String login(Model model,String username,double salary)throws Exception{
        System.out.println(username+salary);
        model.addAttribute("message","登录成功");
        return "/jsp/success.jsp";
    }
}

4.在业务控制方法中写入HttpServletRequest,HttpServletResponse,Model等传统web参数

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

    @RequestMapping(method= RequestMethod.POST,value = "/register" )
    public void  register(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String username = request.getParameter("username");
        String salary = request.getParameter("salary");

        System.out.println(username+salary);
        request.setAttribute("message","转发参数");
//        response.sendRedirect(request.getContextPath()+"/jsp/success.jsp");
        request.getRequestDispatcher("/jsp/success.jsp").forward(request,response);
    }
}

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

  jsp中的元素name属性不用加user.前缀

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

    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        //向springmvc中注册一个自定义的类型转换器
        //参数一:将string转成什么类型的字节码
        //参数二:自定义转换规则
        binder.registerCustomEditor(Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
    }
    @RequestMapping(method= RequestMethod.POST,value = "/register" )
    public String   register(User user, Model model)throws Exception{
        System.out.println("用户注册");
        model.addAttribute("user",user);
        System.out.println(new Timestamp(user.getHiredate().getTime()));

        return "/jsp/success.jsp";
    }
}

  在业务控制方法中写入User,Admin多个模型收集参数,需要更大的模型包装User,Admin

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

@Controller
@RequestMapping(value = "/emp")
public class EmpAction {
    @RequestMapping(value = "/deleteAll",method = RequestMethod.POST)
    public String deleteAll(Model model,int[] id)throws Exception{
        for(int i:id)
        {
            System.out.println(i);
        }
        model.addAttribute("message","批量删除员工成功");
        return "/jsp/success.jsp";
    }
}

jsp

<form action="${pageContext.request.contextPath}/emp/deleteAll.action" method="post">
    <table>
        <tr><th>
            编号
        </th><th>
            姓名
        </th></tr>

        <tr>
            <td>
                <input type="checkbox" name="id" value="1123">
            </td>
            <td>哈哈</td>
        </tr>
        <tr>
            <td>
                <input type="checkbox" name="id" value="2123">
            </td>
            <td>嘻嘻</td>
        </tr>
        <tr>
            <td>
                <input type="checkbox" name="id" value="3">
            </td>
            <td>呵呵</td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="提交">
            </td>
        </tr>
    </table>
</form>

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

bean

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

action

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

jsp

<form action="${pageContext.request.contextPath}/emp/addAll.action" method="post">
    <table>
        <tr>
            <td><input name="empList[0].username" type="text" value="哈哈"></td>
            <td><input name="empList[0].salary" type="text" value="6000"></td>
        </tr>
        <tr>
            <td><input name="empList[1].username" type="text" value="呵呵"></td>
            <td><input name="empList[1].salary" type="text" value="7000"></td>
        </tr>
        <tr>
            <td><input name="empList[2].username" type="text" value="嘻嘻"></td>
            <td><input name="empList[2].salary" type="text" value="8000"></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input  type="submit" value="注册"></td>
        </tr>
    </table>
</form>

8.结果的转发和重定向

@Controller
@RequestMapping(value="/emp")
public class EmpAction {

    @RequestMapping(value="/find")
    public String findEmpById(int id,Model model) throws Exception{
        System.out.println("查询"+id+"号员工信息");

        //转发到EmpAction的另一个方法中去,即再次发送请求
        return "forward:/emp/update.action";

        //重定向到EmpAction的另一个方法中去,即再次发送请求
        //return "redirect:/emp/update.action?id=" + id;

    }

    @RequestMapping(value="/update")
    public String updateEmpById(int id,Model model) throws Exception{
        System.out.println("更新" + id +"号员工信息");
        model.addAttribute("message","更新员工信息成功");
        return "/jsp/ok.jsp";
    }

}

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

1.导入包jackson-core-asl-1.9.11、jackson-mapper-asl-1.9.11

2.配置json转换器

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

3.方法名中加注解

    /**
     * @ResponseBody Emp 表示让springmvc将Emp对象转成json文本
     */
    @RequestMapping(value="/bean2json")
    public @ResponseBody Emp bean2json() throws Exception{
        //创建Emp对象
        Emp emp = new Emp();
        emp.setId(1);
        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(new Emp(1,"哈哈",7000D,new Date()));
        empList.add(new Emp(2,"呵呵",8000D,new Date()));
        empList.add(new Emp(3,"嘻嘻",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(new Emp(1,"哈哈",7000D,new Date()));
        empList.add(new Emp(2,"呵呵",8000D,new Date()));
        empList.add(new Emp(3,"嘻嘻",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;
    }
    
时间: 2024-08-07 21:33:17

SpringMVC进阶的相关文章

SpringMVC进阶(二)

一.高级参数绑定 1.1. 绑定数组 Controller方法中可以用String[]接收,或者pojo的String[]属性接收.两种方式任选其一即可. /** * 包装类型 绑定数组类型,可以使用两种方式,pojo的属性接收,和直接接收 * * @param queryVo * @return */ @RequestMapping("queryItem") public String queryItem(QueryVo queryVo, Integer[] ids) { Syste

SpringMVC 进阶版

请求限制 一些情况下我们可能需要对请求进行限制,比如仅允许POST,GET等... RequestMapping注解中提供了多个参数用于添加请求的限制条件 value 请求地址 path 请求地址 method 请求方法 headers 请求头中必须包含指定字段 params 必须包含某个请求参数 consumes 接受的数据媒体类型 (与请求中的contentType匹配才处理) produce 返回的媒体类型 (与请求中的accept匹配才处理) 案例: @RequestMapping(va

Spring注解开发系列 VIII --- SpringMVC

SpringMVC是三层架构中的控制层部分,有过JavaWEB开发经验的同学一定很熟悉它的使用了.这边有我之前整理的SpringMVC相关的链接: 1.SpringMVC入门 2.SpringMVC进阶 3.深入SpringMVC注解 看过之后大致对springmvc有一个了解,但对于真正完全掌握springmvc还差得远,本篇博客主要针对的是springmvc的注解开发,传统的项目使用spingmvc避免不了地需要在web.xml里配置前端控制器等等,想要在项目中优雅地去掉这些配置,还得学习如

SpringMVC使用进阶-内置对象和跳转

内置对象和页面跳转是web开发中比较重要的组成部分,springmvc作为新生代的框架,对这方面的支持也还算不错,这次着重分享跳转方式和内置对象的使用 一   页面跳转 页面跳转分为客户端跳转和服务端跳转两种,在springmvc中使用跳转是比较简单的,只需在return后面写就可以了 (1)客户端跳转 return "redirect:user.do?method=reg5"; return "redirect:http://www.baidu.com"; (2)

BootStrap-validator 使用记录(JAVA SpringMVC实现)

BootStrap 是一个强大的前面框架,它用优雅的方式解决了网页问题.最近正在使用其开发网站的表单验证,一点体会记录如下: 注:本文中借鉴了博客Franson 的文章<使用bootstrapvalidator的remote验证经验> 一.准备工作 1.你的网站环境中要有 BootStrap,中文网地址:http://www.bootcss.com/ 2.下载BootStrap Validator相关材料,地址:http://bv.doc.javake.cn/ 当然,如果你不想一个一个下载到您

springmVC源码分析之拦截器

一个东西用久了,自然就会从仅使用的层面上升到探究其原理的层面,在javaweb中springmvc更是如此,越是优秀的框架,其底层实现代码更是复杂,而在我看来,一个优秀程序猿就相当于一名武林高手,不断进阶武功秘籍,越是高深莫测的功夫,越是要探究其原理,而springmvc就是一本十分深奥的武功秘籍. 说起拦截器,说不得不和过滤器进行对比,在此贴图一张不进行多加解释,简单的来说拦截器能作用于controller层方法实现的前后. 在这里先列出一个简单的controller层的实现 正常访问之后我们

10本Java精选书籍助你快速进阶Java顶尖程序员

书是人类进步的阶梯,从某种意义上讲,一个人读书多少,跟这个人将来能有多大成就取得多大成功有着必然的联系,然而读书不仅仅是求量的过程,还需要精读.有选择的读,前面的文章给大家介绍过从零基础学习java编程到精通之路的五本书籍,但是Java学习入门之后,想要往更高层次的Java方向发展,如果能有几本好书的辅助,可以使我们在Java进阶之路上事半功倍,那么下面亦是美网络小编再给大家推荐10本Java精选书籍助你进阶Java顶尖程序员. 1.<深入理解Java虚拟机:JVM高级特性与最佳实践> 本书从

Java进阶之路

Java进阶之路--从初级程序员到架构师,从小工到专家. 怎样学习才能从一名Java初级程序员成长为一名合格的架构师,或者说一名合格的架构师应该有怎样的技术知识体系,这是不仅一个刚刚踏入职场的初级程序员也是工作三五年之后开始迷茫的老程序员经常会问到的问题.希望这篇文章会是你看到过的最全面最权威的回答. 一: 编程基础 不管是C还是C++,不管是Java还是PHP,想成为一名合格的程序员,基本的数据结构和算法基础还是要有的.下面几篇文章从思想到实现,为你梳理出常用的数据结构和经典算法. 1-1 常

JMS学习之路(一):整合activeMQ到SpringMVC

JMS的全称是Java Message Service,即Java消息服务.它主要用于在生产者和消费者之间进行消息传递,生产者负责产生消息,而消费者负责接收消息.把它应用到实际的业务需求中的话我们可以在特定的时候利用生产者生成一消息,并进行发送,对应的消费者在接收到对应的消息后去完成对应的业务逻辑.对于消息的传递有两种类型,一种是点对点的,即一个生产者和一个消费者一一对应:另一种是发布/订阅模式,即一个生产者产生消息并进行发送后,可以由多个消费者进行接收. 整合activeMQ到springmv