IDEA 创建 Spring MVC 基于JSP 详细教程 (一)

一、使用DEA创建项目 

  1. 新建项目file-new -project

 

 2.新建一个maven project,并且选择webapp原型。 

3.填写GroupId和ArtifactId,

GroupID 是项目组织唯一的标识符,实际对应JAVA的包的结构,是main目录里java的目录结构,一般域名+公司名。 

ArtifactID是项目的唯一的标识符,实际对应项目的名称,就是项目根目录的名称。 

4.项目目录结构

5.根据对项目的任意目录进行这五种目录类型标注。

6. 包结构设置

二 、搭建项目

  1. 准备好之后,开始配置SpringMVC ,先是配置 pom.xml文件。
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.hf</groupId>
  <artifactId>springmvc</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>springmvc Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>


  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
<!-- 标记库用于视图层的支持 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
      <scope>runtime</scope>
    </dependency>

    <!--spring相关包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

  </dependencies>

  <build>
    <finalName>springmvc</finalName>
    <resources>
    
    </resources>

    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>


</project>

2. 接下来配置web 文件,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 xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd "
         version="3.0">
    <display-name>Archetype Created Web Application</display-name>

    <!-- 配置引用spring-mvc.xml -->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!-- 启动时加载spring-mvc.xml -->
            <param-value>classpath:spring-mvc.xml</param-value>
            <!--<param-value>/WEB-INF/spring-mvc.xml</param-value>-->
        </init-param>
        <!-- 启动时加载spring-mvc.xml 的优先级高-->
        <load-on-startup>1</load-on-startup>
    </servlet>

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

</web-app>

在web.xml 配置中设置spring-servlet.xml的加载路径
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-mvc.xml</param-value>
        </init-param>
上面的这个是可以不用配置的,框架默认在/WEB-INF/下 自己扫描对应的XXX--mvc.xml配置文件,也可以自己指定;同时也可把配置文件指定到 resources 目录下,本例则是放在resources 目录下。

3. 配置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:context="http://www.springframework.org/schema/context"
       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/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd ">

    <!-- 开启spring的扫描注入,使用如下注解 -->
    <!-- @Component,@Repository,@Service,@Controller-->
    <!-- 错误点 com.hf.controller 不能扫描到service ,dao等-->
    <context:component-scan base-package="com.hf"/>

    <!-- 开启springMVC的注解驱动,使得url可以映射到对应的controller -->
    <mvc:annotation-driven />

    <!-- 视图解析 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

注意点:新建项目需要引入下图红框中的链接,用于支持MVC注解驱动。

<!-- 开启springMVC的注解驱动,使得url可以映射到对应的controller --> 
<mvc:annotation-driven />

4. 配置基本完成,接下来进行controller ,service ,dao,pojo 的代码编写。

  • Controller 层代码
package com.hf.controller;

import com.hf.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;


/**
 * @Description:
 * @author: 
 * @date: 2018/10/17 13:32
 * @Version: 1.0
 */
@Controller
@RequestMapping("student")
public class StudentController {

//    @Resource(name = "studentService")
    @Autowired
    private StudentService studentService;
    //get 错误点   地址栏请求属于get请求,因此method方法不能使用post
    @RequestMapping(value = "/getStudents",method = RequestMethod.GET)
    public ModelAndView getStudent(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("studentDis");
        mav.addObject("student",studentService.getStudents());
        return mav;
    }

}
  • Service 层代码
package com.hf.service;

import com.hf.dao.StudentDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description:
 * @author:
 * @date: 2018/10/17 13:33
 * @Version: 1.0
 */
@Service("studentService")
public class StudentService {

    /**
     *   @Autowired  自动注入   或者
     *   @Resource(name = "studentDao")
     **/
//    @Resource(name = "studentDao")
    @Autowired
    private StudentDao studentDao;

   public List getStudents(){
     return studentDao.findStudentAll();
   }
}
  • dao 层代码
package com.hf.dao;

import com.hf.pojo.Student;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @author:
 * @date: 2018/10/17 13:34
 * @Version: 1.0
 */
@Repository("studentDao")
public class StudentDao {

    public List<Student> findStudentAll(){

        List<Student> students = new ArrayList<>();
        students.add(new Student("1", "tom", 58, true));
        students.add(new Student("5", "yao", 26, true));
        students.add(new Student("3", "ming", 18, true));
        students.add(new Student("66", "liu", 22, true));
        return students;
    }
}
  • pojo 代码
package com.hf.pojo;

import java.io.Serializable;

/**
 * @Description:
 * @author:
 * @date: 2018/10/17 13:36
 * @Version: 1.0
 */
public class Student implements Serializable {

    private String id;
    private String name;
    private int age;
    private boolean sex;

   public Student(){    }

    public Student(String id, String name, int age, boolean sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

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

    public boolean isSex() {
        return sex;
    }

    public void setSex(boolean sex) {
        this.sex = sex;
    }
}
  • 页面jsp代码
<%--
  Created by IntelliJ IDEA.
  User: ygxzz
  Date: 2018/10/17
  Time: 13:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Spring MVC Hello World</title>
</head>

<body>
<h2>学生列表</h2>
<table border="1">
    <tr>
        <th>Id</th>
        <th>名字</th>
        <th>年龄</th>
        <th>性别</th>
    </tr>
    <%--console.log(student);--%>
    <%--console.log(${student});--%>
    <%--request:${requestScope.message}<br/>--%>
    <c:forEach  items="${student}" var="student">
        <tr>
            <td>${student.id}</td>
            <td>${student.name}</td>
            <td>${student.age}</td>
            <td>${student.sex}</td>
        </tr>
    </c:forEach>
</table>

</body>
</html>

 

三 、 配置本地 Tomcat。

  • 选择 Edut Configurations

  • 选择+号,添加Tomcat。

  • 配置 server 中的tomcat。

  • 配置Deployment 。

  • 配置结果如下图。

  • 启动Tomcat。

四、访问项目

在地址栏中输入 :http://localhost:8080 + controller别名 + 方法别名  如下:

http://localhost:8080/student/getStudents

页面效果如图:

五、项目中遇到的错误点。

  • 项目启动后,加载报错。

错误原因:由于spring-mvc.xml  文件扫描包的范围定义不对。

    <!-- 开启spring的扫描注入,使用如下注解 -->
    <!-- @Component,@Repository,@Service,@Controller-->
    <!-- 错误点 com.hf.controller 不能扫描到service ,dao等-->
    <context:component-scan base-package="com.hf.controller"/>

解决方法:去掉controller 层包。

<!-- 开启spring的扫描注入,使用如下注解 -->
    <!-- @Component,@Repository,@Service,@Controller-->
    <context:component-scan base-package="com.hf"/>
  • 项目访问时,报错

报错原因:请求类型不正确

解决,地址栏请求属于get请求。

如有不当之处请多多指教,如对你有所帮助,请留言或点赞予以支持,谢谢!

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