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請求。

如有不當之處請多多指教,如對你有所幫助,請留言或點贊予以支持,謝謝!

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