搜索词>>war 耗时0.0050
  • spring boot maven项目打war包再部署到外部tomcat中

    spring boot项目打war包再部署到外部tomcat中<h2>一.情况说明</h2> 大多数情况下我们开发的项目需要部署到外部的tomcat中,而并非spring boot默认的jar方式部署,这个时候就需要修改和新增一些配置 <h2>二.spring boot项目war打包具体操作</h2> 2.1修改pom.xml文件 <ul> <li>将<packaging>jar</packaging>修改为<packaging>war</packaging></li> <li>在<dependencies>节点中添加</li> </ul> <pre> <code class="language-xml"><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency></code></pre> <br /> 2.2创建tomcat需要的一个servlet启动类<br /> <br /> 我一般喜欢创建在spring boot启动类的同级目录<br /> <strong>ServletInitializer.java</strong> <pre> <code class="language-java">import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(CyinterfaceApplication.class); } } </code></pre> <strong><span style="color:#ff0000">Tips</span>:CyinterfaceApplication即spring boot默认的启动类</strong> <h2>三.使用maven打包项目</h2> 由于我直接使用的eclipse集成的maven插件,使用方法如下:<br /> <br /> <img alt="打包" class="img-thumbnail" src="/assist/images/blog/df4fa9c18113451082e8f809bac9fba9.png" /><br /> <br /> maven打包后在target目录查看:<br /> <img alt="查看war包" class="img-thumbnail" src="/assist/images/blog/f2e0549b4f534b4ba362d49d6357a231.png" />​​​​​​​
  • spring boot 导入本地jar包

    spring boot 导入本地jar包spring boot maven 打war包时候导入本地jar包spring boot 导入本地jar包spring boot maven 打war包时候导入本地jar包<br /> <br /> <br /> 首先一个纯净的spring boot war包项目的pom.xml如下: <pre> <code class="language-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.leftso</groupId> <artifactId>lee-monitor</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>lee-monitor</name> <description>cmd</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <!--启用本地jar包---> <configuration> <includeSystemScope>true</includeSystemScope> </configuration> </plugin> </plugins> </build> </project> </code></pre> <br /> <br /> 项目中创建一个lib目录,将本地jar包放入lib目录中:<br /> <img alt="lib目录" class="img-thumbnail" src="/assist/images/blog/f53502417f7e4d0480bea7bb1e03ab62.png" /><br />   <pre>  </pre> <pre> <code class="language-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.leftso</groupId> <artifactId>lee-monitor</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>lee-monitor</name> <description>cmd</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--本地包--> <dependency> <groupId>leftso</groupId> <artifactId>common</artifactId> <version>1.0</version> <scope>system</scope> <systemPath>${project.basedir}/lib/Common.jar</systemPath> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> </code></pre> 上面的操作已经可以将本地的jar包引入到spring boot项目中了<br /> <br /> <br /> 打包的时候讲本地jar包打入war中还需要添加一个war的打包插件,配置如下: <pre> <code class="language-xml"> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <webResources> <resource> <directory>${project.basedir}/lib</directory> <targetPath>WEB-INF/lib/</targetPath> <includes> <include>**/*.jar</include> </includes> </resource> </webResources> </configuration> </plugin></code></pre> <br /> 搞定<br />  
  • SpringMVC Maven打包war/jar没有Mapper.xml文件问题

    SpringMVC mybaties Maven打包war/jar没有Mapper.xml文件问题原因以及解决方法<img alt="maven项目结构" class="img-thumbnail" src="/assist/images/blog/17182b8acf4f4b2e92f83fac01361e6a.png" /><br /> <br /> <span style="color:#1abc9c"><strong>xml是属于我们的资源文件,所以在src/main/java中是不被打包的,只有存在src/main/resources中才会进行打包。</strong></span><br />   <h4><strong>解决方法:</strong></h4> 1.将mapper.xml文件放在resources目录下<br /> 2.配置pom.xml打包信息 <pre> <code class="language-xml"><build> <finalName>xzbms</finalName> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> <include>**/*.tld</include> </includes> <!-- 这里是false,用true会报 数据库连接 错误 --> <filtering>false</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> <include>**/*.tld</include> </includes> <filtering>false</filtering> </resource> </resources> </build></code></pre> <br /> <strong>意思就是不管在src/main/java或者是src/main/resources中都被打包。</strong>
  • idea2018配置Tomcat8热部署完整记录

    idea2018配置Tomcat8热部署完整记录    由于初步学习使用idea。所以工具用的还不是很熟。但是热部署这个东西,对于砸门开发人员来说还是非常必要的。经百度了了一下。发现真是写的参差不齐。就连百度经验里面的教程都是不全面的。导致小恼火了一把。特写一篇博客记录完整的配置方式供大家参考。<br />   <p>步骤一:添加Tomcat到idea中<br /> <img alt="添加Tomcat" class="img-thumbnail" src="/assist/images/blog/bbce7b32569f4b0580e5eef5ca5e8ef4.png" /><br /> <br /> <img alt="添加Tomcat" class="img-thumbnail" src="/assist/images/blog/48c1af1146d8474dbf456bb7d9aec17c.png" /><br /> <br /> 上图的+ -号就是添加和删除Tomcat。<br /> <br /> 步骤二:项目中Tomcat的配置<br /> <br /> 点击idea的右上角编辑配置<br /> <img alt="项目中的配置" class="img-thumbnail" src="/assist/images/blog/8c6349b680d140d78477cff1107cb80d.png" /><br /> <br /> 选择Tomcat服务器(初次则这里点击上面的+号添加Tomcat服务器),然后选择Deployment.下方有+/-号添加项目。</p> <blockquote> <p>注意添加的项目会有两个选择一个是war结尾的一个是war exploded的。选择exploded的这个非常重要。选择不对则后面无法配置</p> </blockquote> <p><br /> <img alt="添加项目包到Tomcat中" class="img-thumbnail" src="/assist/images/blog/67233e76fc504d5c9f3957d4b5a7a104.png" /><br /> <br /> <br /> 配置资源热部署<br /> <br /> 在On Update action和on frame deactivation两个配置中选择update class and resources完成配置。如果这里没看到update class and resources配置项。则检查上一步的项目部署包是否选择正确<br /> <img alt="配置资源热部署" class="img-thumbnail" src="/assist/images/blog/b650aa09dbbe4d7ca8bfd15a11eeb0f6.png" /><br /> <br /> <br /> 好啦。完整的idea2018配置Tomcat8 热部署完成。<br />  </p>
  • spring boot使用Jenkins部署Spring Boot项目

    spring boot使用Jenkins部署Spring Boot项目<p>jenkins是devops神器,本篇文章介绍如何安装和使用jenkins部署Spring Boot项目</p> <p>jenkins搭建 部署分为三个步骤;</p> <ul> <li> <p>第一步,jenkins安装</p> </li> <li> <p>第二步,插件安装和配置</p> </li> <li> <p>第三步,Push SSH</p> </li> <li> <p>第四步,部署项目</p> </li> </ul> <h2>第一步 ,jenkins安装</h2> <p>准备环境:</p> <p>JDK:1.8<br /> Jenkins:2.83 Centos:7.3<br /> maven 3.5‘</p> <blockquote> <p>jdk默认已经安装完成</p> </blockquote> <h3>配置maven</h3> <p>版本要求maven3.5.0</p> <p>软件下载</p> <pre> <code class="language-html">wget http://mirror.bit.edu.cn/apache/maven/maven-3/3.5.0/binaries/apache-maven-3.5.0-bin.tar.gz</code></pre> <p>安装</p> <pre> <code class="language-bash">## 解压 tar vxf apache-maven-3.5.0-bin.tar.gz ## 移动 mv apache-maven-3.5.0 /usr/local/maven3</code></pre> <p>修改环境变量, 在/etc/profile中添加以下几行</p> <pre> <code class="language-html">MAVEN_HOME=/usr/local/maven3 export MAVEN_HOME export PATH=${PATH}:${MAVEN_HOME}/bin</code></pre> <p>记得执行 <code>source/etc/profile</code>使环境变量生效。</p> <p>验证 最后运行 <code>mvn-v</code>验证maven是否安装成功</p> <h3>配置防护墙</h3> <p>关闭防护墙</p> <pre> <code class="language-html">#centos7 systemctl stop firewalld.service ============================== #以下为:centOS 6.5关闭防火墙步骤 #关闭命令:   service iptables stop #永久关闭防火墙: chkconfig iptables off</code></pre> <p>两个命令同时运行,运行完成后查看防火墙关闭状态</p> <pre> <code class="language-html">service iptables status</code></pre> <h3>jenkins 安装</h3> <p>下载<br />  </p> <pre> <code class="language-html">cd /opt wget http://mirrors.jenkins.io/war/2.83/jenkins.war</code></pre> <p>启动服务</p> <pre> <code class="language-html">​​​​​​​java -jar jenkins.war &</code></pre> <p>Jenkins 就启动成功了!它的war包自带Jetty服务器</p> <p>第一次启动Jenkins时,出于安全考虑,Jenkins会自动生成一个随机的口令。<strong>注意控制台输出的口令,复制下来</strong>,然后在浏览器输入密码:</p> <pre> <code class="language-html">INFO: ************************************************************* ************************************************************* ************************************************************* Jenkins initial setup is required. An admin user has been created and a password generated. Please use the following password to proceed to installation: 0cca37389e6540c08ce6e4c96f46da0f This may also be found at: /root/.jenkins/secrets/initialAdminPassword ************************************************************* ************************************************************* *************************************************************</code></pre> <p>访问 浏览器访问: <code>http://localhost:8080/<br /> <img alt="安装" class="img-thumbnail" src="/assist/images/blog/dc38e97e558148d1953ee91e9630bf50.jpg" /></code><br />  </p> <p>输入:0cca37389e6540c08ce6e4c96f46da0f</p> <p>进入用户自定义插件界面,建议选择安装官方推荐插件,因为安装后自己也得安装:<br /> <img alt="install 1" class="img-thumbnail" src="/assist/images/blog/badf16beeea84c8a8b119fc7cf5e0d7f.jpg" /><br /> 接下来是进入插件安装进度界面:<br /> <img alt="install 2" class="img-thumbnail" src="/assist/images/blog/c5901b1554cc476a87d2806b048d3c8f.jpg" /><br /> 插件一次可能不会完全安装成功,可以点击Retry再次安装,直到全部安装成功。<br /> <img alt="install 3" class="img-thumbnail" src="/assist/images/blog/f88e983c46a746fb9ab1f7adc3c1f35c.jpg" /><br /> 等待一段时间之后,插件安装完成,配置用户名密码:<br /> <img alt="install 5" class="img-thumbnail" src="/assist/images/blog/d99345eac5e44be7bf9573da39832f99.jpg" /><br />  </p> <p>输入:admin/admin</p> <p>系统管理-》全局工具配置 jdk路径,<br /> <img alt="install 6" class="img-thumbnail" src="/assist/images/blog/049f7d98e1e64175919eb75eefd662f0.jpg" /></p> <h2>第二步,插件安装和配置</h2> <p>有很多插件都是选择的默认的安装的,所以现在需要我们安装的插件不多,Git plugin和Maven Integration plugin,publish over SSH。</p> <p>插件安装:系统管理 > 插件管理 > 可选插件,勾选需要安装的插件,点击直接安装或者下载重启后安装<br /> <img alt="install 7" class="img-thumbnail" src="/assist/images/blog/c4944230d3fb4b668c5f606441d2575f.jpg" /></p> <h3>配置全局变量</h3> <p>系统管理 > 全局工具配置</p> <p><strong>JDK</strong></p> <p>配置本地JDK的路径,去掉勾选自动安装<br /> <img alt="install 8" class="img-thumbnail" src="/assist/images/blog/590fb0fbbb7047df96ea276960438285.png" /><br /> <br />  </p> <p><strong>Maven</strong></p> <p>配置本地maven的路径,去掉勾选自动安装<br /> <img alt="install 9" class="img-thumbnail" src="/assist/images/blog/deb59e78535c45fe8bb914b592491e6a.png" /></p> <p>其它内容可以根据自己的情况选择安装。</p> <h3>配置 SSH免登陆</h3> <p>ssh的配置可使用密钥,也可以使用密码,这里我们使用密钥来配置,在配置之前先配置好jenkins服务器和应用服务器的密钥认证 <strong>jenkins服务器</strong>上生成密钥对,使用 <code>ssh-keygen-t rsa</code>命令</p> <p>输入下面命令 一直回车,一个矩形图形出现就说明成功,在~/.ssh/下会有私钥idrsa和公钥idrsa.pub</p> <pre> <code class="language-html">ssh-keygen -t rsa</code></pre> <p>将<strong>jenkins服务器</strong>的公钥 <code>id_rsa.pub</code>中的内容复制到<strong>应用服务器</strong> 的~/.ssh/下的 <code>authorized_keys</code>文件</p> <pre> <code class="language-html">ssh-copy-id -i id_rsa.pub 192.168.0.xx chmod 644 authorized_keys</code></pre> <p>在<strong>应用服务器</strong>上重启ssh服务, <code>service sshd restart</code>现在jenkins服务器可免密码直接登陆应用服务器</p> <p>之后在用ssh B尝试能否免密登录B服务器,如果还是提示需要输入密码,则有以下原因</p> <ul> <li>a. 非root账户可能不支持ssh公钥认证(看服务器是否有限制)</li> <li>b. 传过来的公钥文件权限不够,可以给这个文件授权下 chmod 644 authorized_keys</li> <li>c. 使用root账户执行ssh-copy-id -i ~/.ssh/idrsa.pub 这个指令的时候如果需要输入密码则要配置sshdconfig<br />  </li> </ul> <pre> <code class="language-html">vi /etc/ssh/sshd_config #内容 PermitRootLogin no</code></pre> <p>修改完后要重启sshd服务</p> <pre> <code class="language-html">service sshd restart</code></pre> <p>最后,如果可以SSH IP 免密登录成功说明SSH公钥认证成功。</p> <h2>第三步,Push SSH</h2> <p>系统管理 > 系统设置</p> <p>选择 Publish over SSH<br /> <img alt="install 10" class="img-thumbnail" src="/assist/images/blog/d7cb7603ce754991b4545d037723c95b.jpg" /><br />  </p> <p>Passphrase 不用设置 Path to key 写上生成的ssh路径: <code>/root/.ssh/id_rsa</code></p> <p>下面的SSH Servers是重点</p> <p>Name 代表这个服务的名字,待会要根据它来选择 Hostname 配置应用服务器的地址 ,Username 配置linux登陆用户名,Remote Directory 不填。</p> <blockquote> <p>点击下方增加可以添加多个应用服务器的地址</p> </blockquote> <h2>第四步,部署项目</h2> <p>首页点击<strong>新建</strong>:输入项目名称<br /> <img alt="install 11" class="img-thumbnail" src="/assist/images/blog/6839c4c2b4fc459997b8da3358ba5ab5.jpg" /><br />  </p> <p>下方选择构建一个maven项目,点击确定。</p> <p>勾选<strong>丢弃旧的构建</strong>,选择是否备份被替换的旧包。我这里选择备份最近的10个<br /> <img alt="install2" class="img-thumbnail" src="/assist/images/blog/7b39a1d66e2141bb85be6ab5b06af713.jpg" />源码管理,选择svn,配置SVN相关信息,点击add可以输入svn的账户和密码<br /> <img alt="install 13" class="img-thumbnail" src="/assist/images/blog/b56df59efbe846858d6246d1d3aadcef.jpg" /></p> <p>svn地址:http://192.168.0.xx/svn/xxx@HEAD, <code>@HEAD</code>意思取最新版本</p> <p>构建环境中勾选“Add timestamps to the Console Output”,代码构建的过程中会将日志打印出来<br /> <img alt="install 14" class="img-thumbnail" src="/assist/images/blog/161fd6e0dab344febfd77e51840044aa.png" /><br />  </p> <p>在Build中输入打包前的mvn命令,如:</p> <pre> <code class="language-html">clean install -Dmaven.test.skip=true -Ptest</code></pre> <p>意思是:排除测试的包内容,使用后缀为test的配置文件。<br /> <img alt="install 15" class="img-thumbnail" src="/assist/images/blog/3fb887bd57584b6ea9741242c227beeb.png" /><br /> Post Steps 选择 Run only if build succeeds<br /> <img alt="install 16" class="img-thumbnail" src="/assist/images/blog/1fb7cbbb0a2b47e4a51984fad847011c.png" /><br /> 点击<strong>Add post-build step</strong>,选择 Send files or execute commands over SSH<br /> <img alt="install 17" class="img-thumbnail" src="/assist/images/blog/7d0297473cb74033951da9881d7f7618.jpg" />Name选择上面配置的Push SSH<br /> <img alt="install 18" class="img-thumbnail" src="/assist/images/blog/bba4530a46d64d30bf4e47cc48850625.jpg" /><br />  </p> <p>Source files配置:target/xxx-0.0.1-SNAPSHOT.jar 项目jar包名 ;Remove prefix:target/ ;Remote directory:Jenkins-in/ 代码应用服务器的目录地址;Exec command:Jenkins-in/xxx.sh 应用服务器对应的脚本。</p> <p>需要在应用服务器创建文件夹:Jenkins-in,在文件夹中复制一下脚本内容:xxx.sh<br />  </p> <pre> <code class="language-html">DATE=$(date +%Y%m%d) export JAVA_HOME PATH CLASSPATH JAVA_HOME=/usr/java/jdk1.8.0_131 PATH=$JAVA_HOME/bin:$JAVA_HOME/jre/bin:$PATH CLASSPATH=.:$JAVA_HOME/lib:$JAVA_HOME/jre/lib:$CLASSPATH DIR=/root/xxx JARFILE=xxx-0.0.1-SNAPSHOT.jar if [ ! -d $DIR/backup ];then   mkdir -p $DIR/backup fi cd $DIR ps -ef | grep $JARFILE | grep -v grep | awk '{print $2}' | xargs kill -9 mv $JARFILE backup/$JARFILE$DATE mv -f /root/Jenkins-in/$JARFILE . java -jar $JARFILE > out.log & if [ $? = 0 ];then        sleep 30        tail -n 50 out.log fi cd backup/ ls -lt|awk 'NR>5{print $NF}'|xargs rm -rf</code></pre>
  • Spring Boot中使用jsp视图模板-Java编程之

    Java编程之Spring Boot中使用jsp视图模板<h2>本文简介</h2> 本文将学习怎么创建spring boot项目并在spring boot项目中使用JSP模板作为视图层。这里会使用嵌入的tomcat server去运行这个程序。 <h2>一、项目结构图</h2> <img alt="项目结构图" class="img-thumbnail" src="/assist/images/blog/76c1ff4b065246e3aac10181ea66430e.png" /> <h2>二、maven依赖文件pom.xml</h2> 这个应用将会使用以下依赖: <pre> <code class="language-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.howtodoinjava</groupId> <artifactId>spring-boot-demo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>spring-boot-demo Maven Webapp</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!-- Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Tomcat Embed --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <!-- JSTL --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!-- To compile JSP files --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> </dependencies> </project></code></pre> <h2>三、spring boot应用的初始类</h2>   首先创建一个可部署的war文件的第一步是提供一个SpringBootServletInitializer子类和覆盖其配置()方法。这将使用Spring Framework的Servlet 3.0支持,并允许您在Servlet容器启动时配置您的应用程序。 <pre> <code class="language-java">import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication public class SpringBootWebApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(SpringBootWebApplication.class); } public static void main(String[] args) throws Exception { SpringApplication.run(SpringBootWebApplication.class, args); } }</code></pre> <h2><br /> 四、Spring Controller</h2> 控制器类可以将方法映射到应用程序中的特定url。在给定的应用程序中,它有两个视图,“/”和“/next” <pre> <code class="language-java">import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class IndexController { @RequestMapping("/") public String home(Map<String, Object> model) { model.put("message", "HowToDoInJava Reader !!"); return "index"; } @RequestMapping("/next") public String next(Map<String, Object> model) { model.put("message", "You are in new page !!"); return "next"; } }</code></pre> <h2>五、配置JSP视图解析器</h2> 解析jsp文件有两种方法可行<br /> 5.1在application.properties中添加以下内容:<br />   <pre> <code>spring.mvc.view.prefix=/WEB-INF/view/ spring.mvc.view.suffix=.jsp //For detailed logging during development logging.level.org.springframework=TRACE logging.level.com=TRACE</code></pre> <br /> 5.2配置InternalResourceViewResolver <pre> <code class="language-java">import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan public class MvcConfiguration extends WebMvcConfigurerAdapter { @Override public void configureViewResolvers(ViewResolverRegistry registry) { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/view/"); resolver.setSuffix(".jsp"); resolver.setViewClass(JstlView.class); registry.viewResolver(resolver); } }</code></pre> <h2><br /> 六、JSP文件编写</h2> <strong>index.jsp</strong> <pre> <code class="language-html"><!DOCTYPE html> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <html lang="en"> <body> <div> <div> <h1>Spring Boot JSP Example</h1> <h2>Hello ${message}</h2> Click on this <strong><a href="next">link</a></strong> to visit another page. </div> </div> </body> </html></code></pre> <strong>next.jsp</strong> <pre> <code class="language-html"><!DOCTYPE html> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <html lang="en"> <body> <div> <div> <h1>Another page</h1> <h2>Hello ${message}</h2> Click on this <strong><a href="/">link</a></strong> to visit previous page. </div> </div> </body> </html></code></pre> <h2>七、运行程序</h2> 在将整个代码编写并放置在文件夹中之后,通过在<code>SpringBootWebApplication</code> 类中执行main()方法来运行应用程序<br /> <br /> 打开浏览器:http://localhost:8080/<br /> <img alt="index" class="img-thumbnail" src="/assist/images/blog/d961b6f45c7142039956ab5b0c411468.png" /><br /> 点击next<br /> <img alt="next" class="img-thumbnail" src="/assist/images/blog/9d25d5a067434b51bb11015b822cce28.png" /> <h2>八、例子下载</h2> <a href="http://howtodoinjava.com/wp-content/downloads/spring-boot-demo-jsp-example.zip" rel="external nofollow" target="_blank">点击下载</a>
  • Spring MVC 5.0

    Spring框架5.0,spring mvc 5.0入门教程。DispatcherServlet的详细讲解配置以及spring mvc5.0的helloword程序<h2>引言</h2>   在本教程中,我们将学习Spring DispatcherServlet类,其职责以及如何使用示例进行配置。spring mvc 5.0基于Java配置 <h2>一.DispatcherServlet是什么</h2> <br />     <code>DispatcherServlet</code> 充当基于Spring的Web应用程序的前端控制器。 它提供了一个请求处理机制,其中实际工作由可配置的委托组件执行。 它从javax.servlet.http.HttpServlet继承,通常在web.xml文件中配置。<br /> <br />     Web应用程序可以定义任意数量的<code>DispatcherServlet</code> 实例。 每个servlet将在其自己的名称空间中运行,使用映射,处理程序等加载它自己的应用程序上下文。只有由ContextLoaderListener加载的根应用程序上下文(如果有)将被共享。 在大多数情况下,应用程序只有一个具有上下文根URL(/)的<code>DispatcherServlet</code> ,也就是说,到达该域的所有请求都将由它处理。<br /> <br />     <code>DispatcherServlet</code> 使用Spring配置类来发现它需要的委托组件,用于请求映射,视图解析,异常处理等。 <h2>二.DispatcherServlet它如何使用WebApplicationContext</h2>     在基于Spring的应用程序中,我们的应用程序对象位于一个对象容器中。 该容器在对象之间创建对象和关联,并管理其完整的生命周期。 这些容器对象被称为Spring管理的bean(或者简单的bean),在Spring世界中容器被称为应用程序上下文(通过类ApplicationContext)。<br /> <br />     WebApplicationContext是一个普通的ApplicationContext的扩展。 它是Web感知的ApplicationContext,即它具有Servlet上下文信息。 当DispatcherServlet被加载时,它查找WebApplicationContext的bean配置文件并初始化它。<br /> <br />     通过访问Servlet上下文,任何实现了ServletConextAware接口的spring bean都可以访问ServletContext实例,并且可以做很多事情。 例如,它可以获取上下文初始化参数,获取上下文根信息并获取Web应用程序文件夹中的资源位置。 <h2>三.基于XML配置的DispatcherServlet(作为参考理解主讲基于Java配置)</h2> 我们来看看典型的DispatcherServlet声明和初始化是怎样的。 <pre> <code class="language-xml"><web-app> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/dispatcher-servlet-context.xml</param-value> </context-param> <servlet> <servlet-name>dispatcher-servlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value></param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher-servlet</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app></code></pre> 在上面的代码中,dispatcher-servlet-context.xml文件将包含所有可用于DispatcherServlet的bean定义和关联。 这些bean定义将覆盖在全局范围内使用相同名称定义的任何bean的定义。 例如: <pre> <code class="language-xml"><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-2.5.xsd"> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name="prefix"> <value>/WEB-INF/views/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans></code></pre> <h2>四.基于JAVA代码配置的DispatcherServlet </h2> 从Servlet 3.0开始,除了web.xml文件中的声明式配置,DispatcherServlet可以通过实现或扩展Spring提供的这三个支持类来编程配置  <ul> <li>WebAppInitializer接口</li> <li>AbstractDispatcherServletInitializer抽象类</li> <li>AbstractAnnotationConfigDispatcherServletInitializer抽象类</li> </ul> 在下面的类中,WebApplicationInitializer确保ApplicationSerializer类被SpringServletContainerInitializer(它本身自动引导)检测到并用来初始化任何Servlet 3容器。<br /> <br /> 引入spring mvc 5.0需要的相关依赖,pom.xml: <pre> <code class="language-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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.leftso.project.demo</groupId> <artifactId>demo-spring5-springmvc5</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <failOnMissingWebXml>false</failOnMissingWebXml> <spring.version>5.0.1.RELEASE</spring.version> <jstl.version>1.2.1</jstl.version> <tld.version>1.1.2</tld.version> <servlets.version>3.1.0</servlets.version> <jsp.version>2.3.1</jsp.version> </properties> <dependencies> <!-- Spring MVC Dependency --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- JSTL Dependency --> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>javax.servlet.jsp.jstl-api</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${tld.version}</version> </dependency> <!-- Servlet Dependency --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlets.version}</version> <scope>provided</scope> </dependency> <!-- JSP Dependency --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>${jsp.version}</version> <scope>provided</scope> </dependency> </dependencies> <build> <sourceDirectory>src/main/java</sourceDirectory> <resources> <resource> <directory>src/main/resources</directory> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/</path> </configuration> </plugin> </plugins> </build> </project></code></pre> <br /> <br /> 通过Java的方式可以将上面的web.xml写一个配置类: <pre> <code class="language-java">public class ApplicationInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { XmlWebApplicationContext appContext = new XmlWebApplicationContext(); appContext.setConfigLocation("/WEB-INF/dispatcher-servlet-context.xml"); ServletRegistration.Dynamic registration = servletContext .addServlet("rootDispatcher", new DispatcherServlet(appContext)); registration.setLoadOnStartup(1); registration.addMapping("/"); } }</code></pre> 基于Java 配置的完整配置<br /> <strong>例子一:</strong> <pre> <code class="language-java">package com.leftso.project.demo.config; import javax.servlet.ServletContext; import javax.servlet.ServletException; 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 ApplicationInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { // 创建 Spring ROOT context AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(AppConfig.class); // 管理ROOT context生命周期 servletContext.addListener(new ContextLoaderListener(rootContext)); // 创建spring的dispatcher ,servlet's Spring application context AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext(); dispatcherContext.register(DispatcherConfig.class); ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } } </code></pre> 在上面的代码中,<code>AppConfig</code> 和<code>DispatcherConfig</code> 类定义了将在Web应用程序上下文中的spring管理的bean。<br /> AppConfig: <pre> <code class="language-java">package com.leftso.project.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import com.leftso.project.demo.TestService; @Configuration @ComponentScan(basePackages = { "com.leftso" }) public class AppConfig { // 该类主要是spring 父级容器配置,里面可以定义很多的bean就像在spring-context.xml中一样 // 例如: @Bean public TestService testService() { return new TestService(); } } </code></pre> DispatcherConfig: <pre> <code class="language-java">package com.leftso.project.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration public class DispatcherConfig extends WebMvcConfigurationSupport { // 覆盖父类的配置进行spring mvc的其他详细配置,配置内容可参考xml的spring-mvc /** * * <pre> * [Function]: * JSP 视图解析器 * [Description]: * JSP 视图解析器 * </pre> * * @return JSP 视图解析器 */ @Bean public ViewResolver jspViewResolver() { InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver(); internalResourceViewResolver.setViewClass(JstlView.class); internalResourceViewResolver.setSuffix(".jsp"); internalResourceViewResolver.setPrefix("/WEB-INF/views/"); internalResourceViewResolver.setOrder(4); return internalResourceViewResolver; } /** * 资源文件处理器 */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } } </code></pre> <p><strong>例子二:</strong><br /> 基于Java配置的Spring MVC 5.0的配置,spring mvc 5.0为我们提供了一个封装的抽象类,我们实现这个类并指定相关的配置Java就可以了非常方便:</p> <pre> <code class="language-java">package com.leftso.project.demo.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; /** * Spring MVC 5启动配置 * * @author xqlee * */ public class SpringMVC5AnnotationConfigDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] {}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { WebMvcConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } } </code></pre> <p>WebMvcConfig:<br />  </p> <pre> <code class="language-java">package com.leftso.project.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.leftso.project.demo" }) public class WebMvcConfig implements WebMvcConfigurer { @Bean public InternalResourceViewResolver resolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setViewClass(JstlView.class); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; } } </code></pre> <p>这比起第一种方式少些几句代码。</p> <h2><br /> 五.编写一个测试spring mvc 5.0的controller</h2> <pre> <code class="language-java">package com.leftso.project.demo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @GetMapping("/sayHello.do") public Object sayHello(String name) { return "Hello," + name; } } </code></pre> 将项目添加到tomcat中,启动tomcat,并在浏览器中访问controller的地址:<br /> <img alt="spring mvc 5.0" class="img-thumbnail" src="/assist/images/blog/e2422615e7924625a55ad38461e09529.png" /><br /> 从上图可以看到我们的<a rel="" target="_blank"href="http://www.leftso.com/blog/305.html" rel="" target="_blank">spring mvc5.0</a>项目已经成功启动.后续将讲解整合其他配置<br />  
  • spring boot elasticsearch 5.x/6.x版本整合详解

    前言    本教程主要讲解spring boot如何整合 spring data elasticsearch 实现elasticsearch检索引擎的整合使用前言    本教程主要讲解spring boot如何整合 spring data elasticsearch 实现elasticsearch检索引擎的整合使用。需要注意的是spring boot 1.x就算当前最新的1.5.11支持的elasticsearch版本仅为2.x。如果需要spring boot支持5.x版本的elasticsearch或者6.x版本的elasticsearch则需要将spring boot版本升级到最新的2.0.1即可。本教程所使用的elasticsearch版本为6.2。所以使用的spring boot版本将会是2.0.1spring boot elasticsearch整合项目结构图 ​Spring Boot elasticsearch整合项目文件详解1.pom.xml文件 由于本项目使用的maven管理。所以这里就只能看到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> <artifactId>demo-springboot-springdata-elasticsearch</artifactId> <packaging>jar</packaging> <url>https://www.leftso.com</url> <version>1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--HTTP方式接入--> <!-- <dependency> <groupId>io.searchbox</groupId> <artifactId>jest</artifactId> </dependency>--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <!-- Package as an executable jar/war --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 核心依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> Book.java 这个类主要用于创建检索的对象实体。package com.leftso.project.demo.book.model; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; @Document(indexName = "lee", type = "books") public class Book { @Id private String id; private String title; private String author; private String releaseDate; public Book() { } public Book(String id, String title, String author, String releaseDate) { this.id = id; this.title = title; this.author = author; this.releaseDate = releaseDate; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getReleaseDate() { return releaseDate; } public void setReleaseDate(String releaseDate) { this.releaseDate = releaseDate; } @Override public String toString() { return "Book{" + "id='" + id + '\'' + ", title='" + title + '\'' + ", author='" + author + '\'' + ", releaseDate='" + releaseDate + '\'' + '}'; } } BookRepository.java 该接口主要继承了spring data的接口。实现了语义即可实现功能。spring data的强大大家都懂。package com.leftso.project.demo.book.repository; import com.leftso.project.demo.book.model.Book; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; public interface BookRepository extends ElasticsearchRepository<Book, String> { Page<Book> findByAuthor(String author, Pageable pageable); Page<Book> findByTitle(String title, Pageable pageable); }BookService.java 该接口主要是写了几个测试的方法。package com.leftso.project.demo.book.service; import com.leftso.project.demo.book.model.Book; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; public interface BookService { Book save(Book book); void delete(Book book); Book findOne(String id); Iterable<Book> findAll(); Page<Book> findByAuthor(String author, PageRequest pageRequest); Page<Book> findByTitle(String title, PageRequest pageRequest); }spring boot 启动类Application.javapackage com.leftso.project.demo; import com.leftso.project.demo.book.model.Book; import com.leftso.project.demo.book.service.BookService; import org.elasticsearch.client.Client; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import java.util.Map; @SpringBootApplication public class Application implements CommandLineRunner { @Autowired private ElasticsearchOperations es; @Autowired private BookService bookService; public static void main(String args[]) { SpringApplication.run(Application.class, args); } @Override public void run(String... args) throws Exception { printElasticSearchInfo(); Book b1=bookService.save(new Book("1001", "这是一个Spring Boot1.0的书籍", "Rambabu Posa", "23-FEB-2017")); Book b2=bookService.save(new Book("1002", "Apache的一本书籍", "Rambabu Posa", "13-MAR-2017")); bookService.save(new Book("1003", "Solr是一个搜索引擎", "Rambabu Posa", "21-MAR-2017")); //fuzzey search // Page<Book> books = bookService.findByAuthor("Rambabu", new PageRequest(0, 10)); Page<Book> books = bookService.findByTitle("书", new PageRequest(0, 10)); books.forEach(x -> System.out.println(x)); } //useful for debug private void printElasticSearchInfo() { System.out.println("--ElasticSearch-->"); Client client = es.getClient(); Map<String, String> asMap = client.settings().getAsMap(); asMap.forEach((k, v) -> { System.out.println(k + " = " + v); }); System.out.println("<--ElasticSearch--"); } } 启动类实现了一个CommandLineRunner接口。该接口主要有个run方法。启动spring boot的时候会执行run方法的内容。就当测试啦。spring boot elasticsearch整合测试 鼠标右键启动application.java即可:​查看下方的执行情况:​从上图可以看到已经连接到elasticsearch 192.168.0.225:3000服务那边去了​从上图可以看到我们已经存入elasticsearch 并且通过spring data elasticsearch 的查询接口查询出了Book title字段中包含“书”的所有结果。提示:项目源码下载 demo-springboot-springdata-elasticsearch.zip
  • spring boot 文件上传 REST风格API ajax方式-Java编程

    Java编程之Spring Boot 文件上传 REST风格API ajax方式<h2>一、摘要说明</h2>   这篇文章将告诉你在spring boot(REST 风格)WEB项目中如何用ajax请求上传文件。<br /> <br />   本文章中需要使用的工具: <ol> <li>Spring Boot 1.4.3.RELEASE</li> <li>Spring 4.3.5.RELEASE</li> <li>Thymeleaf</li> <li>jQuery (webjars)</li> <li>Maven</li> <li>Embedded Tomcat 8.5.6</li> <li>Google Chrome 浏览器(Network Inspect)</li> </ol> <h2>二、项目结构</h2> 一个标准的maven项目结构<br /> <img alt="项目结构" class="img-thumbnail" src="/assist/images/blog/811600c9be364e56b3c68ebbe78e0b07.png" /> <h2>三、项目依赖</h2> 声明一个外部的jQuery webjar依赖项,用于HTML表单中的Ajax请求。<br /> <br /> <strong>pom.xml</strong> <pre> <code class="language-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.mkyong</groupId> <artifactId>spring-boot-file-upload</artifactId> <packaging>jar</packaging> <version>1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.3.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- hot swapping, disable cache for template, enable live reload --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>2.2.4</version> </dependency> </dependencies> <build> <plugins> <!-- Package as an executable jar/war --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project></code></pre> <h2>四、文件上传</h2> 为了支持AJAX请求和响应, 最简单的方式是返回<code>ResponseEntity</code>. <h2>4.1下面的例子演示了上传文件的三种可能方式:</h2> <ol> <li>单个文件上传 – <code>MultipartFile</code></li> <li>多个文件上传– <code>MultipartFile[]</code></li> <li>Map file upload to a Model – <code>@ModelAttribute</code></li> </ol> <strong>RestUploadController.java</strong> <pre> <code class="language-java">import com.mkyong.model.UploadModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @RestController public class RestUploadController { private final Logger logger = LoggerFactory.getLogger(RestUploadController.class); //Save the uploaded file to this folder private static String UPLOADED_FOLDER = "F://temp//"; // 3.1.1 Single file upload @PostMapping("/api/upload") // If not @RestController, uncomment this //@ResponseBody public ResponseEntity<?> uploadFile( @RequestParam("file") MultipartFile uploadfile) { logger.debug("Single file upload!"); if (uploadfile.isEmpty()) { return new ResponseEntity("please select a file!", HttpStatus.OK); } try { saveUploadedFiles(Arrays.asList(uploadfile)); } catch (IOException e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity("Successfully uploaded - " + uploadfile.getOriginalFilename(), new HttpHeaders(), HttpStatus.OK); } // 3.1.2 Multiple file upload @PostMapping("/api/upload/multi") public ResponseEntity<?> uploadFileMulti( @RequestParam("extraField") String extraField, @RequestParam("files") MultipartFile[] uploadfiles) { logger.debug("Multiple file upload!"); // Get file name String uploadedFileName = Arrays.stream(uploadfiles).map(x -> x.getOriginalFilename()) .filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" , ")); if (StringUtils.isEmpty(uploadedFileName)) { return new ResponseEntity("please select a file!", HttpStatus.OK); } try { saveUploadedFiles(Arrays.asList(uploadfiles)); } catch (IOException e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity("Successfully uploaded - " + uploadedFileName, HttpStatus.OK); } // 3.1.3 maps html form to a Model @PostMapping("/api/upload/multi/model") public ResponseEntity<?> multiUploadFileModel(@ModelAttribute UploadModel model) { logger.debug("Multiple file upload! With UploadModel"); try { saveUploadedFiles(Arrays.asList(model.getFiles())); } catch (IOException e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity("Successfully uploaded!", HttpStatus.OK); } //save file private void saveUploadedFiles(List<MultipartFile> files) throws IOException { for (MultipartFile file : files) { if (file.isEmpty()) { continue; //next pls } byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename()); Files.write(path, bytes); } } }</code></pre> <h2>4.2选择4.1中的第三种方式上传文件并且使用注解@ModelAttribute</h2> <strong>UploadModel.java</strong> <pre> <code class="language-java">import org.springframework.web.multipart.MultipartFile; public class UploadModel { private String extraField; private MultipartFile[] files; //getters and setters }</code></pre> <h2>五、视图文件的编写</h2> HTML form for multiple file uploads.<br /> <strong>upload.html</strong> <pre> <code class="language-html"><!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <h1>Spring Boot - Multiple file upload example - AJAX</h1> <form method="POST" enctype="multipart/form-data" id="fileUploadForm"> <input type="text" name="extraField"/><br/><br/> <input type="file" name="files"/><br/><br/> <input type="file" name="files"/><br/><br/> <input type="submit" value="Submit" id="btnSubmit"/> </form> <h1>Ajax Post Result</h1> <pre> <span id="result"></span> </pre> <script type="text/javascript" src="webjars/jquery/2.2.4/jquery.min.js"></script> <script type="text/javascript" src="js/main.js"></script> </body> </html></code></pre> <h2>六、jQuery – Ajax Request</h2> jQuery通过f<code>#id获取form</code>,并且发送multipart form 数据通过ajax请求.<br /> <strong>resources/static/js/main.js</strong> <pre> <code class="language-javascript">$(document).ready(function () { $("#btnSubmit").click(function (event) { //stop submit the form, we will post it manually. event.preventDefault(); fire_ajax_submit(); }); }); function fire_ajax_submit() { // Get form var form = $('#fileUploadForm')[0]; var data = new FormData(form); data.append("CustomField", "This is some extra data, testing"); $("#btnSubmit").prop("disabled", true); $.ajax({ type: "POST", enctype: 'multipart/form-data', url: "/api/upload/multi", data: data, //http://api.jquery.com/jQuery.ajax/ //https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects processData: false, //prevent jQuery from automatically transforming the data into a query string contentType: false, cache: false, timeout: 600000, success: function (data) { $("#result").text(data); console.log("SUCCESS : ", data); $("#btnSubmit").prop("disabled", false); }, error: function (e) { $("#result").text(e.responseText); console.log("ERROR : ", e); $("#btnSubmit").prop("disabled", false); } }); }</code></pre> <h2>七、Exception Handler异常拦截</h2> 拦截来自 Ajax请求的异常, 只需要继承 <code>ResponseEntityExceptionHandler</code> 并且返回 <code>ResponseEntity</code>.<br /> <strong>RestGlobalExceptionHandler.java</strong> <pre> <code class="language-java">import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartException; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import javax.servlet.http.HttpServletRequest; //http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-error-handling @ControllerAdvice public class RestGlobalExceptionHandler extends ResponseEntityExceptionHandler { // Catch file size exceeded exception! @ExceptionHandler(MultipartException.class) @ResponseBody ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) { HttpStatus status = getStatus(request); return new ResponseEntity(ex.getMessage(), status); // example //return new ResponseEntity("success", responseHeaders, HttpStatus.OK); } private HttpStatus getStatus(HttpServletRequest request) { Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); if (statusCode == null) { return HttpStatus.INTERNAL_SERVER_ERROR; } return HttpStatus.valueOf(statusCode); } }</code></pre> <h2>八、演示</h2> 使用默认的嵌入式Tomcat启动Spring启动<code>mvn spring-boot:run</code>.<br /> 8.1访问http://localhost:8080/,选择几个文件并单击submit以触发ajax请求。<br /> <img alt="访问并上传" class="img-thumbnail" src="/assist/images/blog/19d6d8c691d04a079fd5a18adc7560fa.png" /><br /> 8.2 Google Chrome浏览器,检查“网络检查”中的请求和响应<br /> <img alt="观察请求" class="img-thumbnail" src="/assist/images/blog/ae51363c32cf415b943dbdc57d659470.png" /><br /> 8.4 Google Chrome, “Request Payload”<br /> <img alt="上传内容" class="img-thumbnail" src="/assist/images/blog/7f1ff5d5dde64d89ae7afd664c5df0f5.png" /> <h2>9.curl工具测试</h2> More testing with <code>cURL</code> command.<br /> 9.1测试单个文件上传 <pre> <code>$ curl -F file=@"f:\\data.txt" http://localhost:8080/api/upload/ Successfully uploaded - data.txt</code></pre> <br /> 9.2.测试多个文件上传 <pre> <code>$ curl -F extraField="abc" -F files=@"f://data.txt" -F files=@"f://data2.txt" http://localhost:8080/api/upload/multi/ Successfully uploaded - data.txt , data2.txt</code></pre> 9.3测试多个文件上传使用maps to Model模式 <pre> <code>$ curl -F extraField="abc" -F files=@"f://data.txt" -F files=@"f://data2.txt" http://localhost:8080/api/upload/multi/model Successfully uploaded! </code></pre> <br /> 9.4测试一个大文件(超过100MB),将会提示下面的错误信息 <pre> <code>$ curl -F file=@"F://movies//300//Sample.mkv" http://localhost:8080/api/upload/ Attachment size exceeds the allowable limit! (10MB)</code></pre> <h2>十、curl测试加自定义错误对象测试</h2> 10.1创建一个自定义对象去存放异常信息<br /> <strong>CustomError.java</strong> <pre> <code class="language-java">public class CustomError { String errCode; String errDesc; public CustomError(String errCode, String errDesc) { this.errCode = errCode; this.errDesc = errDesc; } //getters and setters }</code></pre> 10.2更新全局的异常拦截支持自定义异常信息<br /> <strong>RestGlobalExceptionHandler.java</strong> <pre> <code class="language-java">import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartException; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import javax.servlet.http.HttpServletRequest; @ControllerAdvice public class RestGlobalExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(MultipartException.class) @ResponseBody ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) { HttpStatus status = getStatus(request); return new ResponseEntity(new CustomError("0x000123", "Attachment size exceeds the allowable limit! (10MB)"), status); //return new ResponseEntity("Attachment size exceeds the allowable limit! (10MB)", status); } private HttpStatus getStatus(HttpServletRequest request) { Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); if (statusCode == null) { return HttpStatus.INTERNAL_SERVER_ERROR; } return HttpStatus.valueOf(statusCode); } }</code></pre> <br /> 10.3再次上传一个大文件 <pre> <code>$ curl -F file=@"F://movies//300//Sample.mkv" http://localhost:8080/api/upload/ {"errCode":"0x000123","errDesc":"Attachment size exceeds the allowable limit! (10MB)"}</code></pre> <br /> <a href="http://www.mkyong.com/wp-content/uploads/2017/01/spring-boot-file-upload-ajax-rest.zip" rel="external nofollow" target="_blank">demo项目下载</a>
  • java常用框架SpringMVC3/4入门教程

    SpringMVC框架是一个java里面非常轻量级的mvc框架之一,与spring框架同源,整合方便快捷.java常用框架SpringMVC3/4入门教程 <p>1SpringMVC3</p> <p>1.1项目结构图</p> <img alt="java常用框架SpringMVC3/4入门教程" src="/assist/images/blog/50f775fc-8470-4e98-bab8-a9195d8d2671.png" style="height:527px; width:313px" /> <p>1.2Pom.xml</p> <pre> <code class="language-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>seven.org</groupId>    <artifactId>springmvc3</artifactId>    <packaging>war</packaging>    <version>0.0.1-SNAPSHOT</version>    <name>springmvc3 Maven Webapp</name>    <url>http://maven.apache.org</url>    <properties>       <junit.version>4.12</junit.version>       <spring.version>3.2.2.RELEASE</spring.version>       <org.codehaus.jackson.version>1.9.13</org.codehaus.jackson.version>       <commons-fileupload.version>1.3.1</commons-fileupload.version>    </properties>    <dependencies>       <dependency>          <!-- test -->          <groupId>junit</groupId>          <artifactId>junit</artifactId>          <version>${junit.version}</version>          <scope>test</scope>       </dependency>         <!-- spring framework start -->       <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-core</artifactId>          <version>${spring.version}</version>       </dependency>       <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-context</artifactId>          <version>${spring.version}</version>       </dependency>       <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-web</artifactId>          <version>${spring.version}</version>       </dependency>       <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-webmvc</artifactId>          <version>${spring.version}</version>       </dependency>       <!-- spring framework end -->         <!-- 为SpringMVC提供json数据类型支持 -->         <!-- 注意,新版的 jackson-core-asl已经升级为Group:com.fasterxml.jackson.core|Artifact:jackson-core在SpringMVC4中需要使用新版 -->       <dependency>          <groupId>org.codehaus.jackson</groupId>          <artifactId>jackson-core-asl</artifactId>          <version>${org.codehaus.jackson.version}</version>       </dependency>       <dependency>          <groupId>org.codehaus.jackson</groupId>          <artifactId>jackson-mapper-asl</artifactId>          <version>${org.codehaus.jackson.version}</version>       </dependency>         <!-- el 标签库 -->       <!-- standard.jar -->       <dependency>          <groupId>taglibs</groupId>          <artifactId>standard</artifactId>          <version>1.1.2</version>       </dependency>       <!-- JSTL -->       <dependency>          <groupId>javax.servlet</groupId>          <artifactId>jstl</artifactId>          <version>1.1.2</version>       </dependency>       <!-- /el 标签库 -->         <!-- 文件上传下载 -->       <dependency>          <groupId>commons-fileupload</groupId>          <artifactId>commons-fileupload</artifactId>          <version>${commons-fileupload.version}</version>       </dependency>         <!-- slf4j 和 log4j合用的Maven配置 -->       <dependency>          <groupId>org.slf4j</groupId>          <artifactId>slf4j-log4j12</artifactId>          <version>1.7.2</version>       </dependency>      </dependencies>    <build>       <finalName>springmvc3</finalName>    </build> </project></code></pre>   <p>1.3web.xml</p> <pre> <code class="language-xml"><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"    version="3.0">    <display-name>Archetype Created Web Application</display-name>      <!-- 字符集处理 -->    <filter>       <filter-name>CharacterEncodingFilter</filter-name>       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>       <init-param>          <param-name>encoding</param-name>          <param-value>utf-8</param-value>       </init-param>    </filter>    <filter-mapping>       <filter-name>CharacterEncodingFilter</filter-name>       <url-pattern>/*</url-pattern>    </filter-mapping>        <!-- spring 配置 -->    <context-param>       <param-name>contextConfigLocation</param-name>       <param-value>classpath:/cfg/spring/spring-beans.xml</param-value>    </context-param>    <listener>       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>      <!-- 配置缓存清除监听器,负责处理由 JavaBean Introspector 功能而引起的缓存泄露 -->    <listener>       <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>    </listener>        <!-- springMVC配置 -->    <servlet>       <servlet-name>springMVCSerlet</servlet-name>       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>       <init-param>          <param-name>contextConfigLocation</param-name>          <param-value>classpath:/cfg/spring/spring-servlet.xml</param-value>       </init-param>       <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>       <servlet-name>springMVCSerlet</servlet-name>       <url-pattern>/</url-pattern>    </servlet-mapping>      <!-- 添加下面容器,防止同一个服务器部署多个项目web.root冲突 -->    <context-param>       <param-name>webAppRootKey</param-name>       <param-value>springMVC3</param-value>    </context-param>        <!-- log4j配置 -->    <context-param>       <param-name>log4jConfigLocation</param-name>       <param-value>classpath:/cfg/log/Log4j.properties</param-value>    </context-param>    <context-param>       <param-name>log4jRefreshInterval</param-name>       <param-value>60000</param-value>    </context-param>      <!-- session timeout -->    <session-config>       <!-- 分钟 -->       <session-timeout>60</session-timeout>    </session-config>      <!-- welcome page -->    <welcome-file-list>       <welcome-file>index.html</welcome-file>       <welcome-file>index.jsp</welcome-file>    </welcome-file-list>      <!-- session copy -->    <distributable /> </web-app></code></pre>   <p>1.4spring-servlet.xml</p> <pre> <code class="language-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" xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans             http://www.springframework.org/schema/beans/spring-beans-3.2.xsd             http://www.springframework.org/schema/mvc             http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd             http://www.springframework.org/schema/context             http://www.springframework.org/schema/context/spring-context-3.2.xsd ">      <!-- 自动扫描包 -->    <context:component-scan base-package="com" />      <!-- 注解驱动 -->    <mvc:annotation-driven />    <mvc:default-servlet-handler />    <!-- 资源管理不拦截 -->    <mvc:resources location="/resources/" mapping="/resources/**" />    <mvc:resources location="/upload/" mapping="/upload/**" />      <!-- 内部资源视图解析器 prefix + logicName + suffix /WEB-INF/jsps/ + index + .jsp -->    <bean id="internalResourceViewResolver"       class="org.springframework.web.servlet.view.InternalResourceViewResolver">       <!-- 前缀 -->       <property name="prefix" value="/WEB-INF/pages/" />       <!-- 后缀 -->       <property name="suffix" value="" />    </bean>        <!-- 上传图片/文件需要配置 -->    <bean id="multipartResolver"       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">       <property name="maxUploadSize" value="104857600" />       <property name="maxInMemorySize" value="4096" />    </bean>        <!-- 配置JSON支持 start -->    <bean id="mappingJacksonHttpMessageConverter"    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">       <property name="supportedMediaTypes">          <list>             <!-- 处理返回的json数据的编码,默认是ISO-88859-1 -->             <value>text/html;charset=UTF-8</value>          </list>       </property>    </bean>    <bean    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">       <!-- messageConverters属性中加入 mappingJacksonHttpMessageConverter用来处理json数据类行 -->       <property name="messageConverters">          <list>             <ref bean="mappingJacksonHttpMessageConverter" />          </list>       </property>    </bean>    <!-- 配置JSON支持 end -->     </beans></code></pre> <br /> 1.5spring-beans.xml <pre> <code class="language-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" xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jpa="http://www.springframework.org/schema/data/jpa"    xsi:schemaLocation="http://www.springframework.org/schema/beans                 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd             http://www.springframework.org/schema/mvc             http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd               http://www.springframework.org/schema/aop             http://www.springframework.org/schema/aop/spring-aop-3.2.xsd             http://www.springframework.org/schema/context             http://www.springframework.org/schema/context/spring-context-3.2.xsd             http://www.springframework.org/schema/tx             http://www.springframework.org/schema/tx/spring-tx-3.2.xsd             http://www.springframework.org/schema/data/jpa             http://www.springframework.org/schema/data/jpa/spring-jpa.xsd ">    <context:annotation-config />    <!-- 启动自动扫描该包下所有的注解(如@controller) -->    <context:component-scan base-package="com" />   </beans>  </code></pre>   <p>1.6Log4j配置文件</p> <pre> <code>#defind the rooeLogger ,the rootlogger min level is INFO,and two way to output log log4j.rootLogger = INFO,FILE,CONSOLE,DATABASE   #---------------------------------------------------------------------- #defind the FILE as file everyday                                     | #---------------------------------------------------------------------- log4j.appender.FILE = org.apache.log4j.DailyRollingFileAppender   #the log min level set as INFO log4j.appender.FILE.Threshold=INFO   #log file encoding set UTF-8 log4j.appender.FILE.encoding=UTF-8   #log file path log4j.appender.FILE.File=/home/tomcat/log/springmvc3/springmvc3   #log file name append log4j.appender.FILE.DatePattern='_'yyyy-MM-dd'.log'   #Immediate write the log is true log4j.appender.FILE.ImmediateFlush=true   #the layout of the log log4j.appender.FILE.layout=org.apache.log4j.PatternLayout   #the detail layout of log  in the log file log4j.appender.FILE.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} Springmvc3 %-5p [%c:%L] | %m%n   #------------------------------------------------------------------------- #this use the 'org.apache.log4j.ConsoleAppender' to output in the Console| #------------------------------------------------------------------------- log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender   #output min level is INFO log4j.appender.Threshold=INFO   #the output target is Console log4j.appender.CONSOLE.Target=System.out   #the layout of the log log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} springmvc3 %-5p | %m%n   #---------------------------------------------------------------------------- #insert the log into database                                               | #---------------------------------------------------------------------------- log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppender #The jdbc url log4j.appender.DATABASE.URL=jdbc:mysql://localhost:3306/springmvc3 #The jdbc driver log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver #DB user log4j.appender.DATABASE.user=root #DB password log4j.appender.DATABASE.password=root #sql log4j.appender.DATABASE.sql=INSERT INTO zhl_log (operationTime,logLevel,logClass,logDetail)  VALUES ("%d{yyyy-MM-dd HH:mm:ss}", "%-5p","%F:%L", "%m") #layout log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout #layout detail log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n</code></pre> <br /> 1.7测试vo <pre> <code class="language-java">package com.xqlee.springmvc.vo;   /**  *  *  * <pre>  * @功能说明 [测试bean]  * @其他说明 [暂无]  * @文件编码 [UTF-8]  * @所属包名 [com.xqlee.springmvc.vo]  * @项目名称 [cdws]  * @创建日期 []  * @创建人员 [lxq]  * @最后修改 []  * @修改说明 [暂无更新]  * @修改人员 [lxq]  * @公司组织 [org]  * @版本说明 [v 1.0]  *  * </pre>  */ public class Tobject {      private String id;    private String name;    private String num;      public Tobject(String id, String name, String num) {       this.id = id;       this.name = name;       this.num = num;    }      public String getId() {       return id;    }      public void setId(String id) {       this.id = id;    }      public String getName() {       return name;    }      public void setName(String name) {       this.name = name;    }      public String getNum() {       return num;    }      public void setNum(String num) {       this.num = num;    }   }</code></pre> <br /> 1.8测试controller <pre> <code class="language-java">package com.xqlee.springmvc.controller;   import java.util.Vector;   import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;   import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;   import com.xqlee.springmvc.vo.Tobject;   /**  *  *  * <pre>  * @功能说明 [测试类]  * @其他说明 [暂无]  * @文件编码 [UTF-8]  * @所属包名 [com.xqlee.springmvc.controller]  * @项目名称 [cdws]  * @创建日期 []  * @创建人员 [lxq]  * @最后修改 []  * @修改说明 [暂无更新]  * @修改人员 [lxq]  * @公司组织 [org]  * @版本说明 [v 1.0]  *  * </pre>  */ @Controller(value = "/beanTestController.do") public class BeanTestController {    @RequestMapping(params = "method=Vector")    // @ResponseBody    public Object testVector(HttpServletRequest request,          HttpServletResponse response) {       // 创建容器       Vector<Tobject> vtb = new Vector<Tobject>();       Tobject tb;       for (int i = 0; i <= 5; i++) {          tb = new Tobject("ID-" + i, "名称Name-" + i, "Num-" + i);          vtb.add(tb);       }       request.setAttribute("vtb", vtb);       return "../../vector.jsp";    }      @RequestMapping(params = "method=testJson")    @ResponseBody    public Object testJson(HttpServletRequest request,          HttpServletResponse response) {       // 创建容器       Vector<Tobject> vtb = new Vector<Tobject>();       Tobject tb;       for (int i = 0; i <= 5; i++) {          tb = new Tobject("ID-" + i, "名称Name-" + i, "Num-" + i);          vtb.add(tb);       }       return vtb;    }   }</code></pre>   <p>1.9index.jsp</p> <pre> <code class="language-html"><!DOCTYPE> <html> <body>    <h2>Hello World!</h2>    <a href="beanTestController.do?method=Vector">Vector Test</a> </body> </html></code></pre> <br /> 1.10vector.jsp <pre> <code class="language-html"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE> <html> <body>    <table border='1'>       <thead>          <tr>             <td>ID</td>             <td>Name</td>             <td>Num</td>          </tr>       </thead>       <tbody>          <c:forEach items="${vtb}" var="Object">             <tr>                 <td>${Object.id}</td>                 <td>${Object.name}</td>                 <td>${Object.num}</td>             </tr>          </c:forEach>       </tbody>    </table>     </body> </html></code></pre> <br /> 2 SpringMVC4 <p>2.1项目结构图</p> <img alt="2" src="/assist/images/blog/63555b40-5fa1-41e6-9d7c-3d9e088a6223.png" style="height:510px; width:387px" /> <p>2.2pom.xml</p> <pre> <code class="language-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>seven.org</groupId>    <artifactId>springMVC</artifactId>    <packaging>war</packaging>    <version>0.0.1-SNAPSHOT</version>    <name>springMVC Maven Webapp</name>    <url>http://maven.apache.org</url>    <!-- 属性版本 -->    <properties>       <junit.version>4.12</junit.version>       <spring.version>4.1.7.RELEASE</spring.version>       <org.slf4j.version>1.7.2</org.slf4j.version>       <mysql.driver.version>5.1.32</mysql.driver.version>    <com.fasterxml.jackson.jaxrs.version>2.4.1</com.fasterxml.jackson.jaxrs.version>       <commons-fileupload.version>1.3.1</commons-fileupload.version>      </properties>    <dependencies>         <!-- 测试所需 -->       <dependency>          <groupId>junit</groupId>          <artifactId>junit</artifactId>          <version>${junit.version}</version>          <scope>test</scope>       </dependency>         <!-- spring core -->       <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-core</artifactId>          <version>${spring.version}</version>       </dependency>       <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-context</artifactId>          <version>${spring.version}</version>       </dependency>       <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-web</artifactId>          <version>${spring.version}</version>       </dependency>       <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-webmvc</artifactId>          <version>${spring.version}</version>       </dependency>         <!-- MySQL数据库驱动 导入 start -->       <dependency>          <groupId>mysql</groupId>          <artifactId>mysql-connector-java</artifactId>          <version>${mysql.driver.version}</version>       </dependency>       <!-- MySQL数据库驱动 导入 end -->           <!-- el 标签库 -->       <!-- standard.jar -->       <dependency>          <groupId>taglibs</groupId>          <artifactId>standard</artifactId>          <version>1.1.2</version>       </dependency>       <!-- JSTL -->       <dependency>          <groupId>javax.servlet</groupId>          <artifactId>jstl</artifactId>          <version>1.1.2</version>       </dependency>       <!-- /el 标签库 -->         <!-- 处理json -->       <dependency>          <groupId>com.fasterxml.jackson.jaxrs</groupId>          <artifactId>jackson-jaxrs-xml-provider</artifactId>          <version>${com.fasterxml.jackson.jaxrs.version}</version>       </dependency>         <!-- 文件上传下载 -->       <dependency>          <groupId>commons-fileupload</groupId>          <artifactId>commons-fileupload</artifactId>          <version>${commons-fileupload.version}</version>       </dependency>         <!-- slf4j 和 log4j合用的Maven配置 -->       <dependency>          <groupId>org.slf4j</groupId>          <artifactId>slf4j-log4j12</artifactId>          <version>${org.slf4j.version}</version>       </dependency>      </dependencies>    <build>       <finalName>springMVC</finalName>    </build> </project></code></pre> <br /> 2.3web.xml <pre> <code class="language-xml"><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"    version="3.0">    <display-name>Archetype Created Web Application</display-name>      <!-- 字符集处理 -->    <filter>       <filter-name>CharacterEncodingFilter</filter-name>       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>       <init-param>          <param-name>encoding</param-name>          <param-value>utf-8</param-value>       </init-param>    </filter>    <filter-mapping>       <filter-name>CharacterEncodingFilter</filter-name>       <url-pattern>/*</url-pattern>    </filter-mapping>        <!-- spring 核心配置 -->    <context-param>       <param-name>contextConfigLocation</param-name>       <param-value>classpath:/cfg/spring/spring-beans.xml</param-value>    </context-param>    <listener>       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>      <!-- 配置缓存清除监听器,负责处理由 JavaBean Introspector 功能而引起的缓存泄露 -->    <listener>       <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>    </listener>        <!-- springMVC配置 -->    <servlet>       <servlet-name>springMVCSerlet</servlet-name>       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>       <init-param>          <param-name>contextConfigLocation</param-name>          <param-value>classpath:/cfg/spring/spring-servlet.xml</param-value>       </init-param>       <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>       <servlet-name>springMVCSerlet</servlet-name>       <url-pattern>/</url-pattern>    </servlet-mapping>      <!-- 添加下面容器,防止同一个服务器部署多个项目web.root冲突 -->    <context-param>       <param-name>webAppRootKey</param-name>       <param-value>springMVC4</param-value>    </context-param>      <!-- session timeout -->    <session-config>       <!-- 分钟 -->       <session-timeout>60</session-timeout>    </session-config>      <!-- log4j配置 -->    <context-param>       <param-name>log4jConfigLocation</param-name>       <param-value>classpath:/cfg/log/Log4j.properties</param-value>    </context-param>    <context-param>       <param-name>log4jRefreshInterval</param-name>       <param-value>60000</param-value>    </context-param>    <!--添加监听 -->    <listener>       <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>    </listener>    <!-- /log4j配置 -->      <!-- welcome page -->    <welcome-file-list>       <welcome-file>index.html</welcome-file>       <welcome-file>index.jsp</welcome-file>    </welcome-file-list>      <!-- session copy -->    <distributable /> </web-app></code></pre>   <p>2.4 weblogic.xml</p> <pre> <code class="language-xml"><?xml version="1.0" encoding="UTF-8"?> <weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee    http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd    http://xmlns.oracle.com/weblogic/weblogic-web-app    http://xmlns.oracle.com/weblogic/weblogic-web-app/1.2/weblogic-web-app.xsd">      <container-descriptor>       <!-- 针对weblogic10以下的版本使用该语句,不能与厦门的prefer-application-packages同时使用 -->       <!-- <prefer-web-inf-classes>true</prefer-web-inf-classes> -->       <!-- 针对weblogic10及以上的版本如果上面语句无法成功使用该语句,不能与厦门的prefer-web-inf-classes同时使用 -->       <prefer-application-packages>          <package-name>org.apache.commons.lang.*</package-name>          <package-name>antlr.*</package-name>          <package-name>org.hibernate.*</package-name>          <package-name>javax.persistence.*</package-name>       </prefer-application-packages>    </container-descriptor> </weblogic-web-app></code></pre>   <p>2.5spring-servlet.xml</p> <pre> <code class="language-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" xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans             http://www.springframework.org/schema/beans/spring-beans-4.1.xsd             http://www.springframework.org/schema/mvc             http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd             http://www.springframework.org/schema/context             http://www.springframework.org/schema/context/spring-context-4.1.xsd ">      <!-- 自动扫描controller包下所有 -->    <context:component-scan base-package="com.xqlee.springmvc.controller" />    <!-- 注解驱动 -->    <mvc:annotation-driven />    <mvc:default-servlet-handler />    <!-- 资源管理不拦截 -->    <mvc:resources location="/resources/" mapping="/resources/**" />    <mvc:resources location="/upload/" mapping="/upload/**" />      <!-- 内部资源视图解析器 prefix + logicName + suffix /WEB-INF/jsps/ + index + .jsp -->    <bean id="internalResourceViewResolver"       class="org.springframework.web.servlet.view.InternalResourceViewResolver">       <!-- 前缀 -->       <property name="prefix" value="/WEB-INF/pages/" />       <!-- 后缀 -->       <property name="suffix" value="" />    </bean>      <!-- 处理在controller中使用注解@ResponseBody标签返回JSON数据 Start -->    <!-- 注意[由于我在pom.xml引入的是2.4.1版本]:所以class=org.springframework.http.converter.json.MappingJackson2HttpMessageConverter -->    <!-- [如果pom.xml引入的是1.xx版本]class=org.springframework.http.converter.json.MappingJacksonHttpMessageConverter -->    <bean id="mappingJackson2HttpMessageConverter"    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">       <property name="supportedMediaTypes">          <list>             <value>text/html;charset=UTF-8</value>             <value>text/json;charset=UTF-8</value>             <value>application/json;charset=UTF-8</value>          </list>       </property>    </bean>    <bean    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">       <property name="messageConverters">          <list>             <ref bean="mappingJackson2HttpMessageConverter" />          </list>       </property>    </bean>    <!-- JSON数据处理 End -->      <!-- 上传图片/文件需要配置 -->    <bean id="multipartResolver"       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">       <property name="maxUploadSize" value="-1" /><!-- -1表示没有限制 -->       <property name="maxInMemorySize" value="4096" />    </bean>   </beans></code></pre>   <p>2.6spring-beans.xml</p> <pre> <code class="language-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" xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jpa="http://www.springframework.org/schema/data/jpa"    xsi:schemaLocation="http://www.springframework.org/schema/beans                 http://www.springframework.org/schema/beans/spring-beans-4.1.xsd             http://www.springframework.org/schema/mvc             http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd               http://www.springframework.org/schema/aop             http://www.springframework.org/schema/aop/spring-aop-4.1.xsd             http://www.springframework.org/schema/context             http://www.springframework.org/schema/context/spring-context-4.1.xsd             http://www.springframework.org/schema/tx             http://www.springframework.org/schema/tx/spring-tx-4.1.xsd             http://www.springframework.org/schema/data/jpa             http://www.springframework.org/schema/data/jpa/spring-jpa.xsd ">    <context:annotation-config />    <!-- 启动自动扫描该包下所有的注解(如@controller) 一般扫描service,entity,dao,controller由springMVC扫描 -->    <context:component-scan       base-package="com.xqlee.springmvc.service,com.xqlee.springmvc.entity,com.xqlee.springmvc.dao" /> </beans></code></pre>   <p>2.7 Log4j配置文件</p> <pre> <code>#defind the rooeLogger ,the rootlogger min level is INFO,and two way to output log log4j.rootLogger = INFO,FILE,CONSOLE,DATABASE   #---------------------------------------------------------------------- #defind the FILE as file everyday                                     | #---------------------------------------------------------------------- #log4j.appender.FILE = org.apache.log4j.DailyRollingFileAppender   #the log min level set as INFO #log4j.appender.FILE.Threshold=INFO   #log file encoding set UTF-8 #log4j.appender.FILE.encoding=UTF-8   #log file path #log4j.appender.FILE.File=/home/tomcat/log/springmvc4/springmvc4   #log file name append #log4j.appender.FILE.DatePattern='_'yyyy-MM-dd'.log'   #Immediate write the log is true #log4j.appender.FILE.ImmediateFlush=true   #the layout of the log #log4j.appender.FILE.layout=org.apache.log4j.PatternLayout   #the detail layout of log  in the log file #log4j.appender.FILE.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} springmvc4 %-5p [%c:%L] | %m%n   #------------------------------------------------------------------------- #this use the 'org.apache.log4j.ConsoleAppender' to output in the Console| #------------------------------------------------------------------------- log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender   #output min level is INFO log4j.appender.Threshold=INFO   #the output target is Console log4j.appender.CONSOLE.Target=System.out   #the layout of the log log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} springmvc4 %-5p | %m%n   #---------------------------------------------------------------------------- #insert the log into database                                               | #---------------------------------------------------------------------------- #log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppender #The jdbc url #log4j.appender.DATABASE.URL=jdbc:mysql://localhost:3306/springmvc4 #The jdbc driver #log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver #DB user #log4j.appender.DATABASE.user=root #DB password #log4j.appender.DATABASE.password=root #sql #log4j.appender.DATABASE.sql=INSERT INTO zhl_log (operationTime,logLevel,logClass,logDetail)  VALUES ("%d{yyyy-MM-dd HH:mm:ss}", "%-5p","%F:%L", "%m") #layout #log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout #layout detail #log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n</code></pre>   <p>2.8测试vo</p> <pre> <code class="language-java">package com.xqlee.springmvc.vo;   /**  *  *  * <pre>  * @功能说明 [测试bean]  * @其他说明 [暂无]  * @文件编码 [UTF-8]  * @所属包名 [com.xqlee.springmvc.vo]  * @项目名称 [cdws]  * @创建日期 []  * @创建人员 [lxq]  * @最后修改 []  * @修改说明 [暂无更新]  * @修改人员 [lxq]  * @公司组织 [org]  * @版本说明 [v 1.0]  *  * </pre>  */ public class User {      private String id;    private String name;    private String num;      public User(String id, String name, String num) {       this.id = id;       this.name = name;       this.num = num;    }      public String getId() {       return id;    }      public void setId(String id) {       this.id = id;    }      public String getName() {       return name;    }      public void setName(String name) {       this.name = name;    }      public String getNum() {       return num;    }      public void setNum(String num) {       this.num = num;    }   }</code></pre>   <p>2.9测试controller</p> <pre> <code class="language-java">package com.xqlee.springmvc.controller;   import java.util.Vector;   import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;   import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;   import com.xqlee.springmvc.vo.User;   /**  *  *  * <pre>  * &#64;功能说明 [测试类]  * &#64;其他说明 [暂无]  * &#64;文件编码 [UTF-8]  * &#64;所属包名 [com.xqlee.springmvc.controller]  * &#64;项目名称 [cdws]  * &#64;创建日期 []  * &#64;创建人员 [lxq]  * &#64;最后修改 []  * &#64;修改说明 [暂无更新]  * &#64;修改人员 [lxq]  * &#64;公司组织 [org]  * &#64;版本说明 [v 1.0]  *  * </pre>  */ @Controller(value = "/beanTestController.do") public class TestController {    /** 日志 **/    private static final Log log = LogFactory.getLog(TestController.class);      @RequestMapping(params = "method=Vector")    // @ResponseBody    public Object testVector(HttpServletRequest request, HttpServletResponse response) {       // 创建容器       Vector<User> vtb = new Vector<User>();       User tb;       for (int i = 0; i <= 5; i++) {          tb = new User("ID-" + i, "小Name-" + i, "李Num-" + i);          vtb.add(tb);       }       request.setAttribute("vtb", vtb);       log.info("即将跳转.....");       return "../../vector.jsp";    } }</code></pre>   <p>2.10 index.jsp</p> <pre> <code class="language-html"><!DOCTYPE> <html> <body>    <h2>Hello World!</h2>    <a href="beanTestController.do?method=Vector">Vector Test</a> </body> </html></code></pre>   <p>2.11 vector.jsp</p> <pre> <code class="language-html"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE> <html> <body>    <table border='1'>       <thead>          <tr>             <td>ID</td>             <td>Name</td>             <td>Num</td>          </tr>       </thead>       <tbody>          <c:forEach items="${vtb}" var="Object">             <tr>                 <td>${Object.id}</td>                 <td>${Object.name}</td>                 <td>${Object.num}</td>             </tr>          </c:forEach>       </tbody>    </table>     </body> </html></code></pre>   <p>2.12运行结果</p> <img alt="3" src="/assist/images/blog/d439127f-c160-4faa-a47b-1f3118f87ba5.png" style="height:213px; width:422px" /><br /> <img alt="4" src="/assist/images/blog/46005b58-d05f-4bab-b517-11ed209014c9.png" style="height:486px; width:611px" /><br />