Spring 4 mvc restful 系列之一

第一篇基本搬运自:

http://websystique.com/springmvc/spring-mvc-4-restful-web-services-crud-example-resttemplate/

首先创建一个maven工程并转换为web module 3.0版本。

一、基础环境

1、创建Maven  web工程

new-->New Maven Project,选择maven webapp,信息填写完整。

2、修改jdk版本,转为web module 3.0(非必须)

在pom.xml的build-plugins里添加编译环境

删除原有的web.xml,因为web.xml不是3.0的格式。同时设置打包位置及打包war名称。在pom.xml里配置:

设置完成后,update项目:maven--》update-project。

update后,转换web module版本。定位到项目的Maven -Project Facets 里,先去掉 Dynamic Web Module 2.5前的选择,点击Apply,确认。然后再次打开勾选3.0,勾选上,再应用apply即可。项目至此已转为web module 3.0了。 

到这一步,可以运行看看是否成功~如看到hello ,world即成功了。

 

二、集成spring MVC

1、在pom.xml里添加spring 依赖及json转换器包依赖如下。这里采用spring 4.2和2.5.3的jackson

2、在src/main/java里建立model,controller,service 等包,结构大概如下

    

现在创建一个student类、对应的service及实现和controller

A:student类

package com.blue.datacenter.model;

public class Student {
    
    private long id;
    private String name;
    private int age;
    private String describ;
    
    public Student(){
        id=0;
    }
    
    public Student(long id,String name,int age,String describ){
        this.id=id;
        this.name=name;
        this.age=age;
        this.describ=describ;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getDescrib() {
        return describ;
    }

    public void setDescrib(String describ) {
        this.describ = describ;
    }
    
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", age=" + age + ", describ=" + describ + "]";
    }
}
View Code

B:service

package com.blue.datacenter.service;

import java.util.List;

import com.blue.datacenter.model.Student;

public interface StudentService {
    Student findById(long id);
    Student findByName(String name);
    void saveStudent(Student student);
    void updateStudent(Student student);
    void deleteStudentById(long id);
    List<Student> findAllStudents();
    void deleteAllStudents();
    public boolean isStudentExist(Student student);
}
View Code

C:实现,这里没有用到数据,所以采用静态生成数据。

package com.blue.datacenter.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.blue.datacenter.model.Student;
import com.blue.datacenter.service.StudentService;

@Service
@Transactional 
public class StudentServiceImpl implements StudentService {
    
    private static final AtomicLong counter = new AtomicLong();
    
    private static List<Student> students;
    static{
        students= populateDummyStudents();
    }

    private static List<Student> populateDummyStudents(){
        List<Student> users = new ArrayList<Student>();
        users.add(new Student(counter.incrementAndGet(),"张三",3, "1st students..."));
        users.add(new Student(counter.incrementAndGet(),"李四",4, "2st students..."));
        users.add(new Student(counter.incrementAndGet(),"王五",5, "3st students..."));
        users.add(new Student(counter.incrementAndGet(),"李飞刀",7, "4st students..."));
        return users;
    }
    
    @Override
    public Student findById(long id) {
        for(Student stu : students){
            if(stu.getId() == id){
                return stu;
            }
        }
        return null;
    }

    @Override
    public Student findByName(String name) {
        for(Student stu : students){
            if(stu.getName().equals(name)){
                return stu;
            }
        }
        return null;
    }

    @Override
    public void saveStudent(Student student) {
        student.setId(counter.incrementAndGet());
        students.add(student);
    }

    @Override
    public void updateStudent(Student student) {
        int index = students.indexOf(student);
        students.set(index, student);
    }

    @Override
    public void deleteStudentById(long id) {
        for (Iterator<Student> iterator = students.iterator(); iterator.hasNext(); ) {
            Student stu = iterator.next();
            if (stu.getId() == id) {
                iterator.remove();
            }
        }
    }

    @Override
    public List<Student> findAllStudents() {
        return students;
    }

    @Override
    public void deleteAllStudents() {
        students.clear();
    }

    @Override
    public boolean isStudentExist(Student student) {
        return findByName(student.getName())!=null;
    }

}
View Code

D:controller,可以说是action?

package com.blue.datacenter.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
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.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.blue.datacenter.model.Student;
import com.blue.datacenter.service.StudentService;

@RestController
public class StudentController {
    
    @Autowired
    private StudentService studentService;
    //-------------------Retrieve All Students--------------------------------------------------------
    @RequestMapping(value = "/Student", method = RequestMethod.GET)
    public ResponseEntity<List<Student>> listAllStudents() {
        List<Student> Students = studentService.findAllStudents();
        if(Students.isEmpty()){
            return new ResponseEntity<List<Student>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
        }
        return new ResponseEntity<List<Student>>(Students, HttpStatus.OK);
    }


    //-------------------Retrieve Single Student--------------------------------------------------------
    
    @RequestMapping(value = "/Student/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Student> getStudent(@PathVariable("id") long id) {
        System.out.println("Fetching Student with id " + id);
        Student Student = studentService.findById(id);
        if (Student == null) {
            System.out.println("Student with id " + id + " not found");
            return new ResponseEntity<Student>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<Student>(Student, HttpStatus.OK);
    }

    
    
    //-------------------Create a Student--------------------------------------------------------
    
    @RequestMapping(value = "/Student/", method = RequestMethod.POST)
    public ResponseEntity<Void> createStudent(@RequestBody Student Student,     UriComponentsBuilder ucBuilder) {
        System.out.println("Creating Student " + Student.getName());

        if (studentService.isStudentExist(Student)) {
            System.out.println("A Student with name " + Student.getName() + " already exist");
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
        }

        studentService.saveStudent(Student);

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/Student/{id}").buildAndExpand(Student.getId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }

    
    //------------------- Update a Student --------------------------------------------------------
    
    @RequestMapping(value = "/Student/{id}", method = RequestMethod.PUT)
    public ResponseEntity<Student> updateStudent(@PathVariable("id") long id, @RequestBody Student Student) {
        System.out.println("Updating Student " + id);
        
        Student currentStudent = studentService.findById(id);
        
        if (currentStudent==null) {
            System.out.println("Student with id " + id + " not found");
            return new ResponseEntity<Student>(HttpStatus.NOT_FOUND);
        }

        currentStudent.setName(Student.getName());
        currentStudent.setAge(Student.getAge());
        currentStudent.setDescrib(Student.getDescrib());
        
        studentService.updateStudent(currentStudent);
        return new ResponseEntity<Student>(currentStudent, HttpStatus.OK);
    }

    //------------------- Delete a Student --------------------------------------------------------
    
    @RequestMapping(value = "/Student/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Student> deleteStudent(@PathVariable("id") long id) {
        System.out.println("Fetching & Deleting Student with id " + id);

        Student Student = studentService.findById(id);
        if (Student == null) {
            System.out.println("Unable to delete. Student with id " + id + " not found");
            return new ResponseEntity<Student>(HttpStatus.NOT_FOUND);
        }

        studentService.deleteStudentById(id);
        return new ResponseEntity<Student>(HttpStatus.NO_CONTENT);
    }

    
    //------------------- Delete All Student --------------------------------------------------------
    
    @RequestMapping(value = "/Student/", method = RequestMethod.DELETE)
    public ResponseEntity<Student> deleteAllStudents() {
        System.out.println("Deleting All Students");

        studentService.deleteAllStudents();
        return new ResponseEntity<Student>(HttpStatus.NO_CONTENT);
    }
        
}
View Code

这些代码原理都可以在开篇的链接中查看。

3、建立spring-mvc.xml和web.xml(从其他3.0的项目拷贝web.xml格式)

 在src/main/java里新建一个包,名字为config(随意)。在包下新建spring-mvc.xml和web.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:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">


    <!-- 注解扫描包 -->
    <context:component-scan base-package="com.blue.datacenter" />
    <!-- 开启注解 -->
    <mvc:annotation-driven />

    <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 将外部请求地址映射为内部实际物理地址 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
</beans>
View Code

web.xml 3.0版本

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  
  <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*:config/spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>
  <filter>
    <filter-name>encodingFilter</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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
View Code

至此,spring和web配置完成。

三、运行

经过第一、二步,已经完成了spring mvc restful的的最基本、最简单的配置,下面可以尝试运行了。右键项目-run as --》run on server,如果没有此项,请在build path里添加 server runtime,选择tomcat 7.0

加载时,可以在输出console窗口里查看到加载了controller的路径了。

接着,在浏览器里输入地址,可以查看到结果。

简单的restful 搭建就到这里,下一章会在此基础上集成mybatis持久层的应用,包括了数据库连接池。

 

转载于:https://www.cnblogs.com/x-a-z/p/5796196.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值