該文檔主要介紹如何創(chuàng)建一個(gè)簡(jiǎn)單的、能夠正常運(yùn)行的spring項(xiàng)目。為往后項(xiàng)目的開(kāi)發(fā)提供便利
成都創(chuàng)新互聯(lián)公司是一家專業(yè)提供會(huì)同企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站制作、成都網(wǎng)站建設(shè)、外貿(mào)營(yíng)銷網(wǎng)站建設(shè)、H5高端網(wǎng)站建設(shè)、小程序制作等業(yè)務(wù)。10年已為會(huì)同眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站設(shè)計(jì)公司優(yōu)惠進(jìn)行中。
使用sts開(kāi)發(fā)軟件創(chuàng)建項(xiàng)目,STS是Spring Tool Suite的簡(jiǎn)稱,該軟件是一個(gè)基于Eclipse環(huán)境的,用于開(kāi)發(fā)spring應(yīng)用程序的軟件。其提供了很多spring相關(guān)的輔助工具,為開(kāi)發(fā)項(xiàng)目提供諸多便利。
編輯spring項(xiàng)目的pom.xml文件,加入spring-mvc容器 相關(guān)jar依賴、spring-ioc容器相關(guān)的jar
<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.bear.simple_spring</groupId>
<artifactId>simple_spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- 導(dǎo)入springmvc jar包 begin -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.2.RELEASE</version>
</dependency>
<!-- 導(dǎo)入springmvc json與對(duì)象轉(zhuǎn)換jar【@RequestBody、@ResponseBody ...注解生效】-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>classmate</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" 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">
<!-- 配置servlet 容器加載 spring-mvc配置文件,使servlet容器啟動(dòng)的時(shí)候同時(shí)啟動(dòng)spring-mvc容器 -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 配置spring-mvc路徑 -->
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<!-- 配置 spring-mvc攔截的請(qǐng)求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置servlet 容器加載 spring-ioc配置文件,使servlet容器啟動(dòng)的時(shí)候同時(shí)啟動(dòng)spring-ioc容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-beans.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
創(chuàng)建spring-mvc的配置文件
<?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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 配置spring 掃描包 -->
<context:component-scan base-package="com.bear.simple.spring" use-default-filters="false">
<!-- 配置 spring-mvc 只掃描的注解Controller【處理http請(qǐng)求注解】、 ControllerAdvice【處理異常的注解】-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
<!-- 配置spring jsp 的試圖解析器 【如不需要用到模板,可不配置】-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置支持靜態(tài)文件訪問(wèn) -->
<mvc:default-servlet-handler/>
<!-- 配置注解驅(qū)動(dòng),讓RequestMapping 、異常處理等注解生效 -->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
<?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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 配置spring-ioc容器掃描的包,并排除 掃描Controller、ControllerAdvice【這兩個(gè)注解交由spring-mvc容器掃描】-->
<context:component-scan base-package="com.bear.simple.spring">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
</beans>
編寫(xiě)controller
package com.bear.simple.spring.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.bear.simple.spring.entity.Account;
import com.bear.simple.spring.service.AccountService;
@RestController
@RequestMapping("account")
public class AccountController {
@Autowired
private AccountService accountService;
/**
* 獲取帳號(hào)信息
* @param id
* @param request
* @return
*/
@RequestMapping("/get")
public Account getAccount(@RequestParam String id,HttpServletRequest request) {
if(null == id || "".equals(id))
throw new RuntimeException("請(qǐng)求參數(shù)缺少id");
Account result = accountService.loadAccountById(id);
return result;
}
}
編寫(xiě)實(shí)體層
package com.bear.simple.spring.entity;
/**
* 登陸帳號(hào)信息
* @author bear
*
*
public class Account {
//登陸帳號(hào)ID
private String id;
//登陸帳號(hào)
private String acccountNo;
//帳號(hào)密碼
private String password;
//帳號(hào)描述
private String desc;
//帳號(hào)是否啟用 0 禁用 1啟用,默認(rèn)為啟用
private int enable = 1;
public Account(String id, String acccountNo, String password) {
super();
this.id = id;
this.acccountNo = acccountNo;
this.password = password;
}
public Account(String id, String acccountNo, String password, String desc, int enable) {
super();
this.id = id;
this.acccountNo = acccountNo;
this.password = password;
this.desc = desc;
this.enable = enable;
}
public Account() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAcccountNo() {
return acccountNo;
}
public void setAcccountNo(String acccountNo) {
this.acccountNo = acccountNo;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getEnable() {
return enable;
}
public void setEnable(int enable) {
this.enable = enable;
}
public Boolean isEnable() {
return 1 == this.enable;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((acccountNo == null) ? 0 : acccountNo.hashCode());
result = prime * result + ((desc == null) ? 0 : desc.hashCode());
result = prime * result + enable;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((password == null) ? 0 : password.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;
Account other = (Account) obj;
if (acccountNo == null) {
if (other.acccountNo != null)
return false;
} else if (!acccountNo.equals(other.acccountNo))
return false;
if (desc == null) {
if (other.desc != null)
return false;
} else if (!desc.equals(other.desc))
return false;
if (enable != other.enable)
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
return true;
}
@Override
public String toString() {
return "Account [id=" + id + ", acccountNo=" + acccountNo + ", password=" + password + ", desc=" + desc
+ ", enable=" + enable + "]";
}
}
編寫(xiě)服務(wù)層
package com.bear.simple.spring.service;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.bear.simple.spring.entity.Account;
@Service
public class AccountService {
private static final Map<String, Account> cache = new HashMap<String, Account>();
static {
cache.put("1", new Account("1", "黃大仙", "123456"));
cache.put("2", new Account("2", "劉不三", "12345678"));
cache.put("3", new Account("3", "劉不四", "8888888"));
}
/**
* 加載帳號(hào),不存在報(bào)異常
*
* @param id
* @return
*/
public Account loadAccountById(String id) {
Optional<Account> accountOpt = findAccountById(id);
if (!accountOpt.isPresent())
throw new RuntimeException(String.format("帳號(hào)【%s】不存在", id));
return accountOpt.get();
}
/**
* 查找?guī)ぬ?hào)
*
* @param id
* @return
*/
public Optional<Account> findAccountById(String id) {
if (null == id || "".equals(id))
return Optional.empty();
Account account = cache.get(id);
return Optional.ofNullable(account);
}
}
測(cè)試請(qǐng)求處理
使用postman軟件測(cè)試
編寫(xiě)返回結(jié)果實(shí)體類【該類包含成功返回,異常返回與錯(cuò)誤返回】
package com.bear.simple.spring.entity;
import java.io.PrintWriter;
import java.io.StringWriter;
public class JsonData {
//是否正確返回
private final boolean ret;
//狀態(tài)碼
private String code = "000";
//數(shù)據(jù)
private Object data;
//提示信息
private String msg;
//異常詳細(xì)信息
private String detail;
private JsonData(boolean ret) {
this.ret = ret;
}
/**
* 創(chuàng)建錯(cuò)誤返回結(jié)果
* @param msg 提示信息
* @return
*/
public static JsonData error(String msg) {
JsonData result = new JsonData(false);
result.msg = msg;
result.code = "999";
return result;
}
public static JsonData error(String msg,Exception e,String code) {
JsonData result = new JsonData(false);
result.msg = msg;
result.code = code;
result.detail = getStackTraceInfo(e);
return result;
}
public static JsonData error(Exception e) {
JsonData result = new JsonData(false);
result.msg = e.getMessage();
result.code = "999";
result.detail = getStackTraceInfo(e);
return result;
}
public static JsonData error(Exception e,String code) {
JsonData result = new JsonData(false);
result.msg = e.getMessage();
result.code = code;
result.detail = getStackTraceInfo(e);
return result;
}
public static JsonData success(Object data,String msg) {
JsonData result = new JsonData(true);
result.msg = msg;
result.data = data;
return result;
}
public static JsonData success(Object data) {
return success(data, null);
}
public static JsonData success() {
return success(null,null);
}
public String getCode() {
return code;
}
public Object getData() {
return data;
}
public String getMsg() {
return msg;
}
public String getDetail() {
return detail;
}
public boolean isRet() {
return ret;
}
/**
* 打印異常堆棧信息
* @param e
* @return
*/
public static String getStackTraceInfo(Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
e.printStackTrace(pw);
pw.flush();
sw.flush();
return sw.toString();
} finally {
try {
pw.close();
} catch (Exception ex) {
ex.printStackTrace();
}
try {
sw.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
統(tǒng)一異常處理
編寫(xiě)異常處理控制器(統(tǒng)一處理系統(tǒng)發(fā)生的所有異常)
package com.bear.simple.spring.controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bear.simple.spring.entity.JsonData;
@ControllerAdvice
public class ExceptionController {
/**
* 處理特定異常
* @param ex
* @return
*/
@ExceptionHandler
@ResponseBody
public JsonData handleUserNotExistException(UserNotExistException ex) {
if(null == ex.getMessage() || "".equals(ex.getMessage()))
return JsonData.error("用戶不存在", ex, "998");
return JsonData.error(ex, "998");
}
/**
* 處理上述遺漏的異常
* @param ex
* @return
*/
@ExceptionHandler
@ResponseBody
public JsonData handleUserNotExistException(Exception ex) {
if(null == ex.getMessage() || "".equals(ex.getMessage()))
return JsonData.error("系統(tǒng)發(fā)生未知異常", ex, "999");
return JsonData.error(ex, "999");
}
}
添加日志處理
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
編寫(xiě)日志配置文件【logback.xml(名稱可自定義)】
<?xml version="1.0" encoding="UTF-8"?>
<!-- scan 為 true 掃描logback.xml文件,一旦發(fā)現(xiàn)文件更新,則重新加載,scanPeriod 為掃描時(shí)間間隔 -->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!-- 變量定義 在logback.xml文件中使用${}應(yīng)用 -->
<property name="appName" value="simpleSpringLog" />
<!-- 定義日志輸出路徑 -->
<property name="logFilePath" value="C:/sts_workspace/log" />
<!-- logback上下文名稱定義 -->
<contextName>${appName}</contextName>
<!-- 控制臺(tái)日志輸出配置 -->
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<!-- encoder 默認(rèn)配置為PatternLayoutEncoder -->
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<!-- 文件日志輸出配置 -->
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>${logFilePath}/testFile.log</file>
<append>true</append>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<!-- 滾動(dòng)日志輸出,每天生成一個(gè)日志文件 -->
<appender name="ROLL_FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 配置滾動(dòng)策略 -->
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logFilePath}/%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<!-- 配置日志輸出格式 -->
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<appender name="TIMEOUT_ROLL_FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 定義日志過(guò)濾器 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<!-- 配置滾動(dòng)策略 -->
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logFilePath}/timeout/%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<!-- 配置日志輸出格式 -->
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<!-- 定義指定類路徑輸出日志 -->
<logger name="com.bear.simple.spring.service" level="INFO"
additivity="false">
<appender-ref ref="STDOUT" />
<appender-ref ref="ROLL_FILE" />
</logger>
<logger name="org" level="INFO"/>
<!-- 設(shè)置root的打印配置,將等級(jí)【level="INFO"】大于INFO的日志打印到控制臺(tái)【ref="STDOUT"】 -->
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="ROLL_FILE" />
</root>
</configuration>
使用springmvc啟動(dòng)加載日志配置文件,編輯web.xml文件使用配置監(jiān)聽(tīng)器加載日志配置文件,只需在web.xml文件中添加如下代碼段即可
<context-param>
<param-name>logbackConfigLocation</param-name>
<!-- 日志配置文件地址 -->
<param-value>C:/developer/apache-tomcat-8.0.32/web_log/logback.xml</param-value>
</context-param>
<listener>
<listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class>
</listener>
配置統(tǒng)一編碼過(guò)濾器
配置springmvc接收的所有請(qǐng)求的編碼格式為utf-8,只需在web.xml文件中添加字符集過(guò)濾器即可,添加的內(nèi)容如下
<!-- 統(tǒng)一字符編碼過(guò)濾器 -->
<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>
<!-- 是否強(qiáng)制所有請(qǐng)求都使用該字符編碼 -->
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
?
網(wǎng)頁(yè)標(biāo)題:創(chuàng)建spring項(xiàng)目步驟一
鏈接分享:http://jinyejixie.com/article38/ppjopp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作、品牌網(wǎng)站制作、網(wǎng)站內(nèi)鏈、自適應(yīng)網(wǎng)站、品牌網(wǎng)站設(shè)計(jì)、網(wǎng)站排名
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)