Spring learning (trampling record + daily chat)

, hi

The progress of the college J2EE course has finally reached the MVC chapter, what a slow drop! School is like this. you have to learn by yourself

Although I have learned once, but still can not resist some forget

Do your homework this time!

(Step pit countless, silently leave tears, encounter a problem to ask Baidu!)

Don’t say much, I want to tell this paragraph of story 🤣, write this record of time, I just completed 8 join the party thought report (a 1000 words) plus rewrite join the party application form (1500), tears drop drops

1. Experimental requirements

  1. Understand the concepts of data binding in Spring MVC;

  2. Familiar with several data binding types in Spring MVC;

  3. Master the use of Spring MVC data binding.

The picture is the most direct

Isn’t it easy, bullshit, homework you can just copy code from a book

2. Experimental procedures

1. Create projects

Create Web projects with Eclipise

If you’ve ever used Eclipse, it’s free! , free things in addition to white piao, other places are ok

Even some of the pain, once a few times I made crazy late-night changes to the code, in order to achieve a function or effect made my scalp pins and needles

It turns out that the reboot solved the problem, or the software problem

Finally I know the truth, ** tears fall down! * * 🤬

I hope you can have a try. After all, changing the code can improve your psychological quality through more pain, ha ha ha ha!

This charge, expensive things in addition to expensive, other good (from LPL famous explanation words)

Of course, the computer is not good calculate, because card, a bit eat memory, but you can configure, when I did not say, because use than

Eclipse is so easy to use! The code hints are too good for a novice or lazy dog (me)

Although eclipse across various, but the school the teacher will teach the software in the teaching, because free, white piao must be sweet, write the textbooks code, can not too simple, actually eclipse can also develop big projects, in the early years when the programmer must have is to use it, as long as your ability to master the basic techniques of writing code and steps, Have good programming habits, I believe that Eclipse you can also be comfortable with! This software can be used to fly people, now early is a big bull, ha ha not pull!

2. Import project dependencies

The teacher has prepared the JAR package needed for this assignment

Maven is used to create and manage projects, not to mention Gradle. The project management tool is so powerful and convenient that it is convenient for us to develop projects.

Cliche: make the programmer only need to focus on the code to achieve the core function

But it is true that some teachers have been out of the profession for too long. After all, public service is great! But there are teachers who pay attention to what’s going on in IT, to new technologies

In short, IT industry changes with each passing day (operating system teacher said 😅), you should pay more attention to, more learning, technology on their own efforts to learn to understand just line, I do not understand

Harm, often feel his words more, the following nonsense little point

Put the jar packages that the project depends on in the lib directory

Then add Build

3. Project configuration

The thoughtful teacher even prepared the configuration file for us. We loved it

In fact, I have learned JSP technology, know how to create web. XML

Just look at the image and right-click the project to find the build! Eclipise has web project modules

After generating, write your own code to configure


      
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <! --encodingFilter-->
    <! Configure utF-8 encoding filter -->
    <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>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/ *</url-pattern>
    </filter-mapping>


    <! --DispatcherServlet-->
    <servlet>
        <servlet-name>DispatcherServlet</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-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>
Copy the code

DispatcherServlet:Spring provides a front-end controller class that controls view jumps, requests, etc

Let’s create the SpringMVC configuration in the SRC directory

Because, I installed the Spring plugin, it was cool at first, write this configuration file prompts, import namespace is convenient, but also quite a lot of bugs, you will see later

Write configuration, view parser, and sweep, as well as annotation driver


      
<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/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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">


    <! -- Configure SpringMVC -->
    <! -- 1. Enable SpringMVC annotation driver -->
    <mvc:annotation-driven />
    <! Static resource default servlet configuration -->
    <mvc:default-servlet-handler/>

    <! 3. Configure JSP to display ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <! -- 4. Scan for web-related beans -->
    <context:component-scan base-package="com.gip.controller" />

</beans>

Copy the code

The sweep is for the Controller layer, just make no mistake

4. Write entity classes

Experiment with 3 entity classes (including a wrapper class) on the line, directly on the code

package com.gip.pojo;

public class User {
	private Integer id;
	private String password;

	public Integer getId(a) {
		return id;
	}

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

	public String getPassword(a) {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public String toString(a) {
		return "User [id=" + id + ", password=" + password + "]"; }}Copy the code
package com.gip.pojo;

public class Orders {

	private Integer ordersId;
	private User user;

	public Integer getOrdersId(a) {
		return ordersId;
	}

	public void setOrdersId(Integer ordersId) {
		this.ordersId = ordersId;
	}

	public User getUser(a) {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	@Override
	public String toString(a) {
		return "Orders [ordersId=" + ordersId + ", user=" + user + "]"; }}Copy the code
package com.gip.pojo;

import java.util.List;

public class UserVO {

	private List<User> users;

	public List<User> getUsers(a) {
		return users;
	}

	public void setUsers(List<User> user) {
		this.users = user;
	}

	@Override
	public String toString(a) {
		return "UserVO [user=" + users + "]"; }}Copy the code

5. Write pages

How do the paths of view jumps match because of the view resolution configuration

bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
Copy the code

So create the JSP directory under/web-INF /

Then write the corresponding page, and put the public page in the WebContent directory

Because the WEB-INF folder is not a public resource

The normal process should be to expose an index page, and then register the URL and method to jump to the corresponding page in the Controller. Then there are links to jump to the corresponding page URL in the Index interface. The jump to the routing control page is the display of different components!

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"% > <! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1> First page </h1> <form action="${pageContext.request.contextPath}/res" method="post"> User name :<input type="text" name="id"> password :<input type="text" name="password"Password confirmation :<input type="text" name="password2">
<input type="submit" value="Registered">
</form>
<div style="color:red">
<%
	String msg=(String)request.getAttribute("msg");
	if(msg! =null){
		out.print(msg);
	}
%>
</div>

</body>
</html>
Copy the code
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"% > <! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1> Second page </h1> <form action="${pageContext.request.contextPath }/find" method="post"> Order number :<input type="text" name="ordersId"> User :<input type="text" name="user.id">
<input type="submit">
</form>
</body>
</html>
Copy the code
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"% > <! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1> Thrid page </h1> <form action="${pageContext.request.contextPath}/thrid" method="post">
<table width="30%" border="1"Choose > < tr > < td > < / td > < td > password < / td > < / tr > < tr > < td > < input name ="users[0].id" value="1" type="checkbox"/>
</td>
<td>
<input name="users[0].password" value="123" type="text"/>
</td>
</tr>
<tr>
<td>
<input name="users[1].id" value="2" type="checkbox"/>
</td>
<td>
<input name="users[1].password" value="321" type="text"/>
</td>
</tr>
</table>
<input type="submit" value="Change"/>
</form>
</body>
</html>
Copy the code

All three pages contain basic forms!

Input tag: name attribute values are the corresponding entity class field name is consistent!

6. Write the Controller layer

Create a FirstController class under the Controller package

package com.gip.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.gip.pojo.Orders;
import com.gip.pojo.User;

@RestController
public class FirstController {
	@PostMapping("/res")
	public String res(User user) {
		return user.toString();
	}

	@RequestMapping("/find")
	public String find(Orders orders) {
		returnorders.toString(); }}Copy the code

This is where I see a bug in eclipse. because I’ve installed a plugin, so when I call @Controller on a class, all the code under that class doesn’t show up. At first, I thought it was a setup problem. Later, I tried to restart it, but the problem still couldn’t be solved. There was a little crash, and then I checked the Jar package to see if there was anything wrong. Sure enough to solve the problem, to Baidu under the line, we are standing on the shoulders of giants to see the farther world, but make wheels, and use wheels are very different ~

Solution: Turn off a plugin setting, in which case, don’t take over

Reference link: blog.csdn.net/iteye_10432…

7. Run the tests

Configure the Tomcat server to get the project up and running

On the first page, enter your account number 5008 and password 666 and click Submit

Result: The value is received in the background and printed on the page

In the background method, the User object is a parameter type, indicating that Spring will help me map the value of the corresponding attribute to the parameter type, provided that the attribute name is consistent!

You can also change to a regular Controller and use the built-in Request object to store the data and forward it to a result page, or forward it back to the original page, where the JSP page uses the embedded syntax format to judge the logic and output the results

For reference:

@RequestMapping("/registerUser")
	public String registerUser(User user, HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Integer id = user.getId();
		String password = user.getPassword();
		String password2 = request.getParameter("password2");
		if(password ! =null && !password.equals(password2)) {
			String msg = "Different passwords!";
			request.setAttribute("msg", msg);
			request.getRequestDispatcher("/first.jsp").forward(request, response);
			System.out.println("Two different passwords.");
		}
		System.out.println("Registration successful! GO!");
		request.setAttribute("user", user);
		return "success";
	}
Copy the code

The second page requests the find method, which has the parameter type of Orders. This class has the property type of User, one-to-many relationship pattern, so it is a complex type. Spring also supports assigning the requested property value to the property of the corresponding parameter. Only the attribute name of the referenced type can be passed. Attribute name for example: name=”user.id” you cannot pass the user object directly, just remember that you can only pass the attribute value of the attribute name

If the value of the corresponding field is not found, it will not be assigned, so it will be empty!

Third page:

Tick all the boxes and click Modify

It will be submitted to the Thrid method in the Thrid class, which takes @Controller and takes UserVO, which is a wrapper class that wants to pass an array or collection of objects ** because the property name must match the value of the name property in the previous form, That’s why you need the UserVO wrapper class

For (User User: Users) iterates over the property Users: that is, the set of User classes in the passed UserVO object

If the front check is done, the ID property is passed, the password change operation is performed,

We then put the Users collection object into the built-in HttpServletRequest object and use the setAttribute method to create a key-value pair

Tip: Using HttpServletRequest requires importing Tomcat’s lib

Or use Model objects, again using the setAttribute method to create key-value pairs (which is what the Spring example does).

The Model object is also implemented by the Request object, and both can use Request. getAttribute to get parameter values, or EL expressions

Then return the “ca”; The front-end control diagram then forwards these parameters to the CA page

package com.gip.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gip.pojo.User;
import com.gip.pojo.UserVO;

@Controller
public class Thrid {

	@RequestMapping("/thrid")
	public String thrid(UserVO userList, HttpServletRequest request, Model model) {
		List<User> users = userList.getUsers();
		for (User user : users) {
			if(user.getId() ! =null) {
				user.setPassword(Change "123");
			}
		}
		request.setAttribute("userList", users);
		model.addAttribute("userList2", users);
		System.out.println(users);
		return "ca"; }}Copy the code

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*,com.gip.pojo.User"% > <! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1> CA page </h1> <%if(request.getAttribute("user")! =null){
	out.print(request.getAttribute("user"));
}

if(request.getAttribute("userList")! =null){
	List<User> users = (List<User>)request.getAttribute("userList");
	for (User user : users) {
		out.print(user);
	}
}
%>
<br/>
${userList2}
<br/>
<%
if(request.getAttribute("userList2")! =null){
	List<User> users = (List<User>)request.getAttribute("userList2");
	for (User user : users) {
		out.print(user);
	}
}
%>
</body>
</html>
Copy the code

By the way, there are two ways to evaluate it on the page (I will)

  1. useJSPembeddedjavaCode, usingout.print()Traverse the print to the page
  2. Using EL expressions${name}

Pit:

  1. useJSPPrint, if the value is usedresquestObject,request.getAttribute("userList");Don’t forget to use the guide bag.segmentationimport="java.util.*,com.gip.pojo.User"Otherwise absolutely error!
  2. Use EL expressions and someJstlLabel support requires derivativesJarBag, find it on the Internet

There are useful annotations in this article, and a cool way to create a corresponding key value pair: blog.csdn.net/weixin_4507…

SpringMVC ModelAndView, Model, Request domain usage: blog.csdn.net/weixin_4013…

3. Experiment summary

Review more, study more, these small problems, small details are worth discovering.

In the later days, I also want to pay more attention to these, you can not see often all details!