Tip: after the article is written, the directory can be generated automatically. Please refer to the help document on the right for how to generate it
Data processing and jump
ModelAndView
Set the ModelAndView object and jump to the specified page according to the name of the view and the view parser
Page: {view parser prefix} + viewName + {view parser suffix}
/WEB-INF/jsp/+viewName +.jsp
<!-- view resolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- prefix --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- suffix --> <property name="suffix" value=".jsp" /> </bean>
Corresponding controller class
public class ControllerTest1 implements Controller { public ModelAndView test() { //Returns a model view object ModelAndView mv = new ModelAndView(); mv.addObject("msg","ControllerTest1"); mv.setViewName("test"); // /WEB-INF/jsp/+**test** +.jsp return mv; } }
SpringMVC
Forward and redirect through spring MVC - view parser;
Redirection does not require a view parser. Its essence is to re request a new place, so pay attention to the path problem
You can redirect to another request implementation
@Controller public class ResultSpringMVC2 { @RequestMapping("/rsm2/t1") public String test1(){ //forward return "test"; } @RequestMapping("/rsm2/t2") public String test2(){ //The redirection address bar will change return "redirect:/index.jsp"; //return "redirect:hello.do"; //hello.do for another request/ } }
data processing
Process submitted data
1. The submitted domain name is consistent with the parameter name of the processing method
Submit data: http://localhost:8080/hello?name=loveyourself
Treatment method:
@RequestMapping("/hello") public String hello(String name){ System.out.println(name); return "hello"; }
Background output: loveyourself
2. The submitted domain name is inconsistent with the parameter name of the processing method
Submit data: http://localhost:8080/hello?username=loveyourself
Treatment method:
//@Requestparam ("username"): the name of the domain submitted by username @RequestMapping("/hello") public String hello(@RequestParam("username") String name){ System.out.println(name); return "hello"; }
Background output: loveyourself
3. Submitted is an object
It is required that the submitted form field and the attribute name of the object are consistent, and the parameter can use the object
1. Entity class
public class User { private int id; private String name; private int age; }
2. Submit data: http://localhost:8080/mvc04/user?name=loveyourself&id=1&age=15
3. Treatment method:
@RequestMapping("/user") public String user(User user){ //Too many transmission parameters can be received by object //Automatically match the field names in the User object. If the names are consistent, they can be transmitted System.out.println(user);//The output object defaults to the toString method used return "hello"; }
Background output: user {id = 1, name = 'loveyourself', age=18}
Note: if an object is used, the parameter name passed by the front end must be consistent with the object name, otherwise it is null.
Data display to front end
First: through ModelAndView
public class ControllerTest { @Controller public ModelAndView hello() { //Returns a model view object ModelAndView mv = new ModelAndView(); mv.addObject("msg","ControllerTest1"); mv.setViewName("test"); return mv; } }
Second: through ModelMap
ModelMap inherits LinkedHashMap, so all functions of UFIDA LinkedHashMap!
@RequestMapping("/hello") public String hello(@RequestParam("username") String name, ModelMap model){ //Encapsulates the data to be displayed in the view //Equivalent to req setAttribute("name",name); model.addAttribute("name",name); System.out.println(name); return "hello"; }
Third: through Model
Model
@RequestMapping("/ct2/hello") public String hello(@RequestParam("username") String name, Model model){ //Encapsulates the data to be displayed in the view //Equivalent to req setAttribute("name",name); model.addAttribute("msg",name); System.out.println(name); return "test"; }
contrast
For novices, the simple difference is:
Model There are only a few methods that are only suitable for storing data, simplifying the novice's understanding of Model Operation and understanding of objects; ModelMap Inherited LinkedMap ,In addition to implementing some of its own methods, the same inheritance LinkedMap Methods and characteristics of; ModelAndView While storing data, you can set the returned logical view and control the jump of the display layer.//Previously used to change the content of a partial page in a blog project
Garbled code problem
1. On the web XML configuration
<!--to configure SpringMVC Random code filtering--> <filter> <filter-name>encoding</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>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
But we found that in some extreme cases This filter does not support get well
Treatment method:
1. Modify tomcat configuration file: set code!
tomcat—>conf---->server.xml
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" />
2. Custom filter
/** * Filter to solve all the garbled codes of get and post requests */ public class GenericEncodingFilter implements Filter { @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //Handle the character encoding of the response HttpServletResponse myResponse=(HttpServletResponse) response; myResponse.setContentType("text/html;charset=UTF-8"); // Transformation into agreement related objects HttpServletRequest httpServletRequest = (HttpServletRequest) request; // Enhanced request packaging HttpServletRequest myrequest = new MyRequest(httpServletRequest); chain.doFilter(myrequest, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { } } //Custom request object, wrapper class of HttpServletRequest class MyRequest extends HttpServletRequestWrapper { private HttpServletRequest request; //Coded flag private boolean hasEncode; //Define a constructor that can be passed into the HttpServletRequest object to decorate it public MyRequest(HttpServletRequest request) { super(request);// super must write this.request = request; } // Override methods that need to be enhanced @Override public Map getParameterMap() { // Get request method first String method = request.getMethod(); if (method.equalsIgnoreCase("post")) { // post request try { // Handle post garbled code request.setCharacterEncoding("utf-8"); return request.getParameterMap(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else if (method.equalsIgnoreCase("get")) { // get request Map<String, String[]> parameterMap = request.getParameterMap(); if (!hasEncode) { // Make sure that the get manual encoding logic runs only once for (String parameterName : parameterMap.keySet()) { String[] values = parameterMap.get(parameterName); if (values != null) { for (int i = 0; i < values.length; i++) { try { // Handle get garbled code values[i] = new String(values[i] .getBytes("ISO-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } hasEncode = true; } return parameterMap; } return super.getParameterMap(); } //Take a value @Override public String getParameter(String name) { Map<String, String[]> parameterMap = getParameterMap(); String[] values = parameterMap.get(name); if (values == null) { return null; } return values[0]; // Retrieve the first value of the parameter } //Take all values @Override public String[] getParameterValues(String name) { Map<String, String[]> parameterMap = getParameterMap(); String[] values = parameterMap.get(name); return values; } }
This is written by some great gods on the Internet. Generally, the default garbled code processing of spring MVC can be well solved!
Then on the web Configure this filter in XML!
The problem of garbled code needs more attention at ordinary times. The unified coding UTF-8 should be set wherever possible!