Spring MVC [data write back and exception handling]

Posted by AZDoc on Sun, 24 Nov 2019 21:44:33 +0100

Article directory

Data back writing

  • Data updating: when updating data, the data queried by the server will be automatically filled into the form.

Default mode

  • Bind data through Map Mode ModelMap explained earlier

Through Model mode

If the object is used to receive the data from the client, the object will be automatically placed in the model by default, and the data in the object can be directly used in the front-end page.

Book.java

package com.sxt.pojo;

public class Book {

	private Integer bookId;
	
	private String bookName;
	
	private String author;
	
	private int publicYear;
	
	public Integer getBookId() {
		return bookId;
	}

	public void setBookId(Integer bookId) {
		this.bookId = bookId;
	}

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public int getPublicYear() {
		return publicYear;
	}

	public void setPublicYear(int publicYear) {
		this.publicYear = publicYear;
	}

	@Override
	public String toString() {
		return "Book [bookName=" + bookName + ", author=" + author + ", publicYear=" + publicYear + "]";
	}
	
}

HelloController.java

package com.sxt.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.sxt.pojo.Book;

/**
 * Annotation based custom controller
 * @author xieS
 *
 */
@Controller
public class HelloController {
	/**
	 * @param book It will be automatically saved in the Model object. The key is book
	 * 		m.addAttribute("book", book);
	 * @return
	 */
	@RequestMapping("/update")
	public String update(@ModelAttribute("bk")Book book){
		System.out.println(book);
		book.setBookName("sbq");
		return "/book.jsp";
	}
	/**
	 * @param book It will be automatically saved in the Model object. The key is book
	 * 		m.addAttribute("book", book);
	 * @return
	 */
	@RequestMapping("/add")
	public String add(@ModelAttribute("bk")Book book){
		System.out.println(book);
		book.setBookName("sbq");
		return "/book.jsp";
	}
	/**
	 * @param book It will be automatically saved in the Model object. The key is book
	 * 		m.addAttribute("book", book);
	 * @return
	 */
	@RequestMapping("/delete")
	public String delete(@ModelAttribute("bk")Book book){
		System.out.println(book);
		book.setBookName("sbq");
		return "/book.jsp";
	}
	@ModelAttribute("list")//Every method will execute
	public List<String> getList(){
		return Arrays.asList("jia","chun","qiu");
	}
}

book.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	${list}<br>
	<form action="update" method="post">
		Title:<input type="text" name="bookName" value="${bk.bookName }"><br>
		author:<input type="text" name="author" value="${bk.author}"><br>
		Year of publication<input type="text" name="publicYear" value="${bk.publicYear}"><br>
		<input type="submit" value="Submission">
	</form>
</body>
</html>

springmvc.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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		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-4.3.xsd">
	<!-- Open scan -->
	<context:component-scan base-package="com.sxt.controller"/>
	
	<!-- open SpringMVC How to annotate -->
	<mvc:annotation-driven></mvc:annotation-driven>
</beans>

web.xml

<?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">
  <display-name>SpringMVC-01</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- To configure SpringMVC Front controller central controller -->
  <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:springmvc.xml</param-value>
  	</init-param>
  	<!-- Load when container starts -->
  	<load-on-startup>2</load-on-startup>
  </servlet>
  <!-- To configure SpringMVC Mapping address for -->
  <servlet-mapping>
  	<servlet-name>SpringMVC</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>


@ModelAttribute annotation implementation

Modify parameter echo variable name

Add @ ModelAttribute("bk") annotation before the object that needs to be returned, and the write back information can be obtained through the bk prefix in the interface.

Configure global variable names

Return a uniform copy of data to each method in the interface

exception handling

Exceptions in the project need to be handled uniformly. Under normal circumstances, an error page needs to be prepared in advance. When an error occurs in the project, the page will be displayed to the user.
Steps:

Exception handler

package com.sxt.resolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * Global exception handler
 * @author xieS
 *
 */
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver{

	/**
	 * Global exception handling method
	 * @return null It means not to execute and handle in the way of not intercepting
	 */
	@Override
	public ModelAndView resolveException(HttpServletRequest request, 
			HttpServletResponse response, Object handler,
			Exception ex) {
		System.out.println("----The exception happened----"+ex);
		ModelAndView m = new ModelAndView();
		m.setViewName("/error.jsp");
		return m;
	}

}

errors.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>Maintenance...Please wait!!!</h1>
</body>
</html>


Topics: Java JSP xml Spring