Java學習筆記之:Spring MVC 環境搭建

1、建立項目

1.新建java動態項目javascript

2.在web-inf/lib文件夾下導入jarjava

3.建立所須要的包和文件jquery

 

2、搭建SpringMVC

1.配置web.xml(WEB-INF下)web

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>springmvc-spring-ibatis</display-name>

    <!-- springmvc的配置 -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <!-- 配置Spring mvc下的配置文件的位置和名稱 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc/sping.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 配置字符集亂碼 -->
    <filter>
        <description>字符集過濾</description>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <description>字符集編碼</description>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- spring的配置 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/spring_*.xml</param-value>
    </context-param>
</web-app>

2.在springmvc包裏建立「spring,xml」並配置springmvc的配置文件ajax

<?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"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
     <!-- 配置自動掃描的包 -->
    <context:component-scan base-package="com.mxp.controller"></context:component-scan>

    <!-- 加載靜態資源 -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <mvc:default-servlet-handler />

    <!-- 配置視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

3.在controller包裏建立"UserController.ava"spring

package com.hgd.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 控制層:com.hgd.action  || com.hgd.controller
 * 服務層:com.hgd.service (將接口和實現類分開com.hgd.service.imp)
 * 持久層:com.hgd.dao (com.hgd.dao.imp) || com.hgd.mapper
 * 視圖層:jsp...
 *
 */
@Controller("userController")
@RequestMapping("/userController")
public class UserController {

    @RequestMapping("login")
    public String login() throws Exception {
        System.out.println("login");
        return "main";
    }
}

注意:1. 首先要在類的前面添加「Controller」註解,表示是spring的控制器,這裏會寫一個方法hello()json

   2. hello方法上方有一個@RequestMapping, 是用於匹配請求的路徑,好比這裏匹配的請求路徑就是「http://localhost:8080/SpingMVC/userController/login」。spring-mvc

4.頁面調試,在index.jsp加入超連接mvc

<a href="userController/login">login</a>

5.當咱們點擊超連接,控制檯會輸出「login」而且調到main.jspapp

6.若是咱們須要傳入參數能夠在方法中加入參數,並在超連接中寫出

    @RequestMapping("login")
    public String login(String user,int age)throws Exception{
        System.out.println("login");
        System.out.println(user+"\t"+age);
        return "main";
    }
<a href="userController/login?user=admin&age=20">login</a>

返回結果:

3、傳入obj類型參數

 1.在model包中建立javabean 

package com.hgd.model;

public class User {

    private String name;
    private int age;

    public User() {
        // TODO Auto-generated constructor stub
    }
        
    public User(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + "]";
    }

}

2.在usercontroller中寫上方法

   @RequestMapping("obj")
    public String obj(User user,HttpServletRequest req)throws Exception{
        System.out.println("obj");
        System.out.println(user);
        req.setAttribute("msg", "request");
        return "main";
    }

3.測試方法

<a href="userController/obj?name=admin&age=35">obj</a>

4.測試結果

4、傳入ajax

1.WebContent下建立jquery文件夾,導入「jQuery文件」,在index.jsp加入js

<script type="text/javascript">

function ajax(){
    
    $.getJSON('userController/getString',{name:'admin'},function(data){
        alert(typeof data +"||"+data.msg);
    });
    
    
}

2.在json包中建立json.java用來發送數據

package com.hgd.json;

public class Json {
    
    private String msg;
    
    public Json() {
        // TODO Auto-generated constructor stub
    }
    
    public void setMsg(String msg) {
        this.msg = msg;
    }
    
    public String getMsg() {
        return msg;
    }

}

3.usercontroller中寫上方法

    @RequestMapping("getString")
    @ResponseBody//@responsebody表示該方法的返回結果直接寫入HTTP
    public Json getString(String name)throws Exception{
        System.out.println(name);
        Json j = new Json();
        j.setMsg("數據");
        return j;
    }

4.測試方法

<a href="javascript:ajax()">ajax</a>

5.測試結果

5、傳入 map

1.在js代碼塊中添加一個函數

function map(){
	$.getJSON('userController/map',function(data){
	});
}

2.usercontroller中寫上方法

    @RequestMapping("map")
    @ResponseBody
    public Map<String, Object> map()throws Exception{
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("A", new User("admin-1",25));
        map.put("B", new User("admin-2",20));
        map.put("C", new User("admin-3",25));
        return map;
    }

3.測試方法

<a href="javascript:map()">map</a>

4.測試結果,F12打開控制檯,能夠看到響應

6、傳入list

1.在js代碼塊中添加一個函數

function list(){
    $.getJSON('userController/list',function(data){
        alert(data.length)
    });
}

2.usercontroller中寫上方法

    @RequestMapping("list")
    @ResponseBody
    public Collection list()throws Exception{
        List<User> list = new ArrayList<User>();
        for (int i = 0; i < 5; i++) {
            list.add(new User("admin"+i, i));
        }        
        return list;
    }

3.測試方法

<a href="javascript:list()">list</a>

4.測試結果,打出list的長度。

相關文章
相關標籤/搜索