springmvc零配置項目開發流程

最後更新日期:2022-12-07

1. 概述

本篇主要介紹使用springmvc零配置開發項目的過程。

參考博客:《SpringMVC學習(五)——零配置實現SrpingMVC》

博客內容簡潔不全,其源碼託管於:https://gitee.com/leo825/spring-framework-learning-example

1.1 開發環境簡述

操作系統:deepin20.7

vscode:1.73.1,需要安裝java,maven,spring,tomcat相關插件

jdk開發運行環境:

#java環境
export JAVA_HOME=/home/liwl/.jdk_for_dev/jdk-17
export PATH=$JAVA_HOME/bin:$PATH
#tomcat環境
export PATH=/home/liwl/.jdk_for_dev/apache-tomcat-8.5.83/bin:$PATH
#maver環境
export PATH=/home/liwl/.jdk_for_dev/apache-maven-3.8.6/bin:$PATH

項目位置:/home/liwl/Documents/nsccwx/liwldev/java/web/springmvc/

數據庫創建:

# 創建數據庫在,注意數據庫的編碼
create database liwldev_java_web_springmvc charset utf8 collate utf8_general_ci;
# 創建表
use liwldev_java_web_springmvc;
create table t_user_info( `id` int(11) unsigned not null primary key auto_increment comment '用戶ID', `name` varchar(20) default null comment '用戶姓名', `gender` varchar(2) default null comment '用戶性別', `age` varchar(3) default null comment '用戶年紀');
# 授權
grant all privileges on liwldev_java_web_springmvc.* to 'liwl'@'localhost' identified by 'liwanliang';
#
flush privileges;

2. 開發過程

2.1 配置部分

進入項目位置:

cd /home/liwl/Documents/nsccwx/liwldev/java/web/springmvc/

創建項目:

mvn archetype:generate -DgroupId=com.liwl -DartifactId=springmvc_annotation -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

2.1.2 配置pom.xml

編輯pom.xml,引入依賴包:

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.liwl</groupId>
  <artifactId>springmvc_noconfig</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>springmvc_noconfig Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <properties>
    <spring.version>5.3.21</spring.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
  </properties>

  <dependencies>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.29</version> 
    </dependency>
      
    <!-- jsp 標準標籤庫 -->
    <dependency>
      <groupId>org.apache.taglibs</groupId>
      <artifactId>taglibs-standard-spec</artifactId>
      <version>1.2.5</version>
    </dependency>

    <dependency>
      <groupId>org.apache.taglibs</groupId>
      <artifactId>taglibs-standard-impl</artifactId>
        <version>1.2.5</version>
    </dependency>
 
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
    </dependency>
      
    </dependencies>
    
  <build>
    <finalName>springmvc_noconfig</finalName>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</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.1.3 配置web.mxl

編輯web.xml,配置項目,內容如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <!-- WEB應用的名字 -->
    <display-name>springmvc noconfig</display-name>
    <!-- WEB應用的描述 -->
    <description>SpringMVC noconfig demo</description>
    <!-- 歡迎頁面,首頁 -->
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

web.xml實際上不需要做任何配置

2.1.4 配置application.properties

src/main/resources目錄下創建application.properties文件

datasource.driverClassName = com.mysql.cj.jdbc.Driver
datasource.url = jdbc:mysql://localhost:3306/liwldev_java_web_springmvc
datasource.username = bGl3bA==
datasource.password = bGl3YW5saWFuZw==

注:username和password是採用了base64加密後的字符串,可以在後續的編碼過程中,通過方法生成,這裏只是提前寫上

2.2 編碼部分

src/main目錄下創建源碼目錄:mkdir src/main/java/com/liwl/{config,controller,model,service,util}

2.2.1 編寫Base64Util.java

src/main/java/com/liwl/util目錄下創建Base64Util.java,如下:

package com.liwl.util;

import java.util.Base64;

public class Base64Util {

    private static final String CHARSET_UTF_8 = "UTF-8";

    public static String encryptData(String content) throws Exception {
        return Base64.getEncoder().encodeToString(content.getBytes(CHARSET_UTF_8));
    }

    public static String decodeData(String encryptData) throws Exception {
        return new String(Base64.getDecoder().decode(encryptData.getBytes()),CHARSET_UTF_8);
    }

    public static void main(String[] args) throws Exception {
        String user = "liwl";
        String password = "liwanliang";
        System.out.println("user原字符串:"+user+",password原字符串:"+password);
        String encodeUser = encryptData(user);
        String encodePassword = encryptData(password);
        System.out.println("加密後,user:"+encodeUser+",password:"+encodePassword);
        System.out.println("解密後,user:"+decodeData(encodeUser)+",password:"+decodeData(encodePassword));   
    }
}

2.2.2 編寫MyPropertyPlaceholder.java

src/main/java/com/liwl/config/目錄下創建MyPropertyPlaceholder.java,如下:

package com.liwl.config;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PlaceholderConfigurerSupport;

import com.liwl.util.Base64Util;

public class MyPropertyPlaceholder  extends PlaceholderConfigurerSupport {
   
    private final static Map<String,String> propertyMap = new HashMap<>();

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,Properties props) {
        for (Object keyString: props.keySet()) {
            String key = keyString.toString();
            String value = props.getProperty(key);
            if ( "datasource.username".equals(key)|| "datasource.password".equals(key)) {
                try {
                    value = Base64Util.decodeData(value);
                } catch (Exception e) {
                    e.printStackTrace();
                    value = "";
                }
            }
            propertyMap.put(key,value);
        }
    }

    public static String getProperty(String name) {
        return propertyMap.get(name);
    }
}

2.2.3 編寫ApplicationContextConfig.java

src/main/java/com/liwl/conf/目錄下創建ApplicationContextConfig.java,如下:

package com.liwl.config;

import java.io.IOException;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class ApplicationContextConfig extends WebMvcConfigurationSupport {


    @Bean(name = "configProperties")
    public PropertiesFactoryBean propertiesFactoryBean() {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("application.properties"));
        propertiesFactoryBean.setSingleton(true);
        System.out.println("propertiesFactoryBean註冊");
        return propertiesFactoryBean;
    }

    @Bean(name = "propertyConfiguer")
    public MyPropertyPlaceholder propertyPlaceholderConfiguer(PropertiesFactoryBean configProperties) throws IOException {
        MyPropertyPlaceholder propertyPlaceholder = new MyPropertyPlaceholder();
        propertyPlaceholder.setProperties(configProperties.getObject());
        System.out.println("preferencesPlaceholderConfig註冊");
        return propertyPlaceholder;
    }

    //創建jdbcTemplate
    @Bean(name = "jdbcTemplate")
    public JdbcTemplate jdbcTemplate(DriverManagerDataSource driverManagerDataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(driverManagerDataSource);
        System.out.println("jdbcTemplate註冊");
        return jdbcTemplate;
    }

    //創建數據源
    @Bean(name = "driveManagerDataSource")
    public DriverManagerDataSource driverManagerDataSource(MyPropertyPlaceholder propertyPlaceholder) {
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName(MyPropertyPlaceholder.getProperty("datasource.driverClassName"));
        driverManagerDataSource.setUrl(MyPropertyPlaceholder.getProperty("datasource.url"));
        driverManagerDataSource.setUsername(MyPropertyPlaceholder.getProperty("datasource.username"));
        driverManagerDataSource.setPassword(MyPropertyPlaceholder.getProperty("datasource.password"));
        System.out.println("driveManagerDataSource註冊");
        return driverManagerDataSource;
    }
}

2.2.4 編寫MySpringMVCServletConfig.java

src/main/java/com/liwl/config目錄下創建MySpringMVCServletConfig.java,內容如下:

package com.liwl.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@ComponentScan(basePackages = {"com.liwl"},excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX,pattern = "com.liwl.config.*"))
public class MySpringMVCServletConfig extends WebMvcConfigurationSupport {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver= new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
    
}

2.2.5 編寫MyWebApplicationIniaitlizer.java

src/main/java/com/liwl/config目錄下創建MyWebApplicationIniaitlizer.java,內容如下:

package com.liwl.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class MyWebApplicationInitializer implements WebApplicationInitializer {
    

    @Override
    public void onStartup(ServletContext container) {

        //創建spring應用的root上下文
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(ApplicationContextConfig.class);
        System.out.println("ApplicationContextConfig註冊");

        //監聽root上下文
        container.addListener(new ContextLoaderListener(applicationContext));

        //web上下文配置
        AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
        webApplicationContext.register(MySpringMVCServletConfig.class);
        System.out.println("MySpringMVCServletConfig註冊");

        //創建和註冊DispatcherServlet
        ServletRegistration.Dynamic registration = container.addServlet("dispathcer", new DispatcherServlet(webApplicationContext));
        registration.setLoadOnStartup(1);
        registration.addMapping("/");
        System.out.println("dispatcher註冊結束");
    }
}

2.2.6 編寫UserInfo.java

src/main/java/com/liwl/model目錄下創建UserInfo.java,內容如下:

package com.liwl.model;

public class UserInfo {

    private Long id;
    private String name;
    private String age;
    private String gender;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

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

    public String getGender() {
        return gender;
    }
    
    public void setGender(String gender) {
        this.gender = gender;
    }
}

2.2.7 編寫UserInfoSerivce.java

src/main/java/com/liwl/service目錄下創建UserInfoSerivice.java,內容如下:

package com.liwl.service;

import java.util.List;

import com.liwl.model.UserInfo;

public interface UserInfoService {
    void insertUserInfo(UserInfo userInfo);
    void deleteUserInfo(Long id);
    void updateUserInfo(Long id,UserInfo newUserInfo);
    List<UserInfo> getUserInfoList();
}

2.2.8 編寫UserInfoServiceImpl.java

src/main/java/com/liwl/service/impl目錄下創建UserInfoSerivceImpl.java,內容如下:

package com.liwl.service.impl;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import com.liwl.model.UserInfo;
import com.liwl.service.UserInfoService;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public void insertUserInfo(UserInfo userInfo) {
        jdbcTemplate.execute("insert into t_user_info(name,age,gender) values('"+userInfo.getName()+"+"+userInfo.getAge()+"+"+userInfo.getGender()+"')");
    }

    @Override
    public void deleteUserInfo(Long id) {
        jdbcTemplate.execute("delete from t_user_info where id="+id);
    }

    @Override
    public void updateUserInfo(Long id, UserInfo newUserInfo) {
        jdbcTemplate.update("update t_user_info set name=?,age=?,gender=? where id=?",new Object[]{
            new UserInfo().getName(),
            new UserInfo().getAge(),
            new UserInfo().getGender(),
        });
    }

    @Override
    public List<UserInfo> getUserInfoList() {
        List<UserInfo> userInfos = new ArrayList<>();
        List<Map<String,Object>> results = jdbcTemplate.queryForList("select * from t_user_info");
        for (Map<String,Object> obj: results){
            UserInfo userInfo = new UserInfo();
            userInfo.setId((Long) obj.get("id"));
            userInfo.setName((String) obj.get("name"));
            userInfo.setAge((String) obj.get("age"));
            userInfo.setGender((String) obj.get("gender"));
            userInfos.add(userInfo);
        }
        return userInfos;
    }    
}

2.2.9 編寫GetUserInfoController.java

src/main/java/com/liwl/controller目錄下創建GetUserInfoController.java,內容如下:

package com.liwl.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.liwl.model.UserInfo;
import com.liwl.service.UserInfoService;

@Controller
public class GetUserInfoController {

    @Autowired
    UserInfoService userInfoService;
    
    @RequestMapping("/getuserinfo")
    public ModelAndView getUserInfo(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) {
        ModelAndView modelAndView = new ModelAndView();
        List<UserInfo> userInfoList = userInfoService.getUserInfoList();
        modelAndView.addObject("data",userInfoList);
        modelAndView.setViewName("info");
        return modelAndView;
    }
}

2.2.10 編寫info.jsp

src/main/webapp/WEB-INF/views下創建info.jsp,內容如下:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<h2>跳轉到success了!!!</h2>
<p>
    <c:forEach items="${data}" var="d">
        <tr><td>${d.id}</td></tr>
        <tr><td>${d.name}</td></tr>
        <tr><td>${d.age}</td></tr>
        <tr><td>${d.gender}</td></tr>
        </br>
    </c:forEach>
</p>
</body>
</html>

編譯以後,訪問:http://localhost:8080/springmvc_noconfig/getuserinfo

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