IDEA創建SpringMVC項目並部署(含Controller和View互相傳值,以及406,415狀態碼的處理)

1.創建項目


勾選SpringMVC 及 web Application(自動勾選),然後下一步

2.項目命名

命名
命名後點finish

3. 在WEB-INF目錄下建classes等目錄

建議建一樣的目錄
在這裏插入圖片描述

4. 配置Tomcat

在這裏插入圖片描述

在這裏插入圖片描述
點擊Configure設置,選擇Tomcat
在這裏插入圖片描述
點擊 + 號添加Tomcat
在這裏插入圖片描述
點擊1號位選擇Tomcat目錄,2號位自動生成,點擊OK保存
在這裏插入圖片描述
出來,選擇剛添加的Tomcat,點擊OK保存
在這裏插入圖片描述

創建Artifact完之後點OK保存

5. 添加類庫

file》Project Structure,選擇Artifact,底部有黃色警告,點擊所選位置,添加類庫
在這裏插入圖片描述
添加完如圖:
在這裏插入圖片描述
點擊OK保存

6. 運行項目

打開index.jsp 點擊右上角在這裏插入圖片描述運行項目
如圖,成功運行項目
在這裏插入圖片描述

7.創建文件並配置

項目已經成功運行了,接下來開始MVC的東西

  1. Controller
    在src目錄下建包(必須要有包名,默認包運行不了),然後創建 HelloWorldController.java 文件,如圖:
    在這裏插入圖片描述 @Controller 說明這個類是一個控制器
    @RequestMapping("/hello") 表示整個控制器的地址是/hello
    @RequestMapping("/hw") 表示 helloWorld()方法的地址是/hw
    return "hw" 表示進入helloWord之後會轉到hw.jsp頁面(需要配置視圖解析器)

  2. 配置前端控制器DispatcherServlet
    實際上項目創建好之後,IDEA已經自動幫我們在web.xml文件中配置好DispatcherServlet了,如圖:
    在這裏插入圖片描述
    <url-pattern>*.from</url-pattern> 表示已 .from 結尾的URL地址,將會請求轉發只相應的控制器處理
    一般情況下本人會將.from改成/

  3. 配置 component-scan
    在dispatcher-servlet.xml文件中配置component-scan,讓系統能找到你所創建好的控制器

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

  4. 配置視圖解析器 ViewResolver

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <!-- 視圖的路徑 -->
       <property name="prefix" value="/WEB-INF/jsp/"/>
       <!-- 視圖名稱後綴  -->
       <property name="suffix" value=".jsp"/>
    </bean>
    
    

    上面控制器 return "hw" 經過視圖解析器的解析會到 /WEB-INF/jsp/ 目錄下找名字爲 hw 後綴名爲 .jsp 的文件

以上全部配置好之後運行項目,輸入 http://localhost:8080/pictureupdate/hello/hw 即可看到如下頁面
在這裏插入圖片描述
url中的pictureupdate 是上面配置Tomcat時設置的項目名,如圖
在這裏插入圖片描述
hellohw 則爲控制器中兩個 @RequestMapping 註解中的地址

  1. 通過返回ModelAndView,跳轉至jsp頁面
@RequestMapping("/hw1")
public ModelAndView helloWorld1() {
    ModelAndView mv = new ModelAndView();
    mv.setViewName("hw1");
    return mv;
}

在瀏覽器中輸入http://localhost:8080/pictureupdate/hello/hw1,即可進入hw1.jsp頁面

8. Controller和View互相傳值

(1)view和Controller互傳簡單類型

hw.jsp 向 controller 傳值,controller 轉向 hw1.jsp(與上面的V向C傳值結合)
controller

	@RequestMapping("hw")
    public String hw(Model model) {

        return "hw";
    }

    @RequestMapping(value = "hw1", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView hw1(String name, String sex, Integer age) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("name", name);
        mv.addObject("sex", sex);
        mv.addObject("age", age);
        mv.setViewName("hw1");
       return mv;
    }

    @RequestMapping(value = "hw2", method = {RequestMethod.GET, RequestMethod.POST})
    public String hw2(String name, String sex, Integer age, Model model) {
        model.addAttribute("name", name);
        model.addAttribute("sex", sex);
        model.addAttribute("age", age);
        return "hw1";
    }

view
hw.jsp

<body>
    <%--<form method="post" action="${pageContext.request.contextPath}/hello/hw1">--%>
    <form method="post" action="${pageContext.request.contextPath}/hello/hw2">
        name:<input type="text" name="name"/>
        sex:<input type="text" name="sex"/>
        age:<input type="text" name="age"/>
        <input type="submit" value="submit">
    </form>
</body>

hw1.jsp

<body>
    name:${name}, sex:${sex}, age:${age}
</body>

###(2)View和Controller互傳對象(Controller用對象接收數據,用對象將數據傳給View)
pojo

:對象必須要有默認構造器,否則會報錯:No default constructor found; nested exception is java.lang.NoSuchMethodExce

public class User {
    private String name;
    private String sex;
    private int age;

    public User() {
        super();
    }

    public User(String name, String sex, int age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }
}

Controller

@Controller
@RequestMapping("/hello")
public class HelloWorldController {

    @RequestMapping("/hw")
    public String helloWorld(){

        return "hw";
    }

    @RequestMapping("/hw1")
    public String helloWorld1(User user, Model model) {
        model.addAttribute("user", user);
        return "hw1";
    }
}

hw.jsp

<body>
    <form method="post" action="${pageContext.request.contextPath}/hello/hw1">
        name:<input type="text" name="user.name"/>
        sex:<input type="text" name="user.sex"/>
        age:<input type="text" name="user.age"/>
        <input type="submit" value="submit">
    </form>
</body>

hw1.jsp

<body>
name: ${user.name}, sex: ${user.sex}, age: ${user.age}
</body>

以上是Controller和View互傳簡單類型和對象的實例

(3)Controller接收json數據並傳回前端

Controller接收json字符串,自動轉換成對象;返回對象,自動轉換成json字符串傳給前端
添加 Jackson.jar 包
Jackson.jar下載地址:http://repo1.maven.org/maven2/com/fasterxml/jackson/core/
在這裏插入圖片描述
在項目中添加jar包:Project Structure》Module
在這裏插入圖片描述
點擊 + ,找到對應的位置將jar包添加進來
點擊 Artifacts ,像上面添加spring的jar包一樣,將Jackson.jar 包添加進項目
在這裏插入圖片描述
Controller

	@RequestMapping("/hw2")
	@ResponseBody
	public User helloWorld(@RequestBody User user) {
		return user;
	}

注:@ResponseBody和@RequestBody分別放不同的位置,不能亂了

運行項目,使用Google瀏覽器插件Restlet進行訪問測試(配置還未完成,訪問 http://localhost:8080/pictureupdate/hello/hw2 將會報錯,並返回406狀態碼)
在這裏插入圖片描述
注:Content-Type 必須是 application/json
填充好數據之後發送請求,將會返回406狀態碼,訪問失敗。需要在spring配置文件(applicationContext.xml)中配置

    <!-- 避免IE執行AJAX時,返回JSON出現下載文件
        spring3爲:MappingJacksonHttpMessageConverter
        spring4爲:MappingJackson2HttpMessageConverter
     -->
    <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!-- 啓動Spring MVC的註解功能,完成請求和註解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" /><!-- json轉換器 -->
            </list>
        </property>
    </bean>

此時如果重啓項目,測試。將會返回 415 狀態碼,訪問還是失敗,還需要在 dispatcher-servlet.xml文件中添加<mvc:annotation-driven />配置。若添加是報錯,則需要在beans標籤中添加配置:
添加屬性:

xmlns:mvc=“http://www.springframework.org/schema/mvc”

xsi:schemaLocation 中添加

http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd

至此完成所有配置,重啓項目,再次測試訪問情況,返回200狀態碼,訪問成功,併成功拿到json數據
在這裏插入圖片描述

IDEA創建SpringMVC項目並部署,C和V傳值(簡單類型,對象,json數據)演示到此結束。
筆者能力有限,有什麼錯誤的或不足之處,可在下方留言或私信探討,互相學習,謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章