springmvc全注解项目开发流程
最后更新日期:2022-12-01
1. 概述
本篇主要介绍使用springmvc全注解开发项目的过程。
参考博客:《SpringMVC学习(二)——快速搭建SpringMVC开发环境(注解方式)》
博客内容简洁不全,其源码托管于: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 配置部分
2.1.1 maven创建项目
进入到项目位置:
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_annotation</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>springmvc_annotation 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_annotation</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.xml
编辑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">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>springmvc_annotation</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc_annotation-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc_annotation</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
web.xml里面通过contextConfigLocation
参数,引入了springmvc_annotaion-servlet.xml
配置,在resources目录下创建springmvc_annotation-servlet.xml
2.1.4 配置servlet.xml
在resources目录下创建springmvc_annotation-servlet.xml,内容如下:
需要注意的是xmlns的配置,如果配置有问题,则无法识别mvc标签
<?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-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
default-lazy-init="true">
<!-- 处理器映射器,将处理器Handler的name作为URL进行查找 -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
<!-- 处理器适配器,适配处理器中handlerRequest方法的调用 -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
<!-- 配置视图解析器,把handler方法返回的逻辑视图解析为实际的物理视图 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:annotation-driven></mvc:annotation-driven>
<context:component-scan base-package="com.liwl"></context:component-scan>
</beans>
2.1.5 配置jdbc.properties
在src/main/resources/
目录下创建jdbc.properties
文件
jdbc.driver = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/liwldev_java_web_springmvc
jdbc.username = liwl
jdbc.password = liwanliang
2.2 编码部分
/src/main/
下创建源码目录:
mkdir src/main/java/com/liwl/{config,controller,model,service,util}
2.2.1 编写SpringmvcConfig.java
在src/main/java/com/liwl/config
目录下,创建``SpringmvcConfig.java`,如下:
package com.liwl.config;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import com.mchange.v2.c3p0.ComboPooledDataSource;
@Configuration
@ComponentScan("com.liwl")
@PropertySource("classpath:jdbc.properties")
public class SpringmvcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource")
public DataSource jdbcProperties() {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass(driver);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean("jdbcTemplate")
public JdbcTemplate returnJdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
}
2.2.5 编写UserInfo.java
在src/main/java/com/liwl/model
下创建UserInfo.java
,如下:
此类对应数据库liwldev_java_web_springmvc的表t_user_info的各个字段
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.6 编写UserInfoService.java
在src/main/java/com/liwl/service
目录下,创建UserInfoService.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.7 编写UserInfoServiceImpl.java
在src/main/java/com/liwl/service/impl
目录下,创建UserInfoServiceImpl.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.8 编写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) throws Exception{
ModelAndView modelAndView = new ModelAndView();
List<UserInfo> userInfoList = userInfoService.getUserInfoList();
modelAndView.addObject("data",userInfoList);
modelAndView.setViewName("info");
return modelAndView;
}
}
2.2.9 编写info.jsp
在src/main/webapp/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_xml_annotation/getuserinfo