springmvc非注解项目开发流程


1. 概述

本篇主要介绍使用springmvc非注解开发项目的过程。

参考博客:《SpringMVC学习(一)——快速搭建SpringMVC开发环境(非注解方式)》

博客内容简洁不全,其源码托管于:https://gitee.com/leo825/spring-framework-learning-example

1.1 开发环境简述

本篇主要使用了vscode远程开发模式。

远程主机

远程虚拟机(centos7.9)部署Java开发环境:

#jdk环境
export JAVA_HOME=/opt/javaenv/jdk-17
export PATH=$JAVA_HOME/bin:$PATH
#tomcat环境
export PATH=/opt/javaenv/apache-tomcat-8.5.81/bin:$PATH
#maver环境
export PATH=/opt/javaenv/apache-maven-3.8.6/bin:$PATH

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

项目创建命令:mvn archetype:generate -DgroupId=com.liwl.java -DartifactId=liwl_springmvc_xml -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

本地工具

本地使用的操作系统(win10/deepin20.6),代码编辑器:vscode1.69.0

vscode插件:Java开发插件,Maven for java, Community Server Connectors

2. 开发过程

2.1 maven创建项目

进入到项目位置:cd /home/liwl/Documents/nsccwx/liwldev/java/web/springmvc/

创建项目:mvn archetype:generate -DgroupId=com.liwl.java -DartifactId=liwl_springmvc_xml -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

使用vscode远程管理功能,连接远程主机后,打开目录:/home/liwl/Documents/nsccwx/liwldev/java/web/springmvc/liwl_springmvx_xml即可进行开发

2.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.java</groupId>
  <artifactId>liwl_springmvc_xml</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>liwl_springmvc_xml 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>

    <!-- servlet接口 -->
    <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>
      <scope>provided</scope>
    </dependency>

    <!-- jstl 标签库  -->
    <dependency>  
      <groupId>javax.servlet</groupId>  
      <artifactId>jstl</artifactId>  
      <version>1.2</version>  
      <scope>runtime</scope>  
    </dependency>  
    <!-- jsp 标准标签库 -->
  <dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
  </dependency>

  </dependencies>

  <build>
    <finalName>liwl_springmvc_xml</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.3 web.xml配置项目

通过web.xml配置项目的servlet

<?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>liwl_springmvc_by_xml</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:liwl-springmvc-servlet.xml</param-value>
    </init-param>
  </servlet>

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

</web-app>

在web.xml里面指定了加载liwl-springmvc-servlet.xml。

2.4 springmvc.xml配置mvc内容

在resources目录下,创建liwl-springmvc-servlet.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 处理器映射器,将处理器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>

</beans>

2.5 编写controller和测试

  1. 创建目录src/main/java/com/liwl/controller,在该目录下创建HelloController.java文件,
package com.liwl.controller;

import java.util.List;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

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

public class HelloController implements Controller{

    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("data","测试成功");
        modelAndView.setViewName("success");
        return modelAndView;
    }
}
  1. 创建文件webapp/WEB-INF/views/success.jsp,内容如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<h2>跳转到success了!!!</h2>
    <p>
        ${data}
    </p>
</body>
</html>
  1. 在resources/liwl-springmvc-servlet.xml注册bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 处理器映射器,将处理器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>
    
    <bean id="helloController" name="/hello" class="com.liwl.controller.HelloController"></bean>

</beans>
  1. 右键启动项目插件SERVERS下的:Community Server Connector,然后添加Tomcat服务器,指定Tomcat为本地的/home/liwl/.jdk_for_dev/apache-tomcat-8.5.81目录,并且右键启动。
  2. 使用vscode的插件maven对项目进行编译,编译完成,在生成的target目录下,右键liwlspringmvc.war,执行Run on Server
  3. 浏览器访问http://localhost:8080/liwlspringmvc/hello

2.6 增加数据库配置

pom.xml已经引入了数据库的依赖包(此过程本部分略,上文pom.xml已经引入)。

在deepin系统安装mariadb:sudo apt install mariadb-server,执行:sudo systemctl start mariadb && sudo systemctl enable mariadb启动数据库同时设置开机启动。执行:sudo mysql使用MySQL的root账号进行授权设置。

创建数据库

# 创建数据库在,注意数据库的编码
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 '用户年纪');
MariaDB [liwldev_java_web_springmvc]> desc t_user_info;
+--------+------------------+------+-----+---------+----------------+
| Field  | Type             | Null | Key | Default | Extra          |
+--------+------------------+------+-----+---------+----------------+
| id     | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
| name   | varchar(20)      | YES  |     | NULL    |                |
| gender | varchar(2)       | YES  |     | NULL    |                |
| age    | varchar(3)       | YES  |     | NULL    |                |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.000 sec)

授权登录:

grant all privileges on liwldev_java_web_springmvc.* to 'liwl'@'localhost' identified by 'liwanliang';
flush privileges;

修改web.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 处理器映射器,将处理器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>

    <!-- Spring内置连接池 -->
    <bean id="driverManagerDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/liwldev_java_web_springmvc"></property>
        <property name="username" value="liwl"></property>
        <property name="password" value="liwanliang"></property>
    </bean>

    <!--指定连接池-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="driverManagerDataSource"></property>
    </bean>

    <bean id="beanUtil" class="com.liwl.util.ApplicationContextUtil"></bean>
    <bean id="userInfoService" class="com.liwl.service.impl.UserInfoServiceImpl"></bean>
    <bean id="helloController" name="/hello" class="com.liwl.controller.HelloController"></bean>

</beans>

2.7 编码部分

2.7.1 创建util目录

在该目录下创建ApplicationContextUtil.java类

package com.liwl.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextUtil implements ApplicationContextAware{

    private static ApplicationContext applicationContext;

    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
        
    }

    public static <T> T getBean(String beanName,Class<T> clazz){
        return clazz.cast(getBean(beanName));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtil.applicationContext = applicationContext;     
    }
    
}

解析数据库的类DBUtil.java

用于获取applicationcontext.xml定义的jdbcTemplate的bean。

package com.liwl.util;

import org.springframework.jdbc.core.JdbcTemplate;

public class DBUtil {
    public static JdbcTemplate getJdbcTemplate() {
       return (JdbcTemplate)  ApplicationContextUtil.getBean("jdbcTemplate");
    } 
}

2.7.2 创建model

src/main/java/com/liwl/下创建model目录,在model下创建UserInfo.java

此类对应数据库liwldev_java_web_springmvc的表t_user_info的各个字段

package com.liwl.model;

public class UserInfo {
    Long id;
    String name;
    String gender;
    String age;

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

    public Long getId() {
        return id;
    }
    
    public void setName(String name) {
        this.name = name;
    }

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

    public String getGender() {
        return gender;
    }

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

    public String getAge() {
        return age;
    }
    
    @Override
    public String toString() {
        return "用户信息:::"+"name:"+name+",age:"+age+",gender:"+gender;
    }
}

2.7.3 创建service目录

service目录下创建UserInfoService.java接口。创建impl目录,该目录下的UserInfoServiceImpl.java是UserInfoService.java的具体实现

接口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();
}

实现类UserInfoServiceImpl.java

package com.liwl.service.impl;

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

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

public class UserInfoServiceImpl implements UserInfoService{

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

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

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

    @Override
    public List<UserInfo> getUserInfoList() {
        List<UserInfo> userInfos = new ArrayList<>();
        List<Map<String,Object>> results = DBUtil.getJdbcTemplate().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.setGender((String) obj.get("gender"));
            userInfo.setAge((String) obj.get("age"));
            userInfos.add(userInfo);
        }
        return userInfos;
    }
    
}

2.7.4 创建controller文件

在controller目录下修改HelloController.java类

package com.liwl.controller;

import java.util.List;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

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

public class HelloController implements Controller{

    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        UserInfoService userInfoService = (UserInfoService) ApplicationContextUtil.getBean("userInfoService");
        ModelAndView modelAndView = new ModelAndView();
        List<UserInfo> userInfoList = userInfoService.getUserInfoList();
        modelAndView.addObject("data",userInfoList);
        modelAndView.setViewName("success");
        return modelAndView;
    }
}

2.7.5 修改success.jsp

修改success.jsp,内容如下

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ 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/liwl_springmvc_xml/hello,即可获取数据库信息

原创文章,作者:745907710,如若转载,请注明出处:https://blog.ytso.com/273812.html

(0)
上一篇 2022年7月12日
下一篇 2022年7月12日

相关推荐

发表回复

登录后才能评论