java web开发入门六(spring mvc)基于intellig idea


spring mvc

 ssm=spring mvc+spring +mybatis

spring mvc工作流程

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

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

2)映射器根据客户的http请求,再对比<?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_4_0.xsd" version="4.0"> <servlet> <servlet-name>springmvcservlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class> <init-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:springmvc.xmlparam-value> init-param> servlet> <servlet-mapping> <servlet-name>springmvcservlet-name> <url-pattern>*.actionurl-pattern> servlet-mapping> <filter> <filter-name>CharacterEncodingFilterfilter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class> <init-param> <param-name>encodingparam-name> <param-value>utf-8param-value> init-param> filter> <filter-mapping> <filter-name>CharacterEncodingFilterfilter-name> <url-pattern>/*url-pattern> filter-mapping> web-app>

springmvc.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:p="http://www.springframework.org/schema/p"
       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.xsd
          http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx.xsd
          http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/tx/spring-mvc.xsd

">

    
    <bean name="/hello.action" class="com.eggtwo.action.HelloController">bean>

    
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">bean>

    
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter">bean>

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

3.编写Action

package com.eggtwo.action;


import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;


public class HelloController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", "这是我的第二个springmvc应用程序,视图使用逻辑名");

        //原来封装视图的真实路径
     // modelAndView.setViewName("/WEB-INF/jsp/success.jsp");

        String name = request.getParameter("name");//获取表单提交的数据
        System.out.println("姓名:"+name);

        //现在封装视图的逻辑名称
        modelAndView.setViewName("success");

        return modelAndView;
    }

}

注解实现spring mvc

解决的问题:

1.一个controller中放置多个action

2.获取get/post请求的参数(action接收的string类型的date参数怎么转成date)

3.限定action只能接收一种请求方式(get/post)

4.解决表单提交的中文乱码

5.在action中获取request/response

6.在action中重定向

7.action返回值类型(返回html、string、json、file等等)

8.在action中获取request

1.引入jar包:

spring核心包

commons-logging-1.1.3.jar
spring-beans-4.2.5.RELEASE.jar
spring-context-4.2.5.RELEASE.jar
spring-core-4.2.5.RELEASE.jar
spring-expression-4.2.5.RELEASE.jar

spring aop包(注解会使用到aop)

aopalliance.jar
aspectjrt.jar
aspectjweaver.jar
spring-aop-4.2.5.RELEASE.jar

spring mvc包

spring-web-4.2.5.RELEASE.jar
spring-webmvc-4.2.5.RELEASE.jar

2.配置XML:

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_4_0.xsd"
         version="4.0">

    
    <servlet>
        
        <servlet-name>springmvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:spring_annotation.xmlparam-value>
        init-param>
    servlet>
    <servlet-mapping>
        <servlet-name>springmvcservlet-name>
        <url-pattern>*.actionurl-pattern>
    servlet-mapping>


    
    <filter>
        <filter-name>CharacterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>utf-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>




web-app>

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

">
    
    <context:component-scan base-package="com.eggtwo.action">context:component-scan>

    
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">bean>


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

3.开发controller 和action:

package com.eggtwo.action;

import com.eggtwo.entity.Student;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 此控制器是单例模式,构造函数只执行一次
 * 注解控制器
 */
@Controller
@RequestMapping(value = "/anno")
public class AnnotationController {

    public AnnotationController() {
        System.out.println("AnnotationController()");
    }

    @RequestMapping(value = "/login.action")
    public String login(Model model) {
        model.addAttribute("message", "第一个注解实现的spring mvc login");
        return "success";//逻辑名称,需要配置视图解析器
        //return "/WEB-INF/jsp/success.jsp";

    }

    /**
     * 设置请求的url,接收参数的方式,请求的方式(get/post)(默认get/post请求都支持)
     */
    @RequestMapping(value = "/register1.action", method = {RequestMethod.POST, RequestMethod.GET})
    public String register1(Model model, String name, int age, boolean man) {

        model.addAttribute("message", "注册成功");
        return "success";
        // return "/WEB-INF/jsp/success.jsp";

    }

    /**
     * 请求url中的.action可以省略
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(Model model, Student student) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        System.out.println(student.getBirthday());
        model.addAttribute("message", "注册成功");
        model.addAttribute("student", student);

        return "success";
        // return "/WEB-INF/jsp/success.jsp";

    }

    /**
     * 日期类型转换器
     *
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        //设置什么类型的时间格式可以转
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));//true:允许为空, false:不允许为空
    }
}

3.1action向view视图(jsp页面传值)

   @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(Model model, Student student) {     
        model.addAttribute("message", "注册成功");
        model.addAttribute("student", student);
        return "success";   

    }

3.2指定action加载返回的视图(jsp页面)

指定物理视图名称:

return "/WEB-INF/jsp/success.jsp";

指定逻辑视图名称:

 return "success";

逻辑视图需要在spring mvc文件配置视图解析器


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

4.URL配置:

在controller和请求action上配置

@RequestMapping(value = "/anno")

5.请求方式配置:

@RequestMapping(value = "/register1.action", method = {RequestMethod.POST, RequestMethod.GET})
@RequestMapping(value = "/register", method = RequestMethod.POST)

如果不配置method,默认支持所有请求方式

6.请求参数接收:

1.变量直接接收:方法的变量名要和表单的name值保持一致,多用于get查询请求

 @RequestMapping(value = "/register1.action", method = {RequestMethod.POST, RequestMethod.GET})
    public String register1(Model model, String name, int age, boolean man) {

        model.addAttribute("message", "注册成功");
        return "success";
        // return "/WEB-INF/jsp/success.jsp";

    }

2.模型绑定接收:方法的变量名要和表单的name值保持一致,可以设置多个模型,多用于表单提交

 @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(Model model, Student student) {
        System.out.println(student.getBirthday());
        model.addAttribute("message", "注册成功");
        model.addAttribute("student", student);

        return "success";
        // return "/WEB-INF/jsp/success.jsp";

    }

3.数组参数接收:批量删除时用于接收ids,批量添加

ids为checkbox的名称

   @RequestMapping(value = "/batchDelete.action")
    public String register(Model model, Integer[] ids) {
        for(int id :ids){
            System.out.println(id);
        }
        return "success";

    }

4.接收List集合

7.内部转发和重定向

内部 转发,url不变:可以使用model在多个action中传值,因为model是request域对象

 @RequestMapping(value = "/forward.action")
    public String forward(Model model) {
        return "forward:/anno/login.action";
    }

URL重定向,以url后缀的方式进行传值

    @RequestMapping(value = "/go.action")
    public String go(Model model) {
        return "redirect:/anno/login.action?id=3";
    }

8.action返回json和字符串

第一步:导入json包

jackson-annotations-2.6.0-xh.jar

jackson-core-2.6.0-xh.jar

jackson-databind-2.6.0-xh.jar

jackson-jr-all-2.4.3-xh.jar

第二步:在action请求方法上使用@ResponseBody注解表示该方法的返回值放在响应体(Response Body)返回给用户

 第三步:在springmvc xml文件中配置json解析适配器

    
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
            list>
        property>
    bean>

第四步:开发action

返回json 

@RequestMapping(value = "/getJson.action")
    @ResponseBody
    public  Student getJson() {
        Student student = new Student();
        student.setName("测试");
        student.setMan(true);
        student.setBirthday(new Date());
        student.setAge(14);
        student.setScore(12.254);
        return student;
    }

 返回字符串

@RequestMapping(value = "/getString.action",method = RequestMethod.GET)
    @ResponseBody
    public String getString() {
        return "直接返回字符串";
    }

9.在action中获取当前请求的request

在controller中添加如下特性:可以放在baseController



@Autowired
protected HttpServletRequest request; //自动注入request