Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deploy a project remotely through ManagerServlet in tomcat

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to deploy a project remotely through ManagerServlet in tomcat. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Introduction

When I was an intern in the post office, leader asked me to read the source code of tomcat and try to implement the remote deployment project myself, so I had this practice.

There is a Manager application in Tomact, which is used to manage deployed web applications, in which ManagerServlet is his main servlet, through which we can obtain some of the metrics of tomcat and remotely manage web applications, but this function is protected by security constraints in the deployment of web applications.

When you request ManagerServlet, it checks the value returned by getPathInfo () and the relevant query parameters to determine the requested operation. It supports the following operations and parameters (starting with the servlet path):

Request path description / deploy?config= {config-url} deploy and start a new web application based on the specified path (see source code) / deploy?config= {config-url} & war= {war-url} / deploy and start a new web application based on the specified pat (see source code) / deploy?path=/xxx&war= {war-url} deploy and start a new web application based on the specified path (see Source code) / list lists the context paths for all web applications. The format is path:status:sessions (active sessions) / reload?path=/xxx to reload the global JNDI resources available to the web application / resources?type=xxxx enumeration based on the specified path You can restrict the specified java class name / serverinfo to display system information and JVM information / sessions this method has expired / expire?path=/xxx lists the session idle time information of the web application under the path path / expire?path=/xxx&idle=mmExpire sessions for the context path / xxx which were idle for at least mm minutes./sslConnectorCiphers displays diagnostic information of the current connector configured SSL/TLS password / start?path=/xx starts the web application / stop?path= according to the specified path / xxx closes the web application according to the specified path / threaddumpWrite a JVM threaddump / undeploy?path=/xxx closes and deletes the Web application of the specified path Then delete the underlying WAR file or document base directory.

We can remotely deploy our project to the server through the operation provided by getPathInfo () in ManagerServlet. My practice code will be posted below, and you only need to introduce the httpclient package and the commons package before implementing it.

Encapsulate a unified remote request management class

The encapsulation class is used to facilitate client request ManagerServlet:

Import java.io.File;import java.net.URL;import java.net.URLEncoder;import org.apache.commons.io.IOUtils;import org.apache.commons.lang.StringUtils;import org.apache.http.Header;import org.apache.http.HttpHost;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.auth.AuthScope;import org.apache.http.auth.Credentials;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.AuthCache Import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpRequestBase;import org.apache.http.client.protocol.ClientContext;import org.apache.http.impl.auth.BasicScheme;import org.apache.http.impl.client.BasicAuthCache;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.impl.conn.PoolingClientConnectionManager;import org.apache.http.protocol.BasicHttpContext;public class TomcatManager {private static final String MANAGER_CHARSET = "UTF-8"; private String username; private URL url Private String password; private String charset; private boolean verbose; private DefaultHttpClient httpClient; private BasicHttpContext localContext; / * * constructor * / public TomcatManager (URL url, String username) {this (url, username, "");} public TomcatManager (URL url, String username, String password) {this (url, username, password, "ISO-8859-1");} public TomcatManager (URL url, String username, String password, String charset) {this (url, username, password, charset, true) } public TomcatManager (URL url, String username, String password, String charset, boolean verbose) {this.url = url; this.username = username; this.password = password; this.charset = charset; this.verbose = verbose; / / create the configuration related to the network request PoolingClientConnectionManager poolingClientConnectionManager = new PoolingClientConnectionManager (); poolingClientConnectionManager.setMaxTotal (5); this.httpClient = new DefaultHttpClient (poolingClientConnectionManager) If (StringUtils.isNotEmpty (username)) {Credentials creds = new UsernamePasswordCredentials (username, password); String host = url.getHost (); int port = url.getPort () >-1? Url.getPort (): AuthScope.ANY_PORT; httpClient.getCredentialsProvider (). SetCredentials (new AuthScope (host, port), creds); AuthCache authCache = new BasicAuthCache (); BasicScheme basicAuth = new BasicScheme (); HttpHost targetHost = new HttpHost (url.getHost (), url.getPort (), url.getProtocol ()); authCache.put (targetHost, basicAuth); localContext = new BasicHttpContext (); localContext.setAttribute (ClientContext.AUTH_CACHE, authCache) }} / * * deploy and launch a new application according to the specified path * / public TomcatManagerResponse deploy (String path, File war, boolean update) throws Exception {StringBuilder buffer = new StringBuilder ("/ deploy"); buffer.append ("? path=") .append (URLEncoder.encode (path, charset)); if (war! = null) {buffer.append ("& war=") .append (URLEncoder.encode (war.toString (), charset)) } if (update) {buffer.append ("& update=true");} return invoke (buffer.toString ());} / * * gets the context path of all deployed web applications. The format is path:status:sessions (active sessions) * / public TomcatManagerResponse list () throws Exception {StringBuilder buffer = new StringBuilder ("/ list"); return invoke (buffer.toString ());} / * * get system information and JVM information * / public TomcatManagerResponse serverinfo () throws Exception {StringBuilder buffer = new StringBuilder ("/ serverinfo"); return invoke (buffer.toString ()) } / * * the actual method for sending a request * / private TomcatManagerResponse invoke (String path) throws Exception {HttpRequestBase httpRequestBase = new HttpGet (url + path); HttpResponse response = httpClient.execute (httpRequestBase, localContext); int statusCode = response.getStatusLine (). GetStatusCode (); switch (statusCode) {case HttpStatus.SC_OK: / / 200 case HttpStatus.SC_CREATED: / / 201 case HttpStatus.SC_ACCEPTED: / / 202break Case HttpStatus.SC_MOVED_PERMANENTLY: / / 301case HttpStatus.SC_MOVED_TEMPORARILY: / / 302case HttpStatus.SC_SEE_OTHER: / / 303String redirectUrl = getRedirectUrl (response); this.url = new URL (redirectUrl); return invoke (path) } return new TomcatManagerResponse (). SetStatusCode (response.getStatusLine (). GetStatusCode ()) .setReasonPhrase (response.getStatusLine (). GetReasonPhrase ()) .setHttpResponseBody (IOUtils.toString (response.getEntity (). GetContent ());} / * * extract redirect URL * / protected String getRedirectUrl (HttpResponse response) {Header locationHeader = response.getFirstHeader ("Location"); String locationField = locationHeader.getValue (); / / is it a relative Location or a full? Return locationField.startsWith ("http")? LocationField: url.toString () +'/'+ locationField;}}

Encapsulate the response result set

@ Datapublic class TomcatManagerResponse {private int statusCode; private String reasonPhrase; private String httpResponseBody;}

Test remote deployment

Please release the following user rights in the configuration file before testing:

Here is the code to test the successful remote deployment of the war package:

Import static org.testng.AssertJUnit.assertEquals;import java.io.File;import java.net.URL;import org.testng.annotations.Test;public class TestTomcatManager {@ Test public void testDeploy () throws Exception {TomcatManager tm = new TomcatManager (new URL ("http://localhost:8080/manager/text")," sqdyy "," 123456 "); File war = new File (" E:\\ tomcat\\ simple-war-project-1.0-SNAPSHOT.war ") TomcatManagerResponse response = tm.deploy ("/ simple-war-project-1.0-SNAPSHOT", war, true); System.out.println (response.getHttpResponseBody ()); assertEquals (200, response.getStatusCode ()) / / output: / / OK-Deployed application at context path / simple-war-project-1.0-SNAPSHOT} @ Test public void testList () throws Exception {TomcatManager tm = new TomcatManager (new URL ("http://localhost:8080/manager/text")," sqdyy "," 123456 "); TomcatManagerResponse response = tm.list (); System.out.println (response.getHttpResponseBody ()); assertEquals (200, response.getStatusCode ()) / / output: / / OK-Listed applications for virtual host localhost /: running:0:ROOT / / simple-war-project-1.0-SNAPSHOT:running:0:simple-war-project-1.0-SNAPSHOT / examples:running:0:examples / host-manager:running:0:host-manager / / manager:running:0:manager / docs:running:0: Docs} @ Test public void testServerinfo () throws Exception {TomcatManager tm = new TomcatManager (new URL ("http://localhost:8080/manager/text"),) "sqdyy", "123456") TomcatManagerResponse response = tm.serverinfo (); System.out.println (response.getHttpResponseBody ()); assertEquals (200, response.getStatusCode ()) / / output: / / OK-Server info / / Tomcat Version: Apache Tomcat/7.0.82 / / OS Name: Windows 10 / / OS Version: 10.0 / / OS Architecture: amd64 / / JVM Version: 1.8.0_144-b01 / / JVM Vendor: Oracle Corporation} about how to remotely deploy a project through ManagerServlet in tomcat Hope that the above content can be helpful to you, so that you can learn more knowledge, if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report