Java- SpringMVC篇:注解式开发@controller--洪族99

SpringMVC是一个比struts2更快捷的MVC框架,它的特点就是注解式开发,方便快捷,但是运行速度稍微比struts2慢一点。

首先,导入SpringMVC的依赖。

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.10.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

spring-webmvc:SpringMVC的核心依赖。

servlet:在传递数据时会用到。

接下来,是web.xml:

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>

   
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <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>


</web-app>

 SpringMVC的入口是一个servlet,所以后缀为.action的请求都将被分配到各个controller内,由控制器里的方法处理。

SpringMVC需要一个配置文件:springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">


    <context:component-scan base-package="com.hc.controller"></context:component-scan>

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

  xmlns:context :需要手动copy配置。

context:component-scan:注解扫描器,base-package是控制器所在的包。

InternalResourceViewResolver:视图解析,解析controller所返回的值,将值变为一个jsp的名字(路径)。例如:controller的返回值是First,经过解析后变为/First.jsp,并且进入First.jsp。

prefix:前缀

suffix:后缀

最后,在java文件目录中建controller包,FirstController.java

package com.hc.controller;

import com.hc.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@SessionAttributes("uid")

@Controller
public class FirstController {

    @RequestMapping("**/first")
//    @RequestMapping(value = "/first",method = RequestMethod.GET)
    public String first(@RequestParam("uid") int uid, Map map){
        map.put("uid",uid);
        return "insert";
    }

//"redirect:success.jsp"

    @RequestMapping("/value")
    public String value(Student student,HttpServletRequest request){
        request.setAttribute("student",student);
        return "success";
    }

    @RequestMapping("/student")
    public ModelAndView student(Student student){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("student",student);
        modelAndView.setViewName("success");
        return modelAndView;
    }


}

controller相当于struts2中的action。

@Controller:在class上,必须加上Controller注解,声明这个class是一个Controller

@RequestMapping("/first"):这个first就是所请求的first.action

@RequestMapping("/?/first"):匹配first.action前的一级目录,即允许first.action前有一级目录,且目录只能是一个,如:a、b等。

@RequestMapping("/*/first"):匹配一级目录,但是目录可以是多个字符

@RequestMapping("**/first"):允许多级目录

@RequestMapping(value = "/first",method = RequestMethod.GET):指定这个方法只能被以GET方式提交的first.action所调用。

 public String value(Student student){

}

Student 是对象,可自动收集,并且,页面输入框的name只需要是对象的属性名即可。不需要像struts2那样,对象名.属性名

@RequestParam("uid"):获取所提交的数据,可以不声明。

return "redirect:success.jsp":代表重定向,不转发数据

@SessionAttributes("uid"):这是session,储存名为uid的值。但是,

map.put("uid",uid)  uid是被Map所存放。

传递数据的第一种方式:

public String first(@RequestParam("uid") int uid, Map map){

}
 

在传入参的位置,定义Map,并且map.put("uid",uid),页面即可用EL表达式接收并展示。注意:EL表达式必须标明:

isELIgnored="false"

传递数据的第二种方式:

public String value(Student student,HttpServletRequest request){

}

定义request,通过作用域传值。

 request.setAttribute("student",student)即可。

也可以,

 session.setAttribute("student",student)

传递数据的第三种方式:

public ModelAndView student(Student student){

}

模型视图

modelAndView.addObject("student",student):保存参数。
modelAndView.setViewName("success"):保存应该返回的返回值,即页面jsp的名字。

接下来,测试:

在web.xml配置:

    <welcome-file-list>
        <welcome-file>/first.jsp</welcome-file>
    </welcome-file-list

项目启动后,就会进入这个first.jsp

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018/11/2
  Time: 17:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="/first.action?uid=115">来了,大人</a>
<a href="/students.action">students</a>



</body>
</html>

测试SpringMVC

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018/11/2
  Time: 19:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<a href="/students.action">students</a>
<a href="/insert.jsp">insert</a>


    <form action="/likeStudent.action" method="post">

        <input type="text" name="likeStr">
        <input type="submit" value="搜索">
    </form>


${student.stuId}<br>
${student.stuName}
花样


</body>
</html>

SpringMVC开发效率高,被大量使用!

猜你喜欢

转载自blog.csdn.net/qq_43532342/article/details/83687160