RESTFul and SSM cases

1. RESTFul 2.1 what is RESTFul ...
2.1 what is RESTFul
2.2 use
3.1 general
3.2 introduction cases
3.3 multiple interceptors
4.1 requirements
4.2 environment construction
4.3 import configuration class
4.4 query all
4.5 add
1. RESTFul

2.1 what is RESTFul

  • RESTFul programming is a style, not a protocol.

  • Interpretation of HTTP protocol (landing scheme) and landing of request mode

    http There are 7 protocols in total, 4 common and 2 longest get post put delete
  • RESTFul specifies the operation of the server program.

    • Each operation consists of: request path + request mode. (one path can complete different operations due to different request modes)
    • Data transmission mode: JSON data
    // Traditional development path Query: http://localhost:8080/user/selectAll.action add to: http://localhost:8080/user/addUser.action Modification: http://localhost:8080/user/updateUser.action Delete: http://localhost:8080/user/deleteUser.action // RESTFul style path Query: get http://localhost:8080/user/ Details: get http://localhost:8080/user/123 add to: post http://localhost:8080/user/ Modification: put http://localhost:8080/user/ Delete: delete http://localhost:8080/user/123

2.2 use

2.2.1 steps

  • Step 1: create a new project (day15_mvc_restful)

  • Step 2: import jar packages: spring, spring mvc, jackson, mybatis

  • Step 3: configure the class,

    • spring mvc configuration
    • Start the configuration class. The front-end controller has no extension and is changed from *. action to/
  • Step 4: write controller to complete addition, deletion, modification and query

    • 4.1 class level:

      @Controller ,@ResponseBody //-->Synthetic injection @RestController
    • 4.2 method level: @ RequestMapping(value = "path", method=RequestMethod.GET /POST/PUT/DELETE)

      //Traditional writing @RequestMapping(value="route", method=RequestMethod.GET /POST/PUT/DELETE) //-->Simplified writing of various request modes @GetMapping @PostMapping @PutMapping @DeleteMapping @PathVariable //Used to obtain path parameters
    • 4.3 method return value

      //According to the constraints and based on the RESTFul style, it is recommended to use the ResponseEntity type for the return value of the method // ResponseEntity is used to encapsulate return value information, including status code // Return 200 status code, ResponseEntity.ok("added successfully"); // Other status codes, new responseentity < > ("added successfully", HttpStatus.UNAUTHORIZED)

2.2.2 realization

  • Configuration class

  • controller
package com.czxy.rest.controller; import com.czxy.rest.domain.User; import io.swagger.models.Response; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.Date; import java.util.List; @RestController @RequestMapping("/user") public class UserController { /** * Query all * @return */ //Equivalent @ RequestMapping(method = RequestMethod.GET) @GetMapping public ResponseEntity<List<User>> list() { List<User> list = new ArrayList<>(); list.add(new User(1,"jack","1234", new Date())); list.add(new User(2,"shredded meat","6666", new Date())); list.add(new User(3,"tom","loverose", new Date())); return ResponseEntity.ok(list); } /** * Add user * @param user * @return */ @PostMapping(produces = "application/json;charset=UTF-8") public ResponseEntity add(@RequestBody User user) { System.out.println(user); return ResponseEntity.ok("Added successfully"); } /** * * @param user * @return */ @PutMapping public ResponseEntity<String> update(@RequestBody User user) { System.out.println(user); return ResponseEntity.ok("update success"); } /** * delete * @param userId * @return */ @DeleteMapping("/") public ResponseEntity<String> delete(@PathVariable("id") String userId ) { System.out.println(userId); return ResponseEntity.ok("delete success"); } }
3. spring mvc interceptor

3.1 general

  • The spring mvc interceptor is equivalent to a java web filter
  • Intercept or process during processor execution

preHandler Interceptor pre-processing method, if returned true Continue if returned falseļ¼ŒIndicates being intercepted. postHandler Interceptor processing mode, controller When execution is complete, the processing method is executed. afterCompletion The completion method is triggered when the view rendering is completed.

3.2 introduction cases

  1. Environment: project, jar package, configuration class

  2. Test program: controller, jsp

  3. Write interceptors to verify the process

  4. Write configuration file

  5. Environment: project, jar package, configuration class

  1. Test program: controller, jsp

package com.czxy.inter.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/user") public class UserController { @RequestMapping("/selectAll") public String selectAll() { System.out.println("2 controller-->selectAll"); return "list"; } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> Query results <% System.out.println("4 jsp output"); %> </body> </html>
  1. Write interceptors to verify the process

    package com.czxy.inter.interceptor; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("1 Before interception"); //Release return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("3 In execution"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("5 Final completion"); } }
  2. Write the configuration file and spring mvc configuration class. You need to implement the WebMvcConfigurer interface and re addInterceptors method

    package com.czxy.inter.config; import com.czxy.inter.interceptor.MyInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.view.InternalResourceViewResolver; import javax.annotation.Resource; import java.nio.charset.Charset; @Configuration //Configuration class @ComponentScan(basePackages = {"com.czxy.inter.controller","com.czxy.inter.interceptor"}) @EnableWebMvc public class SpringMVCConfig implements WebMvcConfigurer { @Resource private MyInterceptor myInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { InterceptorRegistration interceptorRegistration1 = registry.addInterceptor(myInterceptor); interceptorRegistration1.addPathPatterns("/**"); } /** * view resolver * @return */ @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); // prefix viewResolver.setPrefix("/WEB-INF/pages/"); // suffix viewResolver.setSuffix(".jsp"); return viewResolver; } }

3.3 multiple interceptors

  • Execution process

  • The order of multi interceptor interception is the order configured in the configuration class.
4. SSM integration: case

4.1 requirements

  • User's addition, deletion, modification and query
    • SSM: spring mvc ,spring,mybatis
    • view: jsp (non key)

4.2 environment construction

  • Project Name: day15_ssm_ums

  • Database: existing data

    # Create database CREATE DATABASE ssm_db2; # Use database USE ssm_db2; # 1.1 create user table CREATE TABLE `user` ( `uid` VARCHAR(32) NOT NULL, `username` VARCHAR(20) DEFAULT NULL, #user name `password` VARCHAR(32) DEFAULT NULL, #password `name` VARCHAR(20) DEFAULT NULL, #nickname `email` VARCHAR(30) DEFAULT NULL, #E-mail `telephone` VARCHAR(20) DEFAULT NULL, #Telephone `birthday` DATE DEFAULT NULL, #birthday `sex` VARCHAR(10) DEFAULT NULL, #Gender `state` INT(11) DEFAULT 0, #Status: 0 = inactive, 1 = activated `code` VARCHAR(64) DEFAULT NULL, #Activation code PRIMARY KEY (`uid`) ) ; # 1.2 initialize user default data INSERT INTO `user` VALUES ('u001','jack','1234','jack','[email protected]','13612345678','2015-11-04','male',0,NULL); INSERT INTO `user` VALUES ('u002','rose','1234','shredded meat','[email protected]','13612345679','2015-11-05','female',0,NULL); INSERT INTO `user` VALUES ('373eb242933b4f5ca3bd43503c34668b','ccc','ccc','aaa','[email protected]','15723689921','2015-11-04','male',0,'9782f3e837ff422b9aee8b6381ccf927bdd9d2ced10d48f4ba4b9f187edf7738'),('3ca76a75e4f64db2bacd0974acc7c897','bb','bb','Zhang San','[email protected]','15723689921','1990-02-01','male',0,'1258e96181a9457987928954825189000bae305094a042d6bd9d2d35674684e6'),('62145f6e66ea4f5cbe7b6f6b954917d3','cc','cc','Zhang San','[email protected]','15723689921','2015-11-03','male',0,'19f100aa81184c03951c4b840a725b6a98097aa1106a4a38ba1c29f1a496c231'),('c95b15a864334adab3d5bb6604c6e1fc','bbb','bbb','Lao Wang','[email protected]','15712344823','2000-02-01','male',0,'71a3a933353347a4bcacff699e6baa9c950a02f6b84e4f6fb8404ca06febfd6f'),('f55b7d3a352a4f0782c910b2c70f1ea4','aaa','aaa','Xiao Wang','[email protected]','15712344823','2000-02-01','male',1,NULL);
  • Import jar package

    • spring,spring mvc
    • Integration of mybatis and spring
    • druid connection pool
    • jsp jstl (Standard Tag Library)

4.3 import configuration class

  • Create corresponding directory structure

4.3.1 MyBatis configuration class

package com.czxy.ssm.config; import com.github.pagehelper.PageHelper; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.context.annotation.Bean; import tk.mybatis.spring.mapper.MapperScannerConfigurer; import javax.sql.DataSource; import java.util.Properties; public class MyBatisConfiguration { /** * Configure session factory * @param dataSource * @return * @throws Exception */ @Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception{ //1 create factoryBean SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); //2 setting data // 2.1 data source factoryBean.setDataSource(dataSource); // 2.2 hump naming Configuration configuration = new Configuration(); configuration.setMapUnderscoreToCamelCase(true); factoryBean.setConfiguration(configuration); // 2.3 paging plug-in Properties props = new Properties(); // Set dialect props.setProperty("dialect", "mysql"); // count query while paging props.setProperty("rowBoundsWithCount", "true"); // Paging rationalization parameters: when pagenum < = 0, the first page will be queried, and when pagenum > pages (exceeds the total), the last page will be queried props.setProperty("reasonable", "true"); // PageInterceptor pageInterceptor = new PageInterceptor(); // pageInterceptor.setProperties(props); PageHelper pageHelper = new PageHelper(); pageHelper.setProperties(props); factoryBean.setPlugins(new Interceptor[] ); //3. Obtain the corresponding information through factorybean return factoryBean.getObject(); } /** * Mapping scanner * @return */ @Bean public MapperScannerConfigurer mapperScannerConfigurer(){ //1 create MapperScannerConfigurer mapperScanner = new MapperScannerConfigurer(); //2 setting package mapperScanner.setBasePackage("com.czxy.ssm.mapper"); return mapperScanner; } }

4.3.2 Spring configuration class

  • Data source profile

    jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssm_db2 jdbc.username=root jdbc.password=1234
  • Configuration class

package com.czxy.ssm.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.PropertySource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; @ComponentScan(basePackages="com.czxy.ssm.service") @PropertySource("classpath:db.properties") @EnableTransactionManagement public class SpringConfiguration { /** * Get the contents in the properties file and inject the corresponding variables */ @Value("$") private String driver; @Value("$") private String url; @Value("$") private String username; @Value("$") private String password; /** * Configure data sources * @return */ @Bean public DataSource dataSource(){ DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(driver); druidDataSource.setUrl(url); druidDataSource.setUsername(username); druidDataSource.setPassword(password); return druidDataSource; } /** * Transaction manager * @param dataSource * @return */ @Bean public DataSourceTransactionManager txManager(DataSource dataSource){ return new DataSourceTransactionManager(dataSource); } }

4.3.3 Spring MVC configuration class

package com.czxy.ssm.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.WebMvcConfigurationSupport; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @ComponentScan(basePackages="com.czxy.ssm.controller") //public class MvcConfiguration extends WebMvcConfigurationSupport { public class MvcConfiguration implements WebMvcConfigurer { /** * view resolver * @return */ @Bean public InternalResourceViewResolver internalResourceViewResolver(){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); //Prefix jsp folder viewResolver.setPrefix("/WEB-INF/pages/"); //Suffix jsp extension viewResolver.setSuffix(".jsp"); return viewResolver; } }

4.3.4 startup configuration class

package com.czxy.ssm.config; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.DispatcherServlet; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; public class WebInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { //1 configure spring Factory AnnotationConfigWebApplicationContext application = new AnnotationConfigWebApplicationContext(); // Register all configuration classes application.register(MyBatisConfiguration.class); application.register(SpringConfiguration.class); application.register(MvcConfiguration.class); //2 post Chinese garbled code FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encoding", new CharacterEncodingFilter("UTF-8")); encodingFilter.addMappingForUrlPatterns(null, true, "/*"); //3 core controller ServletRegistration.Dynamic mvcServlet = servletContext.addServlet("springmvc", new DispatcherServlet(application)); //mvcServlet.addMapping("*.action"); mvcServlet.addMapping("/"); mvcServlet.setLoadOnStartup(2); //When tomcat starts, the initialization method of servlet is executed } }

4.4 query all

4.4.1 requirements

Complete all functions of query

4.4.2 steps

  • Step 1: write a JavaBean (User)
    • Provide field and table class correspondence
    • Add MyBatis related annotation @ Id, etc
  • Step 2: write Mapper (UserMapper)
    • Integrate common Mapper
  • Step 3: write a service
    • Need to manage transactions
  • Step 4: write controller
    • Processing request path
    • Select view page list
  • Step 5: the list.jsp page displays data (non key)

4.4.3 realization

  • Step 1: write a JavaBean (User)

    • Provide field and table class correspondence
    • Add MyBatis related annotation @ Id, etc
    @Entity(name="user") public class User { @Id private String uid; @Column(name="username") private String userName; private String password; private String name; private String email; private String telephone; private Date birthday; private String sex; private Integer state; private String code; // Omit getter s and setter s }
  • Step 2: write Mapper (UserMapper)

    • Integrate common Mapper
    package com.czxy.ssm.mapper; import com.czxy.ssm.domain.User; import tk.mybatis.mapper.common.Mapper; public interface UserMapper extends Mapper<User> { }
  • Step 3: write a service

    • Need to manage transactions
    package com.czxy.ssm.service; import com.czxy.ssm.domain.User; import java.util.List; public interface UserService { /** * Query all * @return */ public List<User> selectAll(); }
    package com.czxy.ssm.service.impl; import com.czxy.ssm.domain.User; import com.czxy.ssm.mapper.UserMapper; import com.czxy.ssm.service.UserService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List; @Service @Transactional public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; @Override public List<User> selectAll() { return userMapper.selectAll(); } }
  • Step 4: write controller

    • Processing request path
    • Select view page list
    package com.czxy.ssm.controller; import com.czxy.ssm.domain.User; import com.czxy.ssm.service.UserService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.annotation.Resource; import java.util.List; @Controller @RequestMapping("/user") public class UserController { @Resource private UserService userService; @RequestMapping("/selectAll") public String selectAll(Model model) { // Query all List<User> list = userService.selectAll(); // Store the query results in the request -- > model model.addAttribute("list", list); // Set view name return "list"; } }
  • Step 5: the list.jsp page displays data (non key)

    <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <table border="1" width="800"> <tr> <td>number</td> <td>Login name</td> <td>nickname</td> <td>email</td> <td>Telephone</td> <td>operation</td> </tr> <c:forEach items="$" var="user"> <tr> <td>$</td> <td>$</td> <td>$</td> <td>$</td> <td>$</td> <td> modify delete </td> </tr> </c:forEach> </table> </body> </html>

4.5 add

4.5.1 requirements

Complete user addition

4.5.2 steps

  • Step 1: click the Add button to display the add form

  • Step 2: write a controller to handle adding functions

    • After adding successfully, jump to the list page
    • After the addition fails, forward the addition page and prompt the error message
  • Step 3: write a service to complete the addition

4.5.3 realization

  • Step 1: click the Add button to display the add form

    • 1.1 in the list.jsp page, write the Add button

      <a href="$/user/addUI.action">add to</a>
    • 1.2 programming UserController display jsp

      /** * Display page * @return */ @RequestMapping("/addUI") public String addUI() { return "add"; }
    • 1.3 writing forms

      <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%-- error message --%> <font color="red"> $</font> <form action="$/user/add.action" method="post"> user name:<input type="text" name="userName" /> <br/> password:<input type="password" name="password" /> <br/> Nickname?<input type="text" name="name" /> <br/> <input type="submit" value="Add user"/> </form> </body> </html>
  • Step 2: write a controller to handle adding functions

    • After adding successfully, jump to the list page
    • After the addition fails, forward the addition page and prompt the error message
    /** * * @param user * @param model * @return */ @RequestMapping("/add") public String add(User user, Model model) { // Add user boolean result = userService.add(user); if(result) { // Added successfully return "redirect:/user/selectAll.action"; } else { // Add failed model.addAttribute("msg", "Add failed"); return "forward:/WEB-INF/pages/add.jsp"; } }
  • Step 3: write the service and finish adding (interface + implementation class)

    /** * add to * @param user * @return */ boolean add(User user);
    @Override public boolean add(User user) { // Auto generate id String uuidString = UUID.randomUUID().toString().replace("-",""); user.setUid(uuidString); int insert = userMapper.insert(user); return insert == 1; }

17 November 2021, 19:22 | Views: 7806

Add new comment

For adding a comment, please log in
or create account

0 comments