最后更新日期: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
标签:java,springmvc,流程,配置,org,liwl,import,com,public From: https://www.cnblogs.com/liwanliangblog/p/16962816.html