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

谁说我不能喝 提交于 2019-12-05 08:43:50

spring mvc

 ssm=spring mvc+spring +mybatis

 

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核心控制器,这时核心控制器再将请求转发到具体的视图页面,取出数据,再显示给用户

 

XML实现spring mvc

 

开发步骤:

 

 

注意:使用的spring framework版本是:4.2.5

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

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

2.xml配置

web.xml配置

配置spring mvc核心控制器

解决提交表单中文乱码

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

    <!-- 注册springmvc核心控制器-->
    <servlet>
        <!--servlet-name的值对应一个文件:/WEB-INF/DispatcherServlet-servlet.xml   -->
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <!-- 指定application.xml文件 -->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>


    <!--spring编码过滤器:解决POST提交中文乱码问题-->
    <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>


</web-app>
View Code

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

">

    <!-- 1.注册Action(必须配置) -->
    <bean name="/hello.action" class="com.eggtwo.action.HelloController"></bean>

    <!--2.映射器:如果将bean标签的name属性值作为请求URL.此标签可以省略-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>

    <!--3.适配器:实现了Controller接口的适配器,默认可省略-->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>

    <!--4.视图解析器-->
    <!--
        如果Action中书写的是视图逻辑名称,那么视图解析器就必须配置
        如果Action中书写的是视图真实名称,那么视图解析器就不能配置
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 路径前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 路径后缀 -->
        <property name="suffix" value=".jsp"/>
        <!-- 前缀+视图逻辑名+后缀=真实路径 -->
    </bean>
</beans>
View Code

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

}
View Code

 

 

注解实现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">

    <!-- 注册springmvc核心控制器-->
    <servlet>
        <!--servlet-name的值对应一个文件:/WEB-INF/DispatcherServlet-servlet.xml   -->
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <!-- 指定application.xml文件 -->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring_annotation.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>


    <!--spring编码过滤器:解决POST提交中文乱码问题-->
    <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>




</web-app>
View Code

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

">
    <!--让spring ioc去扫描具体包下的所有具有注解@Controller的类-->
    <context:component-scan base-package="com.eggtwo.action"></context:component-scan>

    <!--注解映射器:可省略-->
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>


    <!--视图解析器-->
    <!--
        如果Action中书写的是视图逻辑名称,那么视图解析器就必须配置
        如果Action中书写的是视图真实名称,那么视图解析器就不能配置
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 路径前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 路径后缀 -->
        <property name="suffix" value=".jsp"/>
        <!-- 前缀+视图逻辑名+后缀=真实路径 -->
    </bean>
</beans>
View Code

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:不允许为空
    }
}
View Code

 

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文件配置视图解析器

<!--视图解析器-->
    <!--
        如果Action中书写的是视图逻辑名称,那么视图解析器就必须配置
        如果Action中书写的是视图真实名称,那么视图解析器就不能配置
    -->
    <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<javaBean>集合

 

 

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解析适配器

    <!-- 注册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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!