Springboot JSP项目如何以war、jar方式运行

文章目录

  • 一,序
  • 二,样例代码
    • 1,代码结构
    • 2,完整代码备份
  • 三,准备工作
    • 1. pom.xml 引入组件
    • 2. application.yml 指定jsp配置
  • 四,war方式运行
    • 1. 修改pom.xml文件
    • 2. mvn执行打包
  • 五,jar方式运行
    • 1. 修改pom-jsp-jar.xml文件
    • 2. 修改 spring-boot-maven-plugin添加版本号
    • 3. 添加资源文件配置(`Jar运行必须`)
    • 4. mvn执行打包
  • 六,war、jar方式运行配置文件区别

一,序

Spring Boot 官方不推荐使用JSP来作为视图,但是仍有部分项目使用了JSP视图,Springboot JSP项目运行方式有war、Jar两种方式。

二,样例代码

1,代码结构

在这里插入图片描述

2,完整代码备份

如何使用下面的备份文件恢复成原始的项目代码,请移步查阅:神奇代码恢复工具

//goto Dockerfile
#基础镜像
FROM openjdk:8-jre-alpineRUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone#把你的项目war包引入到容器的root目录下
COPY target/*.war /app.warCMD ["--server.port=8080"]#项目的启动方式
#ENTRYPOINT ["java","-Xmx400m","-Xms400m","-Xmn150m","-Xss1024k","-jar","/app.war", "--spring.profiles.active=prod"]
ENTRYPOINT ["java","-jar","/app.war"]
//goto pom-jsp-jar.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.fly</groupId><artifactId>docker-demo</artifactId><version>0.0.1</version><packaging>jar</packaging><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.4.RELEASE</version><relativePath /></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.build.timestamp.format>yyyyMMdd-HH</maven.build.timestamp.format><docker.hub>registry.cn-shanghai.aliyuncs.com</docker.hub><java.version>1.8</java.version><skipTests>true</skipTests></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-log4j2</artifactId></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><scope>compile</scope></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>20.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency><!-- JSTL for JSP --><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId></dependency><!-- For JSP compilation --><dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId><scope>provided</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope></dependency></dependencies><build><finalName>${project.artifactId}-${project.version}</finalName><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>1.4.2.RELEASE</version></plugin><!-- 添加docker-maven插件 --><plugin><groupId>io.fabric8</groupId><artifactId>docker-maven-plugin</artifactId><version>0.41.0</version><executions><execution><phase>package</phase><goals><goal>build</goal><goal>push</goal><goal>remove</goal></goals></execution></executions><configuration><!-- 连接到带docker环境的linux服务器编译image --><!-- <dockerHost>http://192.168.182.10:2375</dockerHost> --><!-- Docker 推送镜像仓库地址 --><pushRegistry>${docker.hub}</pushRegistry><images><image><!--推送到私有镜像仓库,镜像名需要添加仓库地址 --><name>${docker.hub}/00fly/${project.artifactId}:${project.version}-UTC-${maven.build.timestamp}</name><!--定义镜像构建行为 --><build><dockerFileDir>${project.basedir}</dockerFileDir></build></image><image><name>${docker.hub}/00fly/${project.artifactId}:${project.version}</name><build><dockerFileDir>${project.basedir}</dockerFileDir></build></image></images></configuration></plugin></plugins><resources><resource><directory>src/main/java</directory><excludes><exclude>**/*.java</exclude></excludes></resource><resource><directory>src/main/resources</directory><includes><include>**/**</include></includes></resource><resource><directory>src/main/webapp</directory><includes><include>**/**</include></includes><targetPath>META-INF/resources</targetPath></resource></resources></build>
</project>
//goto 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.fly</groupId><artifactId>docker-demo</artifactId><version>0.0.1</version><packaging>war</packaging><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.4.RELEASE</version><relativePath /></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.build.timestamp.format>yyyyMMdd-HH</maven.build.timestamp.format><docker.hub>registry.cn-shanghai.aliyuncs.com</docker.hub><java.version>1.8</java.version><skipTests>true</skipTests></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-log4j2</artifactId></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><scope>compile</scope></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>20.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency><!-- JSTL for JSP --><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId></dependency><!-- For JSP compilation --><dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId><scope>provided</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope></dependency></dependencies><build><finalName>${project.artifactId}-${project.version}</finalName><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin><!-- 添加docker-maven插件 --><plugin><groupId>io.fabric8</groupId><artifactId>docker-maven-plugin</artifactId><version>0.41.0</version><executions><execution><phase>package</phase><goals><goal>build</goal><goal>push</goal><goal>remove</goal></goals></execution></executions><configuration><!-- 连接到带docker环境的linux服务器编译image --><!-- <dockerHost>http://192.168.182.10:2375</dockerHost> --><!-- Docker 推送镜像仓库地址 --><pushRegistry>${docker.hub}</pushRegistry><images><image><!--推送到私有镜像仓库,镜像名需要添加仓库地址 --><name>${docker.hub}/00fly/${project.artifactId}:${project.version}-UTC-${maven.build.timestamp}</name><!--定义镜像构建行为 --><build><dockerFileDir>${project.basedir}</dockerFileDir></build></image><image><name>${docker.hub}/00fly/${project.artifactId}:${project.version}</name><build><dockerFileDir>${project.basedir}</dockerFileDir></build></image></images></configuration></plugin></plugins><resources><resource><directory>src/main/java</directory><excludes><exclude>**/*.java</exclude></excludes></resource><resource><directory>src/main/resources</directory><includes><include>**/**</include></includes></resource><resource><directory>src/main/webapp</directory><includes><include>**/**</include></includes><targetPath>META-INF/resources</targetPath></resource></resources></build>
</project>
//goto shell\docker\1-n\docker-compose.yml
version: '3'
services:demo-dk:image: demo-dk:1.0build:context: .dockerfile: Dockerfilecontainer_name: demo_dkdeploy:resources:limits:cpus: '0.50'memory: 300Mreservations:memory: 128Mports:- 8085:8085- 8086:8086- 8087:8087logging:driver: json-fileoptions:max-size: 5mmax-file: '1'
//goto shell\docker\1-n\Dockerfile
#基础镜像
FROM openjdk:8-jre-alpineRUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo 'Asia/Shanghai' >/etc/timezone#把你的项目war包引入到容器的root目录下
COPY *.war /app.warRUN echo \
"#!/bin/sh\n"\
"nohup java -jar /app.war --server.port=8085 &\n"\
"nohup java -jar /app.war --server.port=8086 &"\
>> /start.shRUN chmod +x /start.sh
CMD nohup sh -c "/start.sh && java -jar /app.war --server.port=8087"
//goto shell\docker\1-n\restart-docker.sh
#!/bin/bash
docker-compose down && docker system prune -f && docker-compose build && docker-compose up -d
//goto shell\docker\1-n\start.sh
#!/bin/bash# 命令后加入 & ,保持程序后台持续运行
nohup java -jar /app.war --server.port=8085 & 
nohup java -jar /app.war --server.port=8086 &# 死循环,保持docker前台运行
while [[ true ]]; dosleep 1
done//goto shell\docker\1-n\start2.sh
#!/bin/bash# 命令后加入 & ,保持程序后台持续运行
nohup java -jar /app.war --server.port=8085 & 
java -jar /app.war --server.port=8086
//goto shell\docker\scale\docker-compose.yml
version: '3.8'
services:nginx:image: nginx:alpinecontainer_name: nginxdeploy:resources:limits:cpus: '0.80'memory: 50Mreservations:memory: 30Mports:- 80:80restart: on-failurevolumes:- ./nginx/nginx.conf:/etc/nginx/nginx.conf- ./nginx/conf.d:/etc/nginx/conf.dlogging:driver: 'json-file'options:max-size: '5m'max-file: '1'  depends_on:- demodemo:hostname: demoimage: registry.cn-shanghai.aliyuncs.com/00fly/docker-demo:0.0.1deploy:resources:limits:cpus: '0.80'memory: 200Mreservations:memory: 100Menvironment:- JAVA_OPTS=-server -Xms128m -Xmx128m -Djava.security.egd=file:/dev/./urandomrestart: on-failurelogging:driver: 'json-file'options:max-size: '5m'max-file: '1'
//goto shell\docker\scale\restart.sh
#!/bin/bash
docker-compose --compatibility restart
//goto shell\docker\scale\scale.sh
#!/bin/bash
docker-compose --compatibility up -d --scale nginx=1 --scale demo=3 
//goto shell\docker\scale\stop.sh
#!/bin/bash
docker-compose down
//goto shell\docker\single\docker-compose.yml
version: '3'
services:docker-demo:image: registry.cn-shanghai.aliyuncs.com/00fly/docker-demo:0.0.1container_name: docker-demodeploy:resources:limits:cpus: '0.80'memory: 300Mreservations:cpus: '0.05'memory: 100Mports:- 80:8080restart: on-failurelogging:driver: json-fileoptions:max-size: 5mmax-file: '1'
//goto shell\docker\single\restart.sh
#!/bin/bash
docker-compose down && docker system prune -f && docker-compose up -d
//goto shell\docker\single\stop.sh
#!/bin/bash
docker-compose down
//goto shell\init.sh
#!/bin/bash
dos2unix *
dos2unix */*
dos2unix */*/*chmod +x *.sh
chmod +x */*.sh
//goto shell\reload-jar.sh
#!/bin/bash
# get pidpname="springboot-cache.jar"
echo  -e  "jar-name=$pname\r\n"get_pid(){pid=`ps -ef | grep $pname | grep -v grep | awk '{print $2}'`echo "$pid"
}ps -ef|grep $pnamePID=$(get_pid)
if [ -z "${PID}" ] 
thenecho -e "\r\nJava Application already stop!"
elseecho -e '\r\nkill -9  '${PID} '\r\n'kill -9 ${PID}echo -e "Java Application is stop!"
firm -rf info.logecho -e "\r\nJava Application will startup!\r\n"
jar_path=`find .. -name $pname`#echo "jarfile=$jar_path"nohup java -jar $jar_path --server.port=8181 >>./info.log 2>&1 &ps -ef|grep $pname
//goto shell\reload-war.sh
#!/bin/bash
# get pid
get_pid(){pname="docker-demo.war"pid=`ps -ef | grep $pname | grep -v grep | awk '{print $2}'`echo "$pid"
}ps -ef|grep docker-demo.warPID=$(get_pid)
if [ -z "${PID}" ] 
thenecho -e "\r\nJava Application already stop!"
elseecho -e '\r\nkill -9  '${PID}kill -9 ${PID}echo -e "Java Application is stop!"
firm -rf info.logecho -e "\r\nJava Application will startup!"
nohup java -jar /work/demo/web/docker-demo.war -Xms64m -Xmx64m --server.port=8181 >>./info.log 2>&1 &
#sleep 2s
#nohup java -jar /work/demo/web/docker-demo.war -Xms64m -Xmx64m --server.port=8182 >>./info.log 2>&1 &ps -ef|grep docker-demo.warecho -e "please visit: https://test.00fly.online/user/"#tail -f info.log
//goto shell\start-service.sh
#!/bin/bash 
java -jar docker-demo.war -Xms64m -Xmx64m --server.port=8083 &
//goto src\main\java\com\fly\common\AnnotationHelper.java
package com.fly.common;import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;import lombok.extern.slf4j.Slf4j;/*** * 注解处理工具类* * @author 00fly* @version [版本号, 2020-04-16]* @see [相关类/方法]* @since [产品/模块版本]*/
@Slf4j
public class AnnotationHelper
{private static List<String> cacheList = new ArrayList<>();private AnnotationHelper(){super();}/*** 得到类上面的注解信息* * @param scannerClass* @param allowInjectClass* @return*/private static Annotation getClassAnnotation(Class<?> scannerClass, Class<? extends Annotation> allowInjectClass){if (!scannerClass.isAnnotationPresent(allowInjectClass)){return null;}return scannerClass.getAnnotation(allowInjectClass);}/*** 使用Java反射得到注解的信息* * @param annotation* @param methodName* @return Exception*/private static Object getAnnotationInfo(Annotation annotation, String methodName)throws Exception{if (annotation == null){return null;}Method declaredMethod = annotation.getClass().getDeclaredMethod(methodName, null);return declaredMethod.invoke(annotation, null);}/*** 从上下文获取 Controller注解类的 RequestMapping注解url信息* * @param applicationContext* @return* @throws Exception* @see [类、类#方法、类#成员]*/public static List<String> getRequestMappingURL(ApplicationContext applicationContext)throws Exception{if (cacheList.isEmpty()){synchronized (AnnotationHelper.class){List<String> list = new ArrayList<>();Map<String, Object> map = applicationContext.getBeansWithAnnotation(Controller.class);for (String key : map.keySet()){Class<?> clazz = map.get(key).getClass();Annotation classAnnotation = getClassAnnotation(clazz, RequestMapping.class);Object object = getAnnotationInfo(classAnnotation, "value");if (object != null){String[] array = (String[])object;log.info("{} -> {}", clazz.getName(), object);for (String it : array){if (!it.contains("$")){list.add(it);}}}}cacheList = list;}}return cacheList;}
}
//goto src\main\java\com\fly\common\AuthorizationInterceptor.java
package com.fly.common;import java.net.InetAddress;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;/*** * AuthorizationInterceptor* * @author 00fly* @version [版本号, 2019年7月21日]* @see [相关类/方法]* @since [产品/模块版本]*/
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter
{@AutowiredApplicationContext applicationContext;@Value("${server.port}")String port;@AutowiredHttpSession session;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception{if (session.getAttribute("urls") == null){session.setAttribute("urls", AnnotationHelper.getRequestMappingURL(applicationContext));session.setAttribute("port", port);session.setAttribute("ip", InetAddress.getLocalHost().getHostAddress());}return true;}
}
//goto src\main\java\com\fly\common\WebMvcConfig.java
package com.fly.common;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/*** * WebMvcConfig* * @author 00fly* @version [版本号, 2019年7月21日]* @see [相关类/方法]* @since [产品/模块版本]*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer
{@Autowiredprivate AuthorizationInterceptor authorizationInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry){registry.addInterceptor(authorizationInterceptor).addPathPatterns("/user/**");}
}
//goto src\main\java\com\fly\demo\model\User.java
package com.fly.demo.model;import java.io.Serializable;import lombok.Data;
import org.hibernate.validator.constraints.Range;import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;@Data
public class User implements Serializable
{private static final long serialVersionUID = -4621975403168327735L;private Long userId;@NotBlank(message = "用户名不能为空")private String userName;@NotNull(message = "年龄不能为空")@Range(min = 10, max = 60, message = "年龄必须在{min}-{max}")private Integer age;private String desc;
}
//goto src\main\java\com\fly\demo\service\impl\UserServiceImpl.java
package com.fly.demo.service.impl;import java.util.List;import javax.annotation.PostConstruct;import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Service;import com.fly.demo.model.User;
import com.fly.demo.service.UserService;
import com.google.common.collect.Lists;import lombok.extern.slf4j.Slf4j;@Slf4j
@Service
public class UserServiceImpl implements  UserService
{private List<User> users = Lists.newArrayList();private Long sequence = 1L;/*** 初始化* * @see [类、类#方法、类#成员]*/@PostConstructpublic void init(){log.info("PostConstruct users");for (int i = 0; i < 5; i++){User user = new User();user.setUserId(sequence);user.setUserName("user_" + sequence);user.setAge(RandomUtils.nextInt(10, 40));user.setDesc("This is a user " + sequence);users.add(user);sequence++;}}private void insert(User user){log.info("insert user : {}", user);user.setUserId(sequence + 1);users.add(user);sequence++;}private void update(User user){log.info("update user id = {}", user.getUserId());for (User it : users){if (it.getUserId().equals(user.getUserId())){it.setUserName(user.getUserName());it.setAge(user.getAge());it.setDesc(user.getDesc());return;}}}/*** 新增/根据id更新* * @param user* @see [类、类#方法、类#成员]*/@Overridepublic void saveOrUpdate(User user){if (user.getUserId() != null){update(user);return;}insert(user);}@Overridepublic void delete(Long userId){log.info("delete user id = {}", userId);for (User user : users){if (user.getUserId().equals(userId)){users.remove(user);return;}}}@Overridepublic User get(Long userId){log.info("get user id = {}", userId);for (User user : users){if (user.getUserId().equals(userId)){return user;}}return null;}@Overridepublic List<User> list(){log.info("list users");return users;}
}
//goto src\main\java\com\fly\demo\service\UserService.java
package com.fly.demo.service;import java.util.List;import com.fly.demo.model.User;public interface UserService
{void saveOrUpdate(User user);void delete(Long userId);User get(Long userId);List<User> list();}
//goto src\main\java\com\fly\demo\web\IndexController.java
package com.fly.demo.web;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;import com.fly.common.AnnotationHelper;/*** * IndexController* * @author 00fly* @version [版本号, 2020-04-16]* @see [相关类/方法]* @since [产品/模块版本]*/
@Controller
public class IndexController
{@AutowiredApplicationContext applicationContext;/*** 首页* * @param model* @return* @throws Exception* @see [类、类#方法、类#成员]*/@GetMapping("/")public String index(Model model)throws Exception{model.addAttribute("urls", AnnotationHelper.getRequestMappingURL(applicationContext));return "/index";}
}
//goto src\main\java\com\fly\demo\web\UserApi.java
package com.fly.demo.web;import javax.validation.Valid;import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;import com.fly.demo.model.User;
import com.fly.demo.service.UserService;import lombok.extern.slf4j.Slf4j;@Slf4j
@Controller
@RequestMapping("/user")
public class UserApi
{@Autowiredprivate UserService userService;/*** 测试添加缓存,后续读取从缓存中取* * @param userId* @return* @see [类、类#方法、类#成员]*/@GetMapping("get")public User get(Long userId){return userService.get(userId);}/*** 新增/更新数据* * @param user* @return* @see [类、类#方法、类#成员]*/@PostMapping("/add")public String add(@Valid @ModelAttribute("item") User user, Errors errors, Model model){if (errors.hasErrors()){StringBuilder errorMsg = new StringBuilder();for (ObjectError error : errors.getAllErrors()){errorMsg.append(error.getDefaultMessage()).append(" ");}if (errorMsg.length() > 0){log.info("errors message={}", errorMsg);}model.addAttribute("items", userService.list());return "/user/show";}userService.saveOrUpdate(user);return "redirect:/user/list";}/*** 测试删除缓存*/@GetMapping("/delete/{id}")public String delete(@PathVariable Long id){userService.delete(id);return "redirect:/user/list";}@GetMapping({"/", "/list"})public String list(Model model){User user = new User();if (RandomUtils.nextInt(1, 10) > 1){user.setUserName(RandomStringUtils.randomNumeric(5));user.setAge(RandomUtils.nextInt(10, 70));user.setDesc(RandomStringUtils.randomNumeric(5));}model.addAttribute("item", user);model.addAttribute("items", userService.list());return "/user/show";}/*** 编辑数据* * @param id* @param model* @return* @see [类、类#方法、类#成员]*/@GetMapping("/update/{id}")public String update(@PathVariable Long id, Model model){model.addAttribute("item", userService.get(id));model.addAttribute("items", userService.list());return "/user/show";}
}
//goto src\main\java\com\fly\DemoBootApplication.java
package com.fly;import java.net.InetAddress;import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;import lombok.extern.slf4j.Slf4j;@Slf4j
@SpringBootApplication
public class DemoBootApplication
{@Value("${server.port}")Integer port;public static void main(String[] args){SpringApplication.run(DemoBootApplication.class, args);}@Bean@ConditionalOnWebApplicationCommandLineRunner openBrowser(){return args -> {if (SystemUtils.IS_OS_WINDOWS && port > 0){log.info("★★★★★★★★  now open Browser ★★★★★★★★ ");String ip = InetAddress.getLocalHost().getHostAddress();String url = "http://" + ip + ":" + port;Runtime.getRuntime().exec("cmd /c start /min " + url);}};}
}
//goto src\main\resources\application.yml
server:port: 8080
spring:mvc:view:prefix: /WEB-INF/viewssuffix: .jsp
//goto src\main\webapp\WEB-INF\views\index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<table><tr><th colspan="${fn:length(urls)+1}">Navigate</th></tr><tr><c:forEach var="item" items="${urls}"><td><a href="${pageContext.request.contextPath}${item}/">${item}</a></td></c:forEach></tr>
</table>
//goto src\main\webapp\WEB-INF\views\user\show.jsp
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<meta charset="utf-8">
<html>
<head>
<title>00fly功能演示</title>
<style>
body {margin: 10;font-size: 62.5%;line-height: 1.5;
}.blue-button {background: #25A6E1;padding: 3px 20px;color: #fff;font-size: 12px;border-radius: 2px;-moz-border-radius: 2px;-webkit-border-radius: 4px;border: 1px solid #1A87B9
}table {width: 70%;
}th {background: SteelBlue;color: white;
}td, th {border: 1px solid gray;font-size: 12px;text-align: left;padding: 5px 10px;overflow:hidden; white-space:nowrap; text-overflow:ellipsis;max-width: 200px;
}
</style>
</head>
<script type="text/javascript">function formReset() {location.href="/user/list";}
</script>
<body><center><table><tr><th colspan="${fn:length(urls)+1}">Navigate</th></tr><tr><c:forEach var="item" items="${urls}"><td><a href="${pageContext.request.contextPath}${item}/">${item}</a></td></c:forEach></tr></table>    <form:form method="post" modelAttribute="item" action="${pageContext.request.contextPath}/user/add"><table><tr><th colspan="3">Add or Edit Item</th><form:hidden path="userId" /></tr><tr><td><form:label path="userName">userName:</form:label></td><td><form:input path="userName" size="30" maxlength="30"></form:input></td><td>String <form:errors path="userName" cssStyle="color:red" /></td></tr><tr><td><form:label path="age">age:</form:label></td><td><form:input path="age" size="30" maxlength="30"></form:input></td><td>Integer <form:errors path="age" cssStyle="color:red" /></td></tr><tr><td><form:label path="desc">desc:</form:label></td><td><form:input path="desc" size="30" maxlength="30"></form:input></td><td>String <form:errors path="desc" cssStyle="color:red" /></td></tr><tr><td colspan="3" style="text-align: center;"><input type="submit" class="blue-button" /> <input type="reset" class="blue-button" onclick="formReset()" /></td></tr></table></form:form><h3>Data List</h3><c:if test="${!empty items}"><table><tr><th width="5">序号</th><th width="5">Edit</th><th width="5">Delete</th><th width="100">userId</th><th width="150">userName</th><th width="150">age</th><th width="150">desc</th></tr><c:forEach items="${items}" var="it" varStatus="vs"><tr><td>${vs.count}</td><td><a href="<c:url value='/user/update/${it.userId}' />">Edit</a></td><td><a href="<c:url value='/user/delete/${it.userId}' />">Delete</a></td><td>${it.userId}</td><td>${it.userName}</td><td>${it.age}</td><td>${it.desc}</td></tr></c:forEach></table></c:if><h3>应用端口:<font color="red">${port}</font></h3><h3>Server IP<font color="red">${ip}</font></h3></center>
</body>
</html>

三,准备工作

1. pom.xml 引入组件

		<!-- JSTL 支持,按需引入 --><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId></dependency><!-- JSP 编译支持,必须引入--><dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId><scope>provided</scope></dependency>

2. application.yml 指定jsp配置

application.yml

spring:mvc:view:prefix: /WEB-INF/viewssuffix: .jsp

四,war方式运行

1. 修改pom.xml文件

	<packaging>war</packaging>

2. mvn执行打包

mvn clean package

执行后会在target目录生成war包,拷贝出来后运行

java -jar docker-demo-0.0.1.war

浏览器访问: http://127.0.0.1:8080/user/ 界面如下:
在这里插入图片描述

五,jar方式运行

复制 pom.xml重命名为 pom-jsp-jar.xml

1. 修改pom-jsp-jar.xml文件

	<packaging>jar</packaging>

2. 修改 spring-boot-maven-plugin添加版本号

注意只能使用1.4.2.RELEASE,其他版本不行

			<plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>1.4.2.RELEASE</version></plugin>

3. 添加资源文件配置(Jar运行必须

		<resources><resource><directory>src/main/java</directory><excludes><exclude>**/*.java</exclude></excludes></resource><resource><directory>src/main/resources</directory><includes><include>**/**</include></includes></resource><resource><directory>src/main/webapp</directory><includes><include>**/**</include></includes><targetPath>META-INF/resources</targetPath></resource></resources>

4. mvn执行打包

mvn clean package -f pom-jsp-jar.xml

执行后会在target目录生成 jar包,拷贝出来后运行

java -jar docker-demo-0.0.1.jar

六,war、jar方式运行配置文件区别

在这里插入图片描述
在这里插入图片描述


有任何问题和建议,都可以向我提问讨论,大家一起进步,谢谢!

-over-

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/179230.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

R语言绘图-5-条形图(修改坐标轴以及图例等)

0. 说明&#xff1a; 1. 绘制条形图&#xff1b; 2. 添加文本并调整位置&#xff1b; 3. 调整x轴刻度的字体、角度及颜色&#xff1b; 4. 在导出pdf时&#xff0c;如果没有字体&#xff0c;该怎么解决问题&#xff1b; 1. 结果&#xff1a; 2. 代码&#xff1a; library(ggp…

UE5数字孪生制作(一) - QGIS 学习笔记

1.下载 QGIS是免费的GIS工具&#xff0c;下载地址&#xff1a; https://www.qgis.org/en/site/ 2.安装 - 转中文 按照步骤安装&#xff0c;完成后&#xff0c;在菜单 设置settings里&#xff0c;选择options&#xff0c;修改语言 确定后&#xff0c;需要重启下软件 3.学习视…

MATLAB和西门子SMART PLC OPC通信

西门子S7-200SMART PLC OPC软件的下载和使用,请查看下面文章 Smart 200PLC PC Access SMART OPC通信_基于pc access smart的opc通信_RXXW_Dor的博客-CSDN博客文章浏览阅读2.7k次,点赞2次,收藏5次。OPC是一种利用微软COM/DCOM技术达成自动控制的协议,采用典型的C/S模式,针…

测试用例设计——WEB通用测试用例

现在项目做完了&#xff0c;我觉得还是有必要总结一下&#xff0c;学习到的内容。毕竟有总结才能有提高嘛&#xff01;总结一下通用的东西&#xff0c;不管什么项目基本都可能会遇到&#xff0c;有写地方也有重复的或者有的是按照个人的习惯来总结的不一定都对&#xff0c;有不…

Visual Components Robotics OLP解决方案 北京衡祖

Visual Components 引入了“Visual Components Robotics OLP”的重大升级&#xff0c;合并了制造模拟和机器人离线编程。该解决方案利用 Delfoi Robotics 的技术&#xff0c;提高生产率、减少停机时间并减少浪费。 一、探索下一代离线机器人编程软件 自 1999 年以来&#xff0…

【计算机网络】应用层

应用层协议原理 客户-服务器体系结构&#xff1a; 特点&#xff1a;客户之间不能直接通信&#xff1b;服务器具有周知的&#xff0c;固定的地址&#xff0c;该地址称为IP地址。 配备大量主机的数据中心常被用于创建强大的虚拟服务器&#xff1b;P2P体系结构&#xff1a; 特点&…

详解IPD需求分析工具$APPEALS

够让企业生存下去的是客户&#xff0c;所以&#xff0c;众多企业提出要“以客户为中心”&#xff0c;那如何做到以客户为中心&#xff1f;IPD中给出的答案是需求管理。 需求管理流程&#xff0c;是IPD&#xff08;集成管理开发&#xff09;体系中的四大支撑流程之一&#xff0…

使用Dockerfile生成docker自定义镜像

Dockerfile常用指令 • FROM 构建镜像基于哪个镜像 • MAINTAINER 镜像维护者姓名或邮箱地址 • RUN 构建镜像时运行的指令,执行一条RUN镜像就会叠加一层&#xff0c;因此RUN尽可能一条写完 • ADD 拷贝文件或目录到容器中&#xff0c;如果是URL或压缩包便会自动下载或自动解压…

[2016-2018]phpstudy的exp制作

[2016-2018]phpstudy的exp制作 用python的requests模块进行编写 修改请求数据包进行远程代码执行 import requests import base64 def remove_code_execute():try:url input("请输入要测试的网址:")cmd input("想要执行的命令:")cmd f"system({…

Powercli批量修改分布式交换机端口组

背景 需求&#xff1a; 批量修改虚拟机的分布式端口组 解决方式一&#xff1a; 三条命令解决&#xff1a;先获取目标虚拟机、获取目标端口组、修改虚拟机端口组、检查虚拟机状态。 $vm Get-VM -Name <虚拟机名称> $portGroup Get-VirtualPortGroup -Name <端口…

使用QEMU模拟启动uboot

uboot的相关知识&#xff0c;可以参考&#xff1a;uboot基本概念。 一、环境配置 WSL: ubutu20.04 模拟开发板&#xff1a;vexpress-a9 uboot版本&#xff1a;u-boot-2023.10 二、安装QEMU 2.1、安装sudo apt install qemu2.2、查看支持哪些开发板qemu-system-arm -M help结…

STM32基本定时器中断

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、STM32定时器的结构&#xff1f;1. 51定时器的结构1.1如何实现定时1s的功能&#xff1f; 2. stm32定时器的结构2.1 通用定时器 二、使用步骤1.开启时钟2.初始…

创意无限,体验非凡——Cinema 4D 2024 Mac 版强势来袭

尊贵的设计师们&#xff0c;艺术与技术的完美结合&#xff0c;正是我们对于设计行业的追求。而在这个追求中&#xff0c;Cinema 4D 2024 Mac 版的问世&#xff0c;必将成为您的得力助手&#xff0c;为您的创作之路注入无限的活力与灵感。 Cinema 4D 一直以来都是设计师们最爱用…

SpringCloud 微服务全栈体系(十)

第十章 RabbitMQ 一、初识 MQ 1. 同步和异步通讯 微服务间通讯有同步和异步两种方式&#xff1a; 同步通讯&#xff1a;就像打电话&#xff0c;需要实时响应。 异步通讯&#xff1a;就像发邮件&#xff0c;不需要马上回复。 两种方式各有优劣&#xff0c;打电话可以立即得…

微信小程序 跳转客服页面

前言 小程序 用户反馈 没有页面设计 可以直接跳转小程序指定客服页面 <button class"contactBtn"open-type"contact" contact"handleContact" session-from"sessionFrom">

css——半圆实心

案例 代码 <view class"circleBox"></view>.circleBox {width: 50px;height: 100px;background: red;border-radius: 100px 0 0 100px; }

小程序如何设置自动预约快递

小程序通过设置自动预约功能&#xff0c;可以实现自动将订单信息发送给快递公司&#xff0c;快递公司可以自动上门取件。下面具体介绍如何设置。 在小程序管理员后台->配送设置处&#xff0c;选择首选配送公司。为了能够支持自动预约快递&#xff0c;请选择正常的快递公司&…

大疆Naza飞控与乐迪at9S pro遥控器搭配时的姿态模式控制

Naza飞控是初学者的优秀选择设置简单。但是在连接不同的遥控器的时候&#xff0c;需要进行不同的设置。尤其是多通道的遥控器。下面以乐迪at9S为例进行姿态选择设置。 首先是要成功的连接地面站软件&#xff0c;前提是飞控要连接电池&#xff0c;拆下螺旋桨&#xff0c;另外还要…

Pixhawk2.4.8接口及引脚定义

pixhawk2.4.8实物图 pixhawk侧边信号线插口 遥控器接收机、电调信号线插在这里 pixhawk侧边功能口 Micro-USB接口用来烧录固件、SD卡中有飞行日志等信息 pixhawk主面板接口 主面板接口功能概览 主面板接口定义 参考博客&#xff1a; https://zhuanlan.zhihu.com/p/61106155…

大模型问答助手前端实现打字机效果 | 京东云技术团队

1. 背景 随着现代技术的快速发展&#xff0c;即时交互变得越来越重要。用户不仅希望获取信息&#xff0c;而且希望以更直观和实时的方式体验它。这在聊天应用程序和其他实时通信工具中尤为明显&#xff0c;用户习惯看到对方正在输入的提示。 ChatGPT&#xff0c;作为 OpenAI …