Java学习笔记之:Spring MVC 环境搭建

一、创建项目

1.新建java动态项目

2.在web-inf/lib文件夹下导入jar

3.创建所需要的包和文件

 

二、搭建SpringMVC

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

<?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的配置文件

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

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()

   2. hello方法上方有一个@RequestMapping, 是用于匹配请求的路径,比如这里匹配的请求路径就是“http://localhost:8080/SpingMVC/userController/login”。

4.页面调试,在index.jsp加入超链接

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

5.当我们点击超链接,控制台会输出“login”并且调到main.jsp

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>

返回结果:

三、传入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.测试结果

四、传入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.测试结果

五、传入 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打开控制台,可以看到响应

六、传入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的长度。

 

posted @ 2016-12-06 20:56  HuTiger  阅读(10548)  评论(0编辑  收藏  举报