首先添加tomcat服务器:window-preferences-server-runtime environments-add-你的服务器地址
window-showview-servers在你的工具栏中会出现servers
Click将tomcat7添加finish即可,注意先finish,然后双击出现的服务器选中图中的选项,这样项目之后就会自动配置到tomcat中一个你可以查看文件夹wtpwebapps中,但真正的运行文件并不在这里,可以方便你查看项目的状况
新建一个maven项目,在项目栏中右击new-project-maven-mavenproject
在图中选中部位右击-Generate D D S
maven的配置可以看一些其他的文章
这个时候我们需要将项目加入到服务器中
右击项目-properties-targeted runtimes
在之前的servers服务器上右击-add and remove
将项目加入finish
publish是部署,start是开始,stop,restart...
我们会在项目列表中还看到servers项目
这就是服务器的一些配置文件,打开下面的server.xml文件我们可以更改字符集,端口号,协议,包括可以添加线程池大小等等,加入的项目也会在最后配置
先关注的两个文件pom.xml和web.xml文件,前者是配置需要引入的包,我会列出一些我用过的,对于不同的环境可能不同的版本才能使用,可以自己调节一下version
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.ck</groupId> <artifactId>MusicWebsite</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <!--dom4j --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <!--mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency> <!--jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--DBCP --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!--junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!--Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.7.RELEASE</version> </dependency> <!--mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.2.8.RELEASE</version> </dependency> <!-- jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.8.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.8.1</version> </dependency> <!-- AOP --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>3.2.7.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.0</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjtools</artifactId> <version>1.8.0</version> </dependency> <!--upload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <!-- Excel文件的下载 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.16</version> </dependency> <!-- codec加密 --> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> <!--jsp的标签 --> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jsp-api</artifactId> <version>9.0.2</version> </dependency> </dependencies> </project>
对于后者web.xml这是配置访问相关文件的,我们了解该服务器的访问流程:浏览器请求http://localhost:8080/项目名/自定义路径-服务器会先从web.xml中查找是否有符合的路径url-pattern,从而访问对应的servlet和filter,如果没有则去找静态的网页资源,所以我们可以在这里配置ssm需要的已存在的类,当然你可以手写或者自动配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>DemoProject</display-name> <welcome-file-list> <welcome-file>web/index.html</welcome-file> <welcome-file>web/index.htm</welcome-file> <welcome-file>web/index.jsp</welcome-file> <welcome-file>web/default.html</welcome-file> <welcome-file>web/default.htm</welcome-file> <welcome-file>web/default.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>DispatcherServlet</display-name> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <description></description> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/*.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <filter> <display-name>CharacterEncodingFilter</display-name> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <description></description> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> </web-app>
Filter过滤器会先遭到访问,DispatcherServlet是总的处理类
在init-param中配置字符集和spring框架的配置文件路径,这个配置文件主要是配置spring框架控制的类的信息,具体的位置如图
会遵循一定的schema格式的xml文件,我们注意到通配符*,所以对于该文件夹下的所有都会被扫描到,这里为了方便只写在一个文件中
spring-mvc.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:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
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/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-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-1.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<context:component-scan base-package="cn.ck"></context:component-scan>自动扫描注解
<mvc:annotation-driven />spring注解的驱动
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/web/"></property>
<property name="suffix" value=".jsp"></property>
</bean>显示的jsp文件的路径,相对webapp文件夹
<util:properties id="dbConfig" location="classpath:db.properties" />数据库的信息提取
<bean id="dbs" class="org.apache.commons.dbcp.BasicDataSource">配置连接池
<property name="driverClassName" value="#{dbConfig.driverclassname}" />
<property name="url" value="#{dbConfig.url}" />
<property name="username" value="#{dbConfig.username}" />
<property name="password" value="#{dbConfig.password}" />
<property name="initialSize" value="#{dbConfig.initialsize}" />
<property name="maxActive" value="#{dbConfig.maxactive}" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">sqlsessionmybatis的重要组建连接池,映射文件
<property name="dataSource" ref="dbs"></property>
<property name="mapperLocations" value="classpath:mybatis/*.xml"></property>
</bean>
<bean id="mapperscanconfig" class="org.mybatis.spring.mapper.MapperScannerConfigurer">sqlsession和映射类的包
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
<property name="basePackage" value="cn.ck.demoproject.mapper" />
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">数据库事物处理
<property name="dataSource" ref="dbs"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="" />
<mvc:exclude-mapping path="/main/**" />
<bean class="cn.ck.demoproject.interceptor.TestInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 请求编码格式 -->
<property name="defaultEncoding" value="utf-8"></property>
<!-- 上传文件大小(单位:字节) -->
<property name="maxUploadSize" value="50000000"></property>
<!-- 缓冲区大小(单位:KB) -->
<property name="maxInMemorySize" value="1024"></property>
</bean>
</beans>
db.properties的内容
driverclassname:com.mysql.jdbc.Driver url:jdbc:mysql://localhost:3306/musicwebsite username:root password:11111 initialsize:30 maxactive:50
musiclistmapper.xml的内容
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.ck.demoproject.mapper.MusicListMapper"> <select id="getFiveTypes" resultType="cn.ck.demoproject.entity.Type"> select guid,type_name typeName,remark,image from type limit 0,5 </select> <select id="getTenHotSongs" resultType="cn.ck.demoproject.entity.Song"> select guid,song_name songName,song_path songPath,song_word songWord,song_size songSize,song_singer songSinger, song_collection songCollection,song_type songType,remark,love,image,song_time songTime from song order by love limit 0,6 </select> <select id="getTenNewSongs" resultType="cn.ck.demoproject.entity.Song"> select guid,song_name songName,song_path songPath,song_word songWord,song_size songSize,song_singer songSinger, song_collection songCollection,song_type songType,remark,love,image,song_time songTime from song order by song_time limit 0,6 </select> <select id="getSingerName" resultType="String" parameterType="String"> select singer_name from singer where guid=#{guid} </select> <select id="getSongById" resultType="cn.ck.demoproject.entity.Song" parameterType="String"> select guid,song_name songName,song_path songPath,song_word songWord,song_size songSize,song_singer songSinger, song_collection songCollection,song_type songType,remark,love,image,song_time songTime from song where guid=#{guid} </select> <update id="addLove"> update song set love=#{love} where guid=#{guid} </update> <select id="getSongsBySingerName" resultType="cn.ck.demoproject.entity.Song" parameterType="String"> select song.guid,song_name songName,song_path songPath,song_word songWord,song_size songSize,song_singer songSinger, song_collection songCollection,song_type songType,song.remark,love,song.image,song_time songTime from song join singer on song.song_singer=singer.guid where singer.singer_name like #{keyword} </select> <select id="getSongsBySongName" resultType="cn.ck.demoproject.entity.Song" parameterType="String"> select song.guid,song_name songName,song_path songPath,song_word songWord,song_size songSize,song_singer songSinger, song_collection songCollection,song_type songType,song.remark,love,song.image,song_time songTime from song where song_name like #{keyword} </select> </mapper>
接下来我们从项目包来走一下流程看一下如何使用
请求-web.xml-dispatcherservlet-spring配置文件-interceptor-请求路径对应的controller-调用service方法-调用mapper方法-对应类的mybatis动态代理技术访问mybatis配置文件-controller返回内容到浏览器或者jsp文件
entity包中是面向对象的实体类,例如user,song等等
这里只是一些配置流程
例如访问http://localhost:8080/MusicWebSite/musiclist/gohomepage.do就会根据返回值访问web下的musicwebsite.jsp文件
package cn.ck.demoproject.controller; import java.io.FileInputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.annotation.Resource; 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 cn.ck.demoproject.entity.ResponseResult; import cn.ck.demoproject.entity.Song; import cn.ck.demoproject.entity.Type; import cn.ck.demoproject.service.MusicListService; @Controller @RequestMapping("/musiclist") public class MusicListController { @Resource(name = "musicListService") MusicListService service; @RequestMapping("/namelist.do") public String getListByName(HttpServletRequest request, String keyword, String page) { List<Song> singernamesongs = service.getSongsBySingerName(keyword); List<Song> songnamesongs = service.getSongsBySongName(keyword); Set<Song> songs = new HashSet<Song>(); songs.addAll(singernamesongs); songs.addAll(songnamesongs); int pages = songs.size() / 5; if (songs.size() % 5 > 0) { pages++; } System.out.println(pages); for (Song song : songs) { String str = song.getSongSinger(); song.setSongSinger(service.getSingerName(str)); } List<Song> songssend = new ArrayList<Song>(); Iterator<Song> it = songs.iterator(); if (page == null) { page = "1"; } int i = Integer.parseInt(page); int j = i * 5; int k = 0; while (it.hasNext() && k < j) { Song song1 = it.next(); System.out.println("....." + song1); if (k >= ((i - 1) * 5)) { songssend.add(song1); } k++; } request.setAttribute("songs", songssend); request.setAttribute("searchkeyword", keyword); request.setAttribute("pages", pages); return "musiclist"; } @RequestMapping("/gohomepage.do") public String goHomePage(HttpServletRequest request) { List<Type> types = service.getFiveTypes(); List<Song> hotsongs = service.getTenHotSongs(); for (Song song : hotsongs) { song.setSongSinger(service.getSingerName(song.getSongSinger())); } List<Song> newsongs = service.getTenNewSongs(); for (Song song : newsongs) { song.setSongSinger(service.getSingerName(song.getSongSinger())); } request.setAttribute("types", types); request.setAttribute("hotsongs", hotsongs); request.setAttribute("newsongs", newsongs); return "musicwebsite"; } @RequestMapping("/love.do") @ResponseBody public ResponseResult love(String guid) { ResponseResult rr = new ResponseResult(); service.addLove(guid); rr.setState(ResponseResult.OK); rr.setMessage("OK"); return rr; } @RequestMapping("/download.do") @ResponseBody public byte[] dowload(HttpServletResponse response, HttpServletRequest request, String guid, String size, String path) throws Exception { // 手工设置 下载头 Content-Disposition System.out.println(path.split("/")[1]); response.setHeader("Content-Disposition", "attachment; filename=\"" + path.split("/")[1] + "\""); System.out.println(request.getRealPath(path)); FileInputStream fis = new FileInputStream(request.getRealPath(path)); byte[] bs = new byte[Integer.parseInt(size)]; int len = 0; while ((len = fis.read(bs)) != -1) { } return bs; } }
package cn.ck.demoproject.entity; import java.io.Serializable; import java.util.Date; public class Song implements Serializable { /** * */ private static final long serialVersionUID = -6647441379708061230L; private String guid; private String songName; private String songPath; private String songWord; private String songSize; private String songSinger; private String songCollection; private String songType; private String remark; private String image; private String love; private Date songTime; public String getSongName() { return songName; } public void setSongName(String songName) { this.songName = songName; } public String getLove() { return love; } public void setLove(String love) { this.love = love; } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getSongPath() { return songPath; } public void setSongPath(String songPath) { this.songPath = songPath; } public String getSongWord() { return songWord; } public void setSongWord(String songWord) { this.songWord = songWord; } public String getSongSize() { return songSize; } public void setSongSize(String songSize) { this.songSize = songSize; } public String getSongSinger() { return songSinger; } public void setSongSinger(String songSinger) { this.songSinger = songSinger; } public String getSongCollection() { return songCollection; } public void setSongCollection(String songCollection) { this.songCollection = songCollection; } public String getSongType() { return songType; } public void setSongType(String songType) { this.songType = songType; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public Date getSongTime() { return songTime; } public void setSongTime(Date songTime) { this.songTime = songTime; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((guid == null) ? 0 : guid.hashCode()); result = prime * result + ((image == null) ? 0 : image.hashCode()); result = prime * result + ((love == null) ? 0 : love.hashCode()); result = prime * result + ((remark == null) ? 0 : remark.hashCode()); result = prime * result + ((songCollection == null) ? 0 : songCollection.hashCode()); result = prime * result + ((songName == null) ? 0 : songName.hashCode()); result = prime * result + ((songPath == null) ? 0 : songPath.hashCode()); result = prime * result + ((songSinger == null) ? 0 : songSinger.hashCode()); result = prime * result + ((songSize == null) ? 0 : songSize.hashCode()); result = prime * result + ((songTime == null) ? 0 : songTime.hashCode()); result = prime * result + ((songType == null) ? 0 : songType.hashCode()); result = prime * result + ((songWord == null) ? 0 : songWord.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Song other = (Song) obj; if (guid == null) { if (other.guid != null) return false; } else if (!guid.equals(other.guid)) return false; if (image == null) { if (other.image != null) return false; } else if (!image.equals(other.image)) return false; if (love == null) { if (other.love != null) return false; } else if (!love.equals(other.love)) return false; if (remark == null) { if (other.remark != null) return false; } else if (!remark.equals(other.remark)) return false; if (songCollection == null) { if (other.songCollection != null) return false; } else if (!songCollection.equals(other.songCollection)) return false; if (songName == null) { if (other.songName != null) return false; } else if (!songName.equals(other.songName)) return false; if (songPath == null) { if (other.songPath != null) return false; } else if (!songPath.equals(other.songPath)) return false; if (songSinger == null) { if (other.songSinger != null) return false; } else if (!songSinger.equals(other.songSinger)) return false; if (songSize == null) { if (other.songSize != null) return false; } else if (!songSize.equals(other.songSize)) return false; if (songTime == null) { if (other.songTime != null) return false; } else if (!songTime.equals(other.songTime)) return false; if (songType == null) { if (other.songType != null) return false; } else if (!songType.equals(other.songType)) return false; if (songWord == null) { if (other.songWord != null) return false; } else if (!songWord.equals(other.songWord)) return false; return true; } @Override public String toString() { return "Song [guid=" + guid + ", songName=" + songName + ", songPath=" + songPath + ", songWord=" + songWord + ", songSize=" + songSize + ", songSinger=" + songSinger + ", songCollection=" + songCollection + ", songType=" + songType + ", remark=" + remark + ", image=" + image + ", love=" + love + ", songTime=" + songTime + "]"; } }
package cn.ck.demoproject.service; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import cn.ck.demoproject.entity.Song; import cn.ck.demoproject.entity.Type; import cn.ck.demoproject.mapper.MusicListMapper; @Service("musicListService") public class MusicListService implements IMusicListService { @Resource(name = "musicListMapper") MusicListMapper dao; public List<Type> getFiveTypes() { // TODO Auto-generated method stub return dao.getFiveTypes(); } public List<Song> getTenHotSongs() { // TODO Auto-generated method stub return dao.getTenHotSongs(); } public String getSingerName(String guid) { // TODO Auto-generated method stub return dao.getSingerName(guid); } public List<Song> getTenNewSongs() { // TODO Auto-generated method stub return dao.getTenNewSongs(); } public void addLove(String guid) { // TODO Auto-generated method stub Song song = dao.getSongById(guid); song.setLove(Integer.parseInt(song.getLove()) + 1 + ""); String love = song.getLove(); dao.addLove(guid, love); } public List<Song> getSongsBySingerName(String keyword) { // TODO Auto-generated method stub keyword = "%" + keyword + "%"; return dao.getSongsBySingerName(keyword); } public List<Song> getSongsBySongName(String keyword) { // TODO Auto-generated method stub keyword = "%" + keyword + "%"; System.out.println(dao.getSongsBySongName("%周%")); return dao.getSongsBySongName(keyword); } }
package cn.ck.demoproject.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.ck.demoproject.entity.Song; import cn.ck.demoproject.entity.Type; public interface MusicListMapper { List<Type> getFiveTypes(); List<Song> getTenHotSongs(); List<Song> getTenNewSongs(); Song getSongById(String guid); void addLove(@Param("guid") String guid, @Param("love") String love); String getSingerName(String guid); List<Song> getSongsBySingerName(String keyword); List<Song> getSongsBySongName(String keyword); }
这里可能大部分的处理写在controller里,这是不合理的,最好写到service里
over