maven项目spring-mvc创建web后端返回json格式数据项目创建全流程

简介java web项目,通过spring-mvc实现文章相关操作。包括: 文章增、改、查、删。返回json类型数据。 maven创建一个简单的web项目【l-1515】 pom.xml添加依赖 src/main/resources 目录下创建spring-mvc.xml文件 修改src/main/webapp/WEB-INF目录下web.xml文件 建立src/main下src/main/java目录

java web项目,通过spring-mvc实现文章相关操作。包括:
文章增、改、查、删。返回json类型数据。


  1. maven创建一个简单的web项目【l-1515
  2. pom.xml添加依赖
  3. src/main/resources 目录下创建spring-mvc.xml文件
  4. 修改src/main/webapp/WEB-INF目录下web.xml文件
  5. 建立src/main下src/main/java目录,并创建包


需要创建的项目文件:


controller

PassageController.java

service

PassageService.java

PassageServiceImpl.java

dao

PassageDao.java

pojo

Passage.java


github上有实现的源码:https://github.com/comonly/javaweb_blog/tree/master/blog_spring_backend

新加评论 评论标题:

文章评论

    pom.xml文件

        2019-10-24    
    修改 删除
    <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>chencheng.vip</groupId>
      <artifactId>blog_spring_backend</artifactId>
      <packaging>war</packaging>
      <version>0.0.1-SNAPSHOT</version>
      <name>blog_spring_backend Maven Webapp</name>
      <url>http://maven.apache.org</url>
      
      <properties>
        <!-- Spring版本号 -->
        <spring.version>4.3.8.RELEASE</spring.version>
      </properties>
      <dependencies>
        <!-- Spring相关包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</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相关包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
           
        <!-- 将返回的对象解析成json格式 -->      
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>2.5.4</version>
        </dependency>
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.5.4</version>
        </dependency>
    	 <dependency>
    	    <groupId>com.fasterxml.jackson.core</groupId>
    	    <artifactId>jackson-annotations</artifactId>
    	    <version>2.5.4</version>
    	</dependency>
    	
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
      </dependencies>
      <build>
        <finalName>blog_spring_backend</finalName>
      </build>
    </project>
    

    spring-mvc.xml

        2019-10-24    
    修改 删除
    <?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <!-- 启动自动扫描 -->
        <context:component-scan base-package="cn.comonly.*" />
    
        <!-- 注册MVC注解驱动 -->
        <mvc:annotation-driven />
     	
    
        <!-- 静态资源可访问的设置方式 -->
        <mvc:default-servlet-handler />
    
        <!-- 配置视图解析器,可以显式设置,也可以不设置,不设置会依据SpringMVC的默认设置 -->
        <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/" />
            <property name="suffix" value=".jsp" />
        </bean>
    </beans>

    web.xml

        2019-10-24    
    修改 删除
    <?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" id="WebApp_ID" version="2.5">
    
        <!-- 指定Spring配置文件位置 -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-*.xml</param-value>
        </context-param>
    
        <!-- 注册ServletContext监听器 -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        
    
        <!-- 注册字符集过滤器 -->
        <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>
        
        <!-- 解决跨域 -->
        <filter>
    	       <filter-name>CorsFilter</filter-name>
    	       <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    	       <init-param>
    	            <param-name>cors.allowed.origins</param-name>
    	            <param-value>
    	                http://localhost:8080,
    	                http://localhost:8081
    	            </param-value>
    	        </init-param>
    	        <init-param>
    	            <param-name>cors.allowed.methods</param-name>
    	            <param-value>
    	                GET,POST,HEAD,OPTIONS,PUT
    	            </param-value>
    	        </init-param>
    	        <init-param>
    	            <param-name>cors.allowed.headers</param-name>
    	            <param-value>
    	                Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Access-Control-Allow-Origin
    	            </param-value>
    	        </init-param>
    	</filter>    
    
    	<filter-mapping>
    	       <filter-name>CorsFilter</filter-name>
    	       <url-pattern>/*</url-pattern>
    	</filter-mapping>
    
        <!-- 注册前端控制器 -->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:spring-mvc.xml</param-value>
            </init-param>
        </servlet>
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
    </web-app>

    PassageController.java

        2019-10-24    
    修改 删除
    package cn.comonly.controller;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import cn.comonly.pojo.Passage;
    import cn.comonly.service.PassageService;
    
    @Controller
    @RequestMapping(value = "/passage")
    public class PassageController {
    	
    	@Autowired 
    	private PassageService passageService;
    	
    	//获取文章列表
    	@RequestMapping(value = "/passIndex", method = RequestMethod.GET)
        public @ResponseBody List<Passage> passIndex() {
        	return passageService.passIndex();
        }
    	
    	//获取单个文章
    	@RequestMapping(value = "/passDetail", method = RequestMethod.GET)
        public @ResponseBody Passage passDetail(int id) {
        	return passageService.passDetail(id);
        }
    
    	//提交单个文章修改
    	@RequestMapping(value = "/passChangeSubmit", method = RequestMethod.POST)
        public @ResponseBody int passChangeSubmit(@RequestBody Passage passage) {
        	return passageService.passChangeSubmit(passage);
        }
    
    	//添加单个文章
    	@RequestMapping(value = "/passAddSubmit", method = RequestMethod.POST)
        public @ResponseBody int passAddSubmit(@RequestBody Passage passage) {
        	return passageService.passAddSubmit(passage);
        }
    	
    	//添加单个文章
    	@RequestMapping(value = "/passDelete", method = RequestMethod.GET)
        public @ResponseBody int passAddSubmit(int id) {
        	return passageService.passDelete(id);
        }
    	
    	//@RequestMapping(value = "/passChange", method = RequestMethod.GET)
    	//直接获取passDetail即可
    
    	//@RequestMapping(value = "/passAdd", method = RequestMethod.GET)
    	//获取分类列表即可
    
    }
    

    PassageService.java

        2019-10-24    
    修改 删除
    package cn.comonly.service;
    
    import java.util.List;
    
    import cn.comonly.pojo.Passage;
    
    public interface PassageService {
    
    	List<Passage> passIndex();
    
    	Passage passDetail(int id);
    
    	int passChangeSubmit(Passage passage);
    
    	int passAddSubmit(Passage passage);
    
    	int passDelete(int id);
    
    }
    

    PassageServiceImpl.java

        2019-10-24    
    修改 删除
    package cn.comonly.service;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import cn.comonly.dao.PassageDao;
    import cn.comonly.pojo.Passage;
    
    @Service
    public class PassageServiceImpl implements PassageService {
    
    	@Autowired 
    	private PassageDao passageDao;
    	
    	public List<Passage> passIndex() {
    		return passageDao.getPassageList("select * from pass_passage");
    	}
    
    	public Passage passDetail(int id) {
    		return passageDao.getPassageById(id);
    	}
    
    	public int passChangeSubmit(Passage passage) {
    
    		passageDao.changePassage(passage.getPnumber(), passage.getPtitle(), passage.getPimage(), passage.getPlabel(), passage.getPcount(), 
    				passage.getPcoming(), passage.getPcomingUrl(), passage.getPkind(), passage.getPbelong());
    		return 0;
    	}
    
    	public int passAddSubmit(Passage passage) {
    		passageDao.addPassage(passage.getPtitle(), passage.getPimage(), passage.getPlabel(), passage.getPcount(), passage.getPcoming(), 
    				passage.getPcomingUrl(), passage.getPkind(), passage.getPbelong());
    		return 0;
    	}
    
    	public int passDelete(int id) {
    		passageDao.deletePassage(id);
    		return 0;
    	}
    
    }

    PassageDao.java

        2019-10-24    
    修改 删除
    package cn.comonly.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.sql.Timestamp;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.springframework.stereotype.Component;
    
    import cn.comonly.connectionDatabase.DBUtilConnection;
    import cn.comonly.pojo.Passage;
    
    @Component
    public class PassageDao {
    	private Connection conn=null;
    	private Statement stmt=null;
    	private PreparedStatement pstmt=null;
    	private ResultSet rs=null;
    
    
    	public List<Passage> getPassageList(String sql){
    		List<Passage> pass_passageInfoList=new ArrayList<Passage>();
    		try {
    			
    			conn=DBUtilConnection.getConnectionImportData();
    			stmt = conn.createStatement();
    			rs = stmt.executeQuery(sql);
    			while (rs.next()){
    				Passage pass_passageInfo=new Passage();
    				pass_passageInfo.setPnumber(rs.getInt(1));
    				pass_passageInfo.setPtitle(rs.getString(2));
    				pass_passageInfo.setPtime(rs.getDate(3));
    				pass_passageInfo.setPlabel(rs.getString(4));
    				pass_passageInfo.setPcount(rs.getString(5));
    				pass_passageInfo.setPcoming(rs.getString(6));
    				pass_passageInfo.setPcomingUrl(rs.getString(7));
    				pass_passageInfo.setPimage(rs.getString(8));
    				pass_passageInfo.setPkind(rs.getInt(9));
    				pass_passageInfo.setPbelong(rs.getInt(10));
    				pass_passageInfo.setPdescribe(rs.getString(11));
    
    				pass_passageInfoList.add(pass_passageInfo);
    			}
    		} catch (Exception e) {
    			System.out.println(e);
    			return null;
    		}finally{
    			DBUtilConnection.closeAll(rs, stmt, null, conn);
    		}
    		
    		return pass_passageInfoList;
    	}
    
    	/*通过id获得一个文章信息*/
    	public Passage getPassageById(int pnumber) {
    		String sql="select * from pass_passage where Pnumber="+pnumber;
    		conn=DBUtilConnection.getConnectionImportData();
    		Passage pass_passageInfo=new Passage();
    		try {
    			stmt = conn.createStatement();
    			rs = stmt.executeQuery(sql);
    			rs.next();
    			pass_passageInfo.setPnumber(rs.getInt(1));
    			pass_passageInfo.setPtitle(rs.getString(2));
    			pass_passageInfo.setPtime(rs.getDate(3));
    			pass_passageInfo.setPlabel(rs.getString(4));
    			pass_passageInfo.setPcount(rs.getString(5));
    			pass_passageInfo.setPcoming(rs.getString(6));
    			pass_passageInfo.setPcomingUrl(rs.getString(7));
    			pass_passageInfo.setPimage(rs.getString(8));
    			pass_passageInfo.setPkind(rs.getInt(9));
    			pass_passageInfo.setPbelong(rs.getInt(10));
    			pass_passageInfo.setPdescribe(rs.getString(11));
    
    			
    		} catch (Exception e) {
    			System.out.println(e);
    			return null;
    		}finally{
    			DBUtilConnection.closeAll(rs, stmt, null, conn);
    		}
    		return pass_passageInfo;
    	}
    
    	/*修改文章信息*/
    	public void changePassage(int number, String title, String image,
    			String keyword, String content, String coming, String comingUrl,
    			int pass_passageKind,int pbelong) {
    		conn=DBUtilConnection.getConnectionImportData();
    		String sql="update pass_passage set Ptitle=?,Plabel=?,Pcount=?,Pcoming=?,PcomingUrl=?,Pimage=?,Pkind=?,Pbelong=?,Pdescribe=? where Pnumber=?";
    		try {
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, title);
    			pstmt.setString(2, keyword);
    			pstmt.setString(3, content);
    			pstmt.setString(4, coming);
    			pstmt.setString(5, comingUrl);
    			pstmt.setString(6, image);
    			pstmt.setInt(7, pass_passageKind);
    			pstmt.setInt(8, pbelong);
    			pstmt.setString(9, "");
    			pstmt.setInt(10,number);
    			pstmt.executeUpdate();
    			
    		} catch (Exception e) {System.out.println(e);
    		}finally{
    			DBUtilConnection.closeAll(null, null, pstmt, conn);
    		}
    	}
    
    	/*新增信息*/
    	public void addPassage(String title, String image, String keyword,
    			String content, String coming, String comingUrl, int pass_passageKind,int passageBelong) {
    		conn=DBUtilConnection.getConnectionImportData();
    		Timestamp ctime = new java.sql.Timestamp(new java.util.Date().getTime());
    		
    		String sql="insert into pass_passage(Ptitle,Plabel,Pcount,Pcoming,PcomingUrl,Pimage,Pkind,Ptime,Pbelong,Pdescribe) values(?,?,?,?,?,?,?,?,?,?)";
    		try {
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, title);
    			pstmt.setString(2, keyword);
    			pstmt.setString(3, content);
    			pstmt.setString(4, coming);
    			pstmt.setString(5, comingUrl);
    			pstmt.setString(6, image);
    			pstmt.setInt(7, pass_passageKind);
    			pstmt.setTimestamp(8, ctime);
    			pstmt.setInt(9, passageBelong);
    			pstmt.setString(10, "");
    			pstmt.executeUpdate();
    		} catch (Exception e) {
    			System.out.println(e);
    		}finally{
    			DBUtilConnection.closeAll(null, null, pstmt, conn);
    		}
    	}
    
    
    	public void deletePassage(int number) {
    		conn=DBUtilConnection.getConnectionImportData();
    		String sql="delete from pass_passage where Pnumber=?";
    		try {
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setInt(1,number);
    			pstmt.executeUpdate();
    			
    		} catch (Exception e) {System.out.println(e);
    		}finally{
    			DBUtilConnection.closeAll(null, null, pstmt, conn);
    		}
    	}
    
    }
    

    Passage.java

        2019-10-24    
    修改 删除
    package cn.comonly.pojo;
    
    import java.util.Date;
    
    public class Passage {
    	
    	int pnumber;
    	String ptitle;
    	Date ptime;
    	String plabel;
    	String pcount;
    	String pcoming;
    	String pcomingUrl;
    	String pimage;
    	int pkind;
    	int pbelong;
    	String pdescribe;
    	
    	public int getPnumber() {
    		return pnumber;
    	}
    	public void setPnumber(int pnumber) {
    		this.pnumber = pnumber;
    	}
    	public String getPtitle() {
    		return ptitle;
    	}
    	public void setPtitle(String ptitle) {
    		this.ptitle = ptitle;
    	}
    	public Date getPtime() {
    		return ptime;
    	}
    	public void setPtime(Date ptime) {
    		this.ptime = ptime;
    	}
    	public String getPlabel() {
    		return plabel;
    	}
    	public void setPlabel(String plabel) {
    		this.plabel = plabel;
    	}
    	public String getPcount() {
    		return pcount;
    	}
    	public void setPcount(String pcount) {
    		this.pcount = pcount;
    	}
    	public String getPcoming() {
    		return pcoming;
    	}
    	public void setPcoming(String pcoming) {
    		this.pcoming = pcoming;
    	}
    	public String getPcomingUrl() {
    		return pcomingUrl;
    	}
    	public void setPcomingUrl(String pcomingUrl) {
    		this.pcomingUrl = pcomingUrl;
    	}
    	public String getPimage() {
    		return pimage;
    	}
    	public void setPimage(String pimage) {
    		this.pimage = pimage;
    	}
    	public int getPkind() {
    		return pkind;
    	}
    	public void setPkind(int pkind) {
    		this.pkind = pkind;
    	}
    	public int getPbelong() {
    		return pbelong;
    	}
    	public void setPbelong(int pbelong) {
    		this.pbelong = pbelong;
    	}
    	public String getPdescribe() {
    		return pdescribe;
    	}
    	public void setPdescribe(String pdescribe) {
    		this.pdescribe = pdescribe;
    	}
    	
    }
    
评论列表
pom.xml文件
spring-mvc.xml
web.xml
PassageController.java
PassageService.java
PassageServiceImpl.java
PassageDao.java
Passage.java