SpringMVC学习

20230712;

1.

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("add")) {
            req.getSession().setAttribute("msg", "执行了add方法");
        } else if ("delete".equals(method)) {
            req.getSession().setAttribute("msg", "执行了delete方法");
        }

        req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

3.

<?xml version="1.0" encoding="UTF-8"?>
<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">

    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.kuang.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    
    <!--<session-config>
        <session-timeout>15</session-timeout>
    </session-config>-->
    
    <!--<welcome-file-list>
        <welcome-file>welcome.jsp</welcome-file>
    </welcome-file-list>-->
</web-app>

4.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

5.

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2023/7/12
  Time: 23:53
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>welcome to SpringMVC!</h1>
</body>
</html>

6.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/hello" method="post">
    <input type="text" name="method"/>
    <input type="submit"/>
</form>
</body>
</html>

20230713;

1.

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
    </dependencies>

2.

<?xml version="1.0" encoding="UTF-8"?>
<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">

    <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-servlet.xml</param-value>
        </init-param>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

3.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="/hello" class="com.kuang.controller.HelloController"/>
</beans>

4.

public class HelloController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", "HelloSpringMVC!");
        mv.setViewName("hello");
        return mv;
    }
}

5.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

20230714;

1.

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <servlet>
        <servlet-name>springmvcTwo</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-servlet-two.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvcTwo</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

2.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <bean id="/hello" class="com.kuang.controllertwo.HelloMvcController"/>
</beans>

3.

public class HelloMvcController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mv = new ModelAndView();
        String str = "HelloSpringMVCTwo!";
        mv.addObject("msg", str);
        mv.setViewName("test");
        return mv;
    }
}

4.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

20230715;

1.

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <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-servlet-annotation.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

2.

<?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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:component-scan base-package="com.kuang.controller"/>
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

3.

@Controller
@RequestMapping("/hello")
public class HelloController {
    @RequestMapping("/h1")
    public String hello1(Model model) {
        model.addAttribute("msg", "Hello,SpringMVC by Annotation one!");
        return "hello1";
    }

    @RequestMapping("/h2")
    public String hello2(Model model) {
        model.addAttribute("msg", "Hello,SpringMVC by Annotaion two!");
        return "hello1";
    }
}

4.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

20230716;

1.

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <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-servlet.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>
</web-app>

2.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <bean id="/helloByImplementsController" class="com.kuang.controller.HelloControllerByImplementsController"/>
</beans>

3.

public class HelloControllerByImplementsController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", "Hello Controller By Implements Controller!");
        mv.setViewName("test");
        return mv;
    }
}

4.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

5.

<?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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:component-scan base-package="com.kuang.controller"/>
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
<!--    <bean id="/helloByImplementsController" class="com.kuang.controller.HelloControllerByImplementsController"/>-->
</beans>

6.

@Controller
@RequestMapping("/helloByAnnotation")
public class HelloControllerByAnnotation {
    @RequestMapping("/methodByAnno")
    public String methodByAnnotation(Model model) {
        model.addAttribute("msg", "Hello By Annotation20230716!");
        return "test";
    }
}

20230717;

1.

@Controller
public class TestRESTfulApiController {
    // http://localhost:8080/ordiReq?a=1&b=2
    @RequestMapping("/ordiReq")
    public String ordinaryRequest(int a, int b, Model model) {
        model.addAttribute("msg", a + b);
        return "test";
    }

    // http://localhost:8080/ordiReq2?a=2&b="abcde"
    // http://localhost:8080/ordiReq2?a=2&b="pingfan"
    @RequestMapping("/ordiReq2")
    public String ordinaryRequest2(int a, String b, Model model) {
        model.addAttribute("msg", a + b);
        return "test";
    }

    // http://localhost:8080/testRESTful/1/'dasfadsf'
    @RequestMapping("/testRESTful/{a}/{b}")
    public String testRESTful(@PathVariable(name = "a") int a, @PathVariable(name = "b") String b, Model model) {
        model.addAttribute("msg", a + b);
        return "test";
    }

    // http://localhost:8080/rest2/1/'dasfadsf'
    @RequestMapping(value = "/rest2/{a}/{b}", method = RequestMethod.GET)
    public String testRESTful2(@PathVariable int a, @PathVariable String b, Model model) {
        model.addAttribute("msg", a + b);
        return "test";
    }

    // http://localhost:8080/rest3/1/'dasfadsf'
    @GetMapping("/rest3/{a}/{b}")
    public String testRESTful3(@PathVariable int a, @PathVariable String b, Model model) {
        model.addAttribute("msg", a + b);
        return "test";
    }
}

20230718;

1.

// 20230718练习
    @RequestMapping("/rest4/{a}/{b}")
    public String rest4(@PathVariable int a, @PathVariable String b, Model model) {
        model.addAttribute("msg", a + b);
        return "test";
    }

    // http://localhost:8080/rest5/22/'dasf'
    //http://localhost:8080/rest5/22/dasf
    @RequestMapping(path = "rest5/{a}/{b}", method = RequestMethod.GET)
    public String rest5(@PathVariable int a, @PathVariable String b, Model model) {
        model.addAttribute("msg", "rest5" + a + b);
        return "test";
    }

    // <form action="/rest5/22/adafa" method="post">
    // 浏览器url也展示为http://localhost:8080/rest5/22/dasf
    @RequestMapping(value = "rest5/{a}/{b}", method = RequestMethod.POST)
    public String rest6(@PathVariable int a, @PathVariable String b, Model model) {
        model.addAttribute("msg", "rest6" + a + b);
        return "test";
    }

2.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/rest5/22/dasf" method="post">
    <input type="submit"/>
</form>
</body>
</html>

3.

<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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:component-scan base-package="com.kuang.controller"/>
<!--    <mvc:default-servlet-handler/>-->
<!--    <mvc:annotation-driven/>-->
<!--    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">-->
<!--        <property name="prefix" value="/WEB-INF/jsp/"/>-->
<!--        <property name="suffix" value=".jsp"/>-->
<!--    </bean>-->
<!--    <bean id="/helloByImplementsController" class="com.kuang.controller.HelloControllerByImplementsController"/>-->
</beans>

4.

@Controller
public class TestBaseServletForwarAndRedirectWithoutViewResolver {
    @RequestMapping("/testBaseServletForwardAndRedirectWithoutViewResolver")
    public String testBaseServletForwardAndRedirectWithoutViewResolver(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        System.out.println(session.getId());
//        return "/WEB-INF/jsp/test.jsp";
//        return "forward:/WEB-INF/jsp/test.jsp";
        return "redirect:/index.jsp";
    }
}

5.

@Controller
public class TestForwardAndRedirectBySpringMvcWithoutViewResolver {
    @RequestMapping("testForwardAndRedirectBySpringMvcWithoutViewResolver")
    public String testForwardAndRedirectBySpringMvcWithoutViewResolver(Model model) {
        model.addAttribute("msg", "testForwardAndRedirectBySpringMvcWithoutViewResolver");
//        return "/WEB-INF/jsp/test.jsp";
//        return "forward:/WEB-INF/jsp/test.jsp";
        return "redirect:/index.jsp";
    }
}

6.

<?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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:component-scan base-package="com.kuang.controller"/>
<!--    <mvc:default-servlet-handler/>-->
<!--    <mvc:annotation-driven/>-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
<!--    <bean id="/helloByImplementsController" class="com.kuang.controller.HelloControllerByImplementsController"/>-->
</beans>

7.

@Controller
public class TestForwardAndRedirectByViewResolver {
    @RequestMapping("/testForwardByViewResolver")
    public String testForwardByViewResolver(Model model) {
        model.addAttribute("msg", "testForwardByViewResolver");
        // 错误事例:
//        return "/WEB-INF/jsp/test.jsp";
        // 正确事例:
        return "test";
    }

    @RequestMapping("/testRedirectByViewResolver")
    public String testRedirectByViewResolver(Model model) {
        model.addAttribute("msg", "testRedirectByViewResolver");
        return "redirect:/index.jsp";
    }
}

20230719;

1.

@Controller
@RequestMapping("/receive")
public class TestReceivingRequestParametersController {
    // http://localhost:8080/receive/notRecommended?name=zhangsan
    @RequestMapping("/notRecommended")
    public String receiveByNoRequestParamAnnoWhichIsNotRecommended(
            String name, Model model) {
        model.addAttribute("msg", name);
        return "test";
    }

    // http://localhost:8080/receive/recommentedWhenNotObject?username=zhangsan
    @RequestMapping("/recommentedWhenNotObject")
    public String receiveByRecommendedUsingRequestParamAnnoWhenNotObject(
            @RequestParam("username") String name, Model model) {
        model.addAttribute("msg", name);
        return "test";
    }

    // http://localhost:8080/receive/receiveObjectNotRecommended?id=1&name=zhangsan&age=28
    @RequestMapping("/receiveObjectNotRecommended")
    public String receiveObjectNotRecommended(
            @RequestParam("id") int id,
            @RequestParam("name") String name,
            @RequestParam("age") int age, Model model) {
        User user = new User(id, name, age);
        model.addAttribute("msg", user);
        return "test";
    }

    // http://localhost:8080/receive/receiveObjectRecomended?id=1&name=zhangsan&age=28
    @RequestMapping("/receiveObjectRecomended")
    public String receiveObjectRecomended(User user, Model model) {
        model.addAttribute("msg", user);
        return "test";
    }
}

20230720;

1.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/encodingBySpringMvcFilter2" method="post">
    <input type="text" name="name"/>
    <input type="submit"/>
</form>
</body>
</html>

2.

public class EncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("=========enter custom filter=========");
        servletRequest.setCharacterEncoding("utf-8");
        servletRequest.setCharacterEncoding("utf-8");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

3.

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <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-servlet.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>
<!--    <filter>-->
<!--        <filter-name>encodingByCustomFilter</filter-name>-->
<!--        <filter-class>com.kuang.filter.EncodingFilter</filter-class>-->
<!--    </filter>-->
<!--    <filter-mapping>-->
<!--        <filter-name>encodingByCustomFilter</filter-name>-->
<!--        <url-pattern>/*</url-pattern>-->
<!--    </filter-mapping>-->
    <filter>
        <filter-name>encodingBySpringMvc</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>encodingBySpringMvc</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

4.

@Controller
public class EncodingController {
    /**
     * 乱码
     * <form action="/encoding/basicTest" method="post">
     *     <input type="text" name="name"/>
     *     <input type="submit"/>
     * </form>
     * @param name
     * @param model
     * @return
     */
    @PostMapping("/basicTest")
    public String basicTest(@RequestParam("name") String name, Model model) {
        System.out.println(name);
        model.addAttribute("msg", name);
        return "test";
    }

    /**
     * 仍乱码
     * <form action="/basicTestByRequestError" method="post">
     *     <input type="text" name="name"/>
     *     <input type="submit"/>
     * </form>
     * @param name
     * @param model
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @PostMapping("/basicTestByRequestError")
    public String basicTestByRequestError(@RequestParam("name") String name, Model model, HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        System.out.println(name);
        model.addAttribute("msg", name);
        return "test";
    }

    /**
     * 乱码
     * <filter>
     *         <filter-name>encodingByCustomFilter</filter-name>
     *         <filter-class>com.kuang.filter.EncodingFilter</filter-class>
     *     </filter>
     *     <filter-mapping>
     *         <filter-name>encodingByCustomFilter</filter-name>
     *         <url-pattern>/</url-pattern>
     *     </filter-mapping>
     */
    @PostMapping("/encodingByCustomFilter")
    public String encodingByCustomFilter(@RequestParam("name") String name, Model model) {
        System.out.println(name);
        model.addAttribute("msg", name);
        return "test";
    }

    /**
     * 不乱码
     * <filter>
     *         <filter-name>encodingByCustomFilter</filter-name>
     *         <filter-class>com.kuang.filter.EncodingFilter</filter-class>
     *     </filter>
     *     <filter-mapping>
     *         <filter-name>encodingByCustomFilter</filter-name>
     *         <url-pattern>/*</url-pattern>
     *     </filter-mapping>
     */
    @PostMapping("/encodingByCustomFilter2")
    public String encodingByCustomFilter2(@RequestParam("name") String name, Model model) {
        System.out.println(name);
        model.addAttribute("msg", name);
        return "test";
    }

    /**
     * 乱码
     * <filter>
     *         <filter-name>encodingBySpringMvc</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>encodingBySpringMvc</filter-name>
     *         <url-pattern>/*</url-pattern>
     *     </filter-mapping>
     * @param name
     * @param model
     * @return
     */
    @PostMapping("/encodingBySpringMvcFilter")
    public String encodingBySpringMvcFilter(@RequestParam("name") String name, Model model) {
        System.out.println(name);
        model.addAttribute("msg", name);
        return "test";
    }

    /**
     * 可以解决乱码
     * <filter>
     *         <filter-name>encodingBySpringMvc</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>encodingBySpringMvc</filter-name>
     *         <url-pattern>/*</url-pattern>
     *     </filter-mapping>
     * @param name
     * @param model
     * @return
     */
    @PostMapping("/encodingBySpringMvcFilter2")
    public String encodingBySpringMvcFilter2(@RequestParam("name") String name, Model model) {
        System.out.println(name);
        model.addAttribute("msg", name);
        return "test";
    }

}

20230721;

1.parse /pɑːs/ 解析;

2.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<script type="text/javascript">
    var user = {
        name : "zhangsan",
        age : 27,
        sex : ""
    };
    var json = JSON.stringify(user);
    console.log(json);
    var obj = JSON.parse(json);
    console.log(obj);
    console.log(user);
</script>
</body>
</html>

20230722;

1.

<dependencies>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.15.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>
    </dependencies>

2.

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <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-servlet.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>
</web-app>

3.

<?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"
       xsi:schemaLocation="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.xsd">
    <context:component-scan base-package="com.kuang.user.controller"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

4.

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
    private String sex;
}

5.

@Controller
public class UserController {
    @RequestMapping("/testBasicToString")
    @ResponseBody
    public String testBasicToString() {
        User user = new User("秦疆1号", 3, "男");
        return user.toString();
    }

    @RequestMapping("/testBasicJackson")
    @ResponseBody
    public String testBasicJackson() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        User user = new User("秦疆2号", 22, "男");
        String s = mapper.writeValueAsString(user);
        return s;
    }
}

20230723;

1.

@RequestMapping(value = "testSolveEncodingProblemByProduces", produces = "text/json;charset=utf-8")
    @ResponseBody
    private String testSolveEncodingProblemByProduces() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        User user = new User("wangwu", 30, "男");
        return mapper.writeValueAsString(user);
    }

20230724;

1.

<?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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:component-scan base-package="com.kuang.user.controller"/>
    <!--SpringMVC处理jackson的JSON乱码问题-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

2.

@RequestMapping("testSolveEncodingProblemByConfig")
    @ResponseBody
    public String testSolveEncodingProblemByConfig() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        User user = new User("木头六", 40, "男");
        return mapper.writeValueAsString(user);
    }

    @RequestMapping("/testReturnArray")
    @ResponseBody
    public String testReturnArray() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        User user1 = new User("张三", 20, "男");
        User user2 = new User("李四", 21, "女");
        User user3 = new User("王五", 22, "男");
        ArrayList<User> users = new ArrayList<>();
        users.add(user1);
        users.add(user2);
        users.add(user3);
        return mapper.writeValueAsString(users);
    }

20230725;

1.

@RequestMapping("/testDateToJsonByJavaSdf")
    @ResponseBody
    public String testDateToJsonByJavaSdf() throws JsonProcessingException {
//        ObjectMapper mapper = new ObjectMapper();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date date = new Date();
//        return mapper.writeValueAsString(sdf.format(date));

//        return JackSonUtil.getJson(new Date(), "yyyy-MM-dd HH:mm:ss");

        return JackSonUtil.getJson(new Date());
    }

    @RequestMapping("/testDateToJsonByObjectMapperSdf")
    @ResponseBody
    public String testDateToJsonByObjectMapperSdf() throws JsonProcessingException {
//        ObjectMapper mapper = new ObjectMapper();
//        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        mapper.setDateFormat(sdf);
//        return mapper.writeValueAsString(new Date());

//        return JackSonUtil.getJson(new Date(), "yyyy-MM-dd HH:mm:ss");
        return JackSonUtil.getJson(new Date());
    }

2.

public class JackSonUtil {
    public static String getJson(Object object) {
        return getJson(object, "yyyy-MM-dd HH:mm:ss");
    }

    public static String getJson(Object object, String dateFormat) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        mapper.setDateFormat(sdf);
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

20230726;

1.

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>

2.

@RequestMapping("/testFastjson")
    @ResponseBody
    public String testFastjson() {
        ArrayList<User> users = new ArrayList<>();
        User u1 = new User("张三", 28, "男");
        User u2 = new User("李四", 20, "男");
        User u3 = new User("王五", 23, "女");
        users.add(u1);
        users.add(u2);
        users.add(u3);
        String s = JSONObject.toJSONString(users);
        return s;
    }

20230729;

1.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>ssmbuild</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.26</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>
    </dependencies>

</project>

2.

@Data
public class Book {
    private int bookId;
    private String bookName;
    private int bookCount;
    private String detail;
}

3.

public interface BookMapper {
    public int addBook(Book book);
    public int deleteBookById(@Param("bookId") int id);
    public int updateBook(Book book);
    public Book queryBookById(@Param("bookId") int id);
    public List<Book> queryAllBook();
}

4.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper>
    <insert id="addUser" parameterType="Book">
        insert into BOOK (bookName, bookCount, detail)
            values (#{bookName}, #{bookCount}, #{detail});
    </insert>

    <delete id="deleteBookById" parameterType="int">
        delete from BOOK where bookId = #{bookId};
    </delete>

    <update id="updateBook" parameterType="Book">
        update BOOK set bookName = #{bookName},
                        bookCount = #{bookCount},
                        detail = #{detail}
                    where bookId = #{bookId};
    </update>

    <select id="queryBookById" parameterType="int" resultType="Book">
        select * from BOOK where bookId = #{bookId};
    </select>

    <select id="queryAllBook" resultType="Book">
        select * from BOOK;
    </select>
</mapper>

5.

public interface BookService {
    public int addBook(Book book);
    public int deleteBookById(int id);
    public int updateBook(Book book);
    public Book queryBookById(int id);
    public List<Book> queryAllBook();
}

6.

public class BookServiceImpl implements BookService {
    private BookMapper bookMapper;

    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    @Override
    public int addBook(Book book) {
        return bookMapper.addBook(book);
    }

    @Override
    public int deleteBookById(int id) {
        return bookMapper.deleteBookById(id);
    }

    @Override
    public int updateBook(Book book) {
        return bookMapper.updateBook(book);
    }

    @Override
    public Book queryBookById(int id) {
        return bookMapper.queryBookById(id);
    }

    @Override
    public List<Book> queryAllBook() {
        return bookMapper.queryAllBook();
    }
}

7.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="com.kuang.pojo"/>
    </typeAliases>

    <mappers>
        <mapper class="com.kuang.mapper"/>
    </mappers>
</configuration>

20230730;

1.

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild
jdbc.username=root
jdbc.password=root

2.

<?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"
       xsi:schemaLocation="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.xsd">

    <context:property-placeholder location="classpath:database.properties"/>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

</beans>

20230801;

1.

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>6.0.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>6.0.9</version>
        </dependency>

2.

<?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"
       xsi:schemaLocation="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.xsd">

    <context:property-placeholder location="classpath:database.properties"/>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.kuang.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

</beans>

3.

<?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"
       xsi:schemaLocation="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.xsd">
    <context:component-scan base-package="com.kuang.service"/>

    <bean id="bookService" class="com.kuang.service.impl.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>

    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

20230803;

1.

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <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: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>

    <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>

    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

2.

<?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/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    <context:component-scan base-package="com.kuang.controller"/>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

3.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <import resource="spring-dao.xml"/>
    <import resource="spring-service.xml"/>
    <import resource="spring-mvc.xml"/>
</beans>

20230905;

1.decoration /ˌdek.əˈreɪ.ʃən/  装饰

text-decoration

20230907,

1.解决idea service控制台中文乱码:https://blog.csdn.net/qq_40406929/article/details/122957674

2.tomcat启动失败:

2.1如果Tomcat启动不成功,是没有lib的原因

解决办法:项目结构-artifacts,然后 把你的WEB-INF目录展开,如果没有lib包就单击一下WEB-INF目录,然后点那个文件夹带个+的图标,新建lib文件夹,选中lib文件夹,点击+下面带个小三角那个图标,选第一个Library Files,全选添加,然后Apply-ok就行了。重启Tomcat就能成功了

2.2启动Tomcat报错:org.apache.jasper.JasperException: java.lang.ClassNotFoundException: org.apache.jsp.index_jsp:

这是因为在lib中加了jsp-api.jar和servlet-api.jar,与Tomcat中的冲突,所以删掉项目lib中的这两个包就行了,因为Tomcat中已经存在了。

2.3启动有问题,正在解决。

20230912,

1.Tomcat启动各种报错,解决方案:project stucture里保证artifacts里lib下不爆红

2.仍报错,重装Tomcat后仍报错,修改catalina.properties解决问题

# tomcat.util.scan.DefaultJarScanner.jarsToSkip=\
# 改为如下
tomcat.util.scan.DefaultJarScanner.jarsToSkip=\,*

Tomcat启动成功。

20230912,

1.spring-mvc.xml里,视图解析器 InternalResourceViewResolver 将控制器返回的逻辑视图名转化为视图资源,

例如将allBook转化为/WEB-INF/jsp/allBook.jsp

所以如果allBook.jsp建在WEB-INF/jsp路径下,在spring-mvx.xml里,配置前缀时一定不能漏了最后的/,即/WEB-INF/jsp/

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("bookServiceImpl")
    private BookService bookService;

    @RequestMapping("/allBook")
    public String allBook(Model model) {
        List<Book> list = bookService.queryAllBook();
        model.addAttribute("list", list);
        return "allBook";
    }
}
<?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/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    <context:component-scan base-package="com.kuang.controller"/>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

20230913,

1.margin 给元素设置外边距,分别是上 右 下 左。

2.border-radius/ˈreɪ.di.əs/ 设置元素的圆角外边框

3.启动报错 无法在web.xml或使用此应用程序部署的jar文件中解析绝对uri:[http://java.sun.com/jsp/jstl/core]

https://www.cnblogs.com/dzwj/p/17438483.html

https://blog.csdn.net/qq_61570366/article/details/132767031

https://developer.aliyun.com/article/922935

即解决方案:

pom导入standard依赖,解压standard.jar将tld复制到WEB/INF,web.xml里配置JSTL,project sturcture菜单里artifacts重新部署

 

4.pom.xml里

<!-- https://mvnrepository.com/artifact/taglibs/standard -->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

5.web.xml里

<jsp-config>
        <taglib>
            <taglib-uri>http://java.sun.com/jstl/fmt</taglib-uri>
            <taglib-location>/WEB-INF/fmt.tld</taglib-location>
        </taglib>
        <taglib>
            <taglib-uri>http://java.sun.com/jstl/core</taglib-uri>
            <taglib-location>/WEB-INF/c.tld</taglib-location>
        </taglib>
    </jsp-config>

6.index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
    <style>
      a{
        text-decoration: none;
        color: black;
        font-size: 18px;
      }
      h3{
        width: 180px;
        height: 38px;
        margin: 100px auto;
        text-align: center;
        line-height: 38px;
        background: deepskyblue;
        border-radius: 5px;
      }
    </style>
  </head>
  <body>
    <h3>
      <a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a>
    </h3>
  </body>
</html>

7.allBook.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="row clearfix">
            <div class="col-md-12 column">
                <div class="page-header">
                    <h1>书籍展示 ———— 书籍列表</h1>
                </div>
            </div>
        </div>
        <div class="row clearfix">
            <div class="col-md-12 column">
                <table class="table table-hover table-striped">
                    <thead>
                        <tr>
                            <th>书籍编号</th>
                            <th>书籍名称</th>
                            <th>书籍数量</th>
                            <th>书籍详情</th>
                        </tr>
                    </thead>
                    <tbody>
                        <c:forEach var="book" items="${list}">
                            <tr>
                                <td>${book.bookId}</td>
                                <td>${book.bookName}</td>
                                <td>${book.bookCount}</td>
                                <td>${book.detail}</td>
                            </tr>
                        </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>

20231008,

1.allBook.jsp

<div class="row">
                <div class="col-md-3 column">
                    <p><a class="btn btn-primary btn-lg" href="${pageContext.request.contextPath}/book/goAddPage" role="button">新增书籍</a></p>
                </div>
            </div>

2.BookController.java

@RequestMapping("/goAddPage")
    public String goAddPage(Model model) {
        return "addBook";
    }

    @RequestMapping("/addBook")
    public String addBook(Book book) {
        System.out.println(book);
        bookService.addBook(book);
        return "redirect:/book/allBook";
    }

3.addBook.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>新增书籍</h1>
            </div>
        </div>
        <div class="row">
            <form class="form-signin" action="${pageContext.request.contextPath}/book/addBook" method="post">
                <label for="bookName">书籍名称</label>
                <input type="text" id="bookName" name="bookName" value="${book.bookName}" class="form-control" placeholder="书籍名称" required autofocus>
                <label for="bookCount">书籍数量</label>
                <input type="text" id="bookCount" name="bookCount" value="${book.bookCount}" class="form-control" placeholder="书籍数量" required>
                <label for="detail">书籍详情</label>
                <input type="text" id = "detail" name="detail" value="${book.detail}" class="form-control" placeholder="书籍详情" required>
                <button class="btn btn-lg btn-primary btn-block" type="submit">保存</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

4.BookMapper.xml

<insert id="addBook" parameterType="Book">
        insert into BOOK (bookName, bookCount, detail)
            values (#{bookName}, #{bookCount}, #{detail});
    </insert>

20231009,

1.BookController.java

@RequestMapping("/goUpdatePage")
    public String goUpdatePage(int id, Model model) {
        Book book = bookService.queryBookById(id);
        model.addAttribute("book", book);
        return "updateBook";
    }

    @RequestMapping("/updateBook")
    public String updateBook(Book book) {
        System.out.println("BookController.updateBook=>" + book);
        int updateResult = bookService.updateBook(book);
        if (updateResult > 0) {
            List<Book> list = bookService.queryAllBook();
            System.out.println("BookController.updateBook 更新成功");
            System.out.println(list);
        }
        return "redirect:/book/allBook";
    }

    @RequestMapping("/deleteBook/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id) {
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }

2.updateBook.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>修改书籍</h1>
            </div>
        </div>
        <div class="row">
            <form class="form-signin" action="${pageContext.request.contextPath}/book/updateBook" method="post">
                <input type="hidden" name="bookId" value="${book.bookId}">
                <label for="bookName">书籍名称</label>
                <input type="text" id="bookName" name="bookName" value="${book.bookName}" class="form-control" placeholder="书籍名称" required autofocus>
                <label for="bookCount">书籍数量</label>
                <input type="text" id="bookCount" name="bookCount" value="${book.bookCount}" class="form-control" placeholder="书籍数量" required>
                <label for="detail">书籍详情</label>
                <input type="text" id = "detail" name="detail" value="${book.detail}" class="form-control" placeholder="书籍详情" required>
                <button class="btn btn-lg btn-primary btn-block" type="submit">修改</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

3.mybatis-config.xml

<settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

4.spring-service.xml

<tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="myPointcut" expression="execution(* com.kuang.mapper.*.*(..))"></aop:pointcut>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"></aop:advisor>
    </aop:config>

5.allBook.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="row clearfix">
            <div class="col-md-12 column">
                <div class="page-header">
                    <h1>书籍展示 ———— 书籍列表</h1>
                </div>
            </div>
            <div class="row">
                <div class="col-md-3 column">
                    <p><a class="btn btn-primary btn-lg" href="${pageContext.request.contextPath}/book/goAddPage" role="button">新增书籍</a></p>
                </div>
            </div>
        </div>
        <div class="row clearfix">
            <div class="col-md-12 column">
                <table class="table table-hover table-striped">
                    <thead>
                        <tr>
                            <th>书籍编号</th>
                            <th>书籍名称</th>
                            <th>书籍数量</th>
                            <th>书籍详情</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <c:forEach var="book" items="${list}">
                            <tr>
                                <td>${book.bookId}</td>
                                <td>${book.bookName}</td>
                                <td>${book.bookCount}</td>
                                <td>${book.detail}</td>
                                <td>
                                    <a href="${pageContext.request.contextPath}/book/goUpdatePage?id=${book.bookId}">修改</a>
                                    &nbsp; | &nbsp;
                                    <a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookId}">删除</a>
                                </td>
                            </tr>
                        </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>

20231010,

1.BookController.java

@RequestMapping("/queryBookByName")
    public String queryBookByName(String queryBookName, Model model) {
        Book book = bookService.queryBookByName(queryBookName);
        List<Book> list = new ArrayList<>();
        if (book != null) {
            list.add(book);
        } else {
            model.addAttribute("errorMsg", "未查询到书籍");
            list = bookService.queryAllBook();
        }
        model.addAttribute("list", list);
        return "allBook";
    }

    @RequestMapping("/queryAllBook")
    public String queryAllBook(Model model) {
        List<Book> list = bookService.queryAllBook();
        model.addAttribute("list", list);
        return "allBook";
    }

2.BookServiceImpl.java

@Override
    public Book queryBookByName(String queryBookName) {
        return bookMapper.queryBookByName(queryBookName);
    }

3.BookService.java

public Book queryBookByName(String queryBookName);

4.BookMapper.java

public Book queryBookByName(@Param("bookName") String queryBookName);

5.BookMapper.xml

<select id="queryBookByName" resultType="Book">
        select * from BOOK where bookName = #{bookName};
    </select>

6.allBook.jsp

<div class="row">
                <div class="col-md-4 column">
                    <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/goAddPage" role="button">新增书籍</a>
                    <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/queryAllBook">查询所有书籍</a>
                </div>
                <div class="col-md-8 column">
                    <form class="form-inline" style="float: right" action="${pageContext.request.contextPath}/book/queryBookByName" method="post">
                        <span style="color: red;font-weight: bold">${errorMsg}</span>
                        <input type="text" name="queryBookName" placeholder="请输入书籍名称" class="form-control" />
                        <input type="submit" value="查询" class="form-control" />
                    </form>
                </div>
            </div>

7.狂神ssm-demo项目效果:

20231012,

1.web.xml

<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:applicationContext.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>

    <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>

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

    <context:component-scan base-package="com.kuang.Controller"/>

    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

3.AjaxController.java

@RestController
public class AjaxController {
    @RequestMapping("/a1")
    public void a1(String name, HttpServletResponse httpServletResponse) throws IOException {
        System.out.println("a1:name=>" + name);
        String result = "kuangshen".equals(name) ? "true" : "false";
        httpServletResponse.getWriter().println(result);
    }
}

4.效果

 

20231013,

1.imitateAjax.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模拟Ajax效果</title>
    <script>
        function getInputUrlRefreshIFrame() {
            document.getElementById("myIFrame").src = document.getElementById("urlInput").value;
        }
        function changeInputUrlShowVueWebsite() {
            document.getElementById("urlInput").value = 'https://cn.vuejs.org';
            document.getElementById("myIFrame").src = document.getElementById("urlInput").value;
        }
    </script>
    <style>
        .url-input {
            width: 500px;
        }
        .my-iframe {
            width: 500px;
            height: 400px;
        }
        .go-input-button {
            width: 235px;
        }
        .go-vue-button {
            width: 293px;
        }
    </style>
</head>
<body>
    <input class="url-input" type="text" style="" id="urlInput" value="https://cn.vuejs.org/api/composition-api-setup.html#basic-usage"/>
    <br>
    <br>
    <div>
        点击在iframe中加载input框中的URL
        <input class="go-input-button" type="button" onclick="getInputUrlRefreshIFrame()" value="showInputUrlInIFrame"/>
    </div>
    <br>
    <div>
        点击在iframe中展示Vue官网
        <input class="go-vue-button" type="button" onclick="changeInputUrlShowVueWebsite()" value="changeInputUrlShowVueWebsiteInIFrame"/>
    </div>
    <br>
    <div>iframe展示:</div>
    <iframe class="my-iframe" id="myIFrame" src="https://cn.vuejs.org/api/composition-api-setup.html#basic-usage"/>
</body>
</html>

2.效果:

3.applicationContext.xml

<mvc:default-servlet-handler/>

4.index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>测试Ajax</title>
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.7.1.js"></script>
    <script>
      function testAjax() {
        $.post({
          url: "${pageContext.request.contextPath}/testAjax",
          dataType: "json",
          data: {
            "name": $("#usernameInput").val()
          },
          success: function (data) {
            alert("success-" + data);
          },
          error: function (data) {
            alert("error-" + data);
            console.log(data);
          }
        })
      }
    </script>
  </head>
  <body>
  <input id="usernameInput" type="text" value="请输入用户名" onblur="testAjax()"/>
<%--  <input type="button" value="提交" onclick="testAjax()"/>--%>
  </body>
</html>

5.AjaxController.java

@RequestMapping("/testAjax")
    public boolean testAjax(String name) {
//        int i = 5 / 0;
        return "kuangshen".equals(name) ? true : false;
    }

6.效果: 

 

20231014,

今天练习过程中突然404了暂时未能解决,下一步继续解决。这导致id="testGetDataByAjax"的按钮的点击事件方法未进行测试。

1.AjaxController.java

@RequestMapping("/testAjaxResponseWrite")
    public void testAjaxResponseWrite(String name, HttpServletResponse httpServletResponse) throws IOException {
        boolean result = "kuangshen".equals(name) ? true : false;
        httpServletResponse.getWriter().print(result);
    }

    /*@RequestMapping("/getUserList")
    public List<User> getUserList() {
        List<User> users = new ArrayList<>();
        users.add(new User("1", "狂神说Java", 3, "男"));
        users.add(new User("2", "狂神说Spring", 4, "男"));
        users.add(new User("3", "狂神说SpringMVC", 5, "男"));
        return users;
    }*/

2.User.java

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String id;
    private String name;
    private int age;
    private String sex;
}

3.testAjaxGetData.jsp

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2023/10/14
  Time: 11:29
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.7.1.js"></script>
    <script>
        function testAjaxStatus() {
            $.post({
                url: "${pageContext.request.contextPath}/testAjax",
                data: {
                    name: $("#username").val()
                },
                success: function(data, status) {
                    console.log("data=>" + data);
                    console.log("status=>" + status);
                },
                error: function(data, status) {
                    console.log("data=>" + data);
                    console.log("status=>" + status);
                }
            })
        }
        function testAjaxResponseWrite() {
            $.post({
                url: "${pageContext.request.contextPath}/testAjaxResponseWrite",
                data: {
                    name: $("#username").val(),
                },
                success: function(data) {
                    console.log("data=>" + data);
                },
                error: function(data) {
                    console.log("data=>" +data);
                }
            });
        }
        /*$(function () {
            $("#testGetDataByAjax").click(function() {
                /!*$.post("${pageContext.request.contextPath}/getUserList", function (data) {
                    debugger;
                    console.log(data);
                    /!*if (data != null && data != "" && data != undefined) {
                        let userTbody = $("#userTable>tbody");
                        let userTr = "";
                        for (let i = 0; i < data.length; i++) {
                            userTr = userTr + "<tr>"
                                + "<td>" + data[i].name + "</td>"
                                + "<td>" + data[i].age + "</td>"
                                + "<td>" + data[i].sex + "</td>";
                        }
                        userTbody.append(userTr);
                    }*!/
                });*!/
                $.post({
                    url: "${pageContext.request.contextPath}/getUserList",
                    data: {},
                    success: function(data) {
                        if (data != null && data != "" && data != undefined) {
                            let userTbody = $("#userTable>tbody");
                            let userTr = "";
                            for (let i = 0; i < data.length; i++) {
                                userTr = userTr + "<tr>"
                                    + "<td>" + data[i].name + "</td>"
                                    + "<td>" + data[i].age + "</td>"
                                    + "<td>" + data[i].sex + "</td>";
                            }
                            userTbody.append(userTr);
                        }
                    }
                });
            });
        })*/
    </script>
</head>
<body>
    <input type="text" id="username"/>
    <input type="button" onclick="testAjaxStatus()" value="测试Ajax返回status"/>
    <input type="button" onclick="testAjaxResponseWrite()" value="测试HttpServletResponse返回"/>
    <input type="button" id="testGetDataByAjax" value="testGetDataByAjax"/>
    <table id="userTable">
        <tr>
            <td>姓名</td>
            <td>年龄</td>
            <td>性别</td>
        </tr>
    </table>
</body>
</html>

20231015,

1.LearnAjaxController.java

@RequestMapping("/getUserList2")
    public List<User> getUserList2() {
        List<User> users = new ArrayList<>();
        users.add(new User("1", "狂神说Java", 3, "男"));
        users.add(new User("2", "狂神说Spring", 4, "男"));
        users.add(new User("3", "狂神说SpringMVC", 5, "男"));
        return users;
    }

2.Solve404Controller.java

@RequestMapping("/solve404")
public class Solve404Controller {
    @RequestMapping("/goTest2Page")
    public String goTest2Page() {
        return "testAjaxGetData";
    }
}

3.applicationContext.xml

<context:component-scan base-package="com.learnajax.controller"/>

4.testAjaxGetData.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.7.1.js"></script>
    <script>
        $(function () {
            $("#testGetDataByAjax").click(function() {
                $.post({
                    url: "${pageContext.request.contextPath}/getUserList2",
                    success: function(data) {
                        if (data != null && data != "" && data != undefined) {
                            let userTbody = $("#userTable>tbody");
                            let userTr = "";
                            for (let i = 0; i < data.length; i++) {
                                userTr = userTr + "<tr>"
                                    + "<td>" + data[i].name + "</td>"
                                    + "<td>" + data[i].age + "</td>"
                                    + "<td>" + data[i].sex + "</td>"
                                    + "</tr>";
                            }
                            console.log(userTr);
                            userTbody.append(userTr);
                        }
                    }
                });
            });
            $("#testGetDataByAjax3").click(function() {
                $.post("${pageContext.request.contextPath}/getUserList2", function (data) {
                    console.log(data);
                    if (data != null && data != "" && data != undefined) {
                        let userTbody = $("#userTable>tbody");
                        let userTr = "";
                        for (let i = 0; i < data.length; i++) {
                            userTr = userTr + "<tr>"
                                + "<td>" + data[i].name + "</td>"
                                + "<td>" + data[i].age + "</td>"
                                + "<td>" + data[i].sex + "</td>";
                        }
                        console.log(userTr);
                        userTbody.append(userTr);
                    };
                });
            });
        })
    </script>
</head>
<body>
    <input type="button" id="testGetDataByAjax" value="testGetDataByAjax"/>
    <br>
    <input type="button" id="testGetDataByAjax3" value="testGetDataByAjax3"/>
    <table id="userTable">
        <tr>
            <td>姓名</td>
            <td>年龄</td>
            <td>性别</td>
        </tr>
    </table>
</body>
</html>

5.效果:

 20231017,

1.LearnAjaxController.java

@RequestMapping("/checkUserNamePassword")
    public String checkUserNamePassword(String userName, String password) {
        if (userName != null && !userName.isEmpty()) {
            return "admin".equals(userName) ? "ok" : "用户名有误";
        } else if (password != null && !password.isEmpty()) {
            return "123456".equals(password) ? "ok" : "密码有误";
        }
        return "";
    }

2.login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.7.1.js"></script>
    <script>
        function checkUserName() {
            $.post({
                url: "${pageContext.request.contextPath}/checkUserNamePassword",
                data: {
                    "userName": $("#userName").val()
                },
                success: function (data) {
                    if (data!=""&&data!=null&&data!=undefined&&"ok"===data.toString()) {
                        $("#userInfo").css("color", "green");
                    } else {
                        $("#userInfo").css("color", "red");
                    }
                    $("#userInfo").html(data.toString());
                }
            })
        }
        function checkPwd() {
            $.post({
                url: "${pageContext.request.contextPath}/checkUserNamePassword",
                data: {
                    "password": $("#password").val()
                },
                success: function (data) {
                    if (data!=""&&data!=null&&data!=undefined&&"ok"===data.toString()) {
                        $("#pwdInfo").css("color", "green");
                    } else {
                        $("#pwdInfo").css("color", "red");
                    }
                    $("#pwdInfo").html(data.toString());
                }
            })
        }
    </script>
</head>
<body>
    <p>
        用户名:<input type="text" id="userName" value="请输入用户名" onblur="checkUserName()"/>
        <!-- span不支持自闭合 -->
        <span id="userInfo"></span>
    </p>
    <p>
        密码:<input type="password" id="password" value="请输入密码" onblur="checkPwd()"/>
        <!-- span不支持自闭合 -->
        <span id="pwdInfo"></span>
    </p>
</body>
</html>

3.applicationContext.xml

<!--SpringMVC处理jackson的JSON乱码问题-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

4.效果:

 

 

 

 

20231018,

1.TestInterceptorController.java

@RestController
public class TestInterceptorController {

    @GetMapping("/t2")
    public String t2() {
        System.out.println("=======kong:execute t2 method=======");
        return "ok";
    }
}

2.MyInterceptor.java

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("=======kong:before execute======");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("=======kong:after execute======");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("=======kong:clean======");
    }
}

3.applicationContext.xml

<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.kuang.config.MyInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

4.效果:

 控制台:

拦截器只保留 preHandler时:

若preHandle返回false,则t2方法不会被执行:

 

20231022,

1.请求转发和请求重定向

如下摘自 https://zhuanlan.zhihu.com/p/604721025 

请求转发(Forward):发生在服务端程序内部,当服务器端收到一个客户端的请求之后,会先将请求,转发给目标地址,再将目标地址返回的结果转发给客户端。而客户端对于这一切毫无感知的,这就好比,张三(客户端)找李四(服务器端)借钱,而李四没钱,于是李四又去王五那借钱,并把钱借给了张三,整个过程中张三只借了一次款,剩下的事情都是李四完成的,这就是请求转发。

请求重定向(Redirect):请求重定向指的是服务器端接收到客户端的请求之后,会给客户端返回了一个临时响应头,这个临时响应头中记录了,客户端需要再次发送请求(重定向)的 URL 地址,客户端再收到了地址之后,会将请求发送到新的地址上,这就是请求重定向。这就好像张三(客户端)找李四(服务器端)借钱,李四没钱,于是李四就告诉张三,“我没钱,你去王五那借“,于是张三又去王五家借到了钱,这就是请求重定向。

20231023,

1.LoginController.java

@Controller
@RequestMapping("/user")
public class LoginController {
    @RequestMapping("/goMain")
    public String goMain() {
        return "main";
    }
    @RequestMapping("/goLogin")
    public String goLogin() {
        return "login";
    }
    @RequestMapping("/login")
    public String login(HttpSession session, String userName, String password, Model model) {
        if (userName != null && !userName.isEmpty()
                && password != null && !password.isEmpty()
                && "tom".equals(userName)
                && "666".equals(password)) {
            session.setAttribute("userLoginInfo", userName);
            model.addAttribute("userName", userName);
            return "main";
        }
        return "login";
    }
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("userLoginInfo");
        return "login";
    }
}

2.LoginInterceptor.java

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getRequestURL().indexOf("goLogin") != -1
            || request.getRequestURL().indexOf("login") != -1) {
            return true;
        }
        HttpSession session = request.getSession();
        if (session.getAttribute("userLoginInfo") != null) {
            String userLoginInfo = (String) session.getAttribute("userLoginInfo");
            if (!userLoginInfo.isEmpty()) {
                return true;
            }
        }
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        return false;
    }
}

3.applicationContext.xml

<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.kuang.config.MyInterceptor"></bean>
        </mvc:interceptor>
        <mvc:interceptor>
            <mvc:mapping path="/user/**"/>
            <bean class="com.kuang.config.LoginInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

4.index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <p>
      <a href="${pageContext.request.contextPath}/user/goMain">首页</a>
    </p>
    <p>
      <a href="${pageContext.request.contextPath}/user/goLogin">登录页</a>
    </p>
  </body>
</html>

5.login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>登录页</h1>

    <form action="${pageContext.request.contextPath}/user/login" method="post">
        用户名:<input type="text" name="userName"/>
        密码:<input type="password" name="password"/>
        <input type="submit" value="登录"/>
    </form>
</body>
</html>

6.main.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>主页</h1>
    <span>${userName}</span>
    <p>
        <a href="${pageContext.request.contextPath}/user/logout">注销</a>
    </p>
</body>
</html>

7.效果:

默认index.jsp

 点击“首页”,LoginInterceptor判断session中没有登录信息,请求转发到登录页:

 用户登录成功后跳转到首页:

点击“注销”,清除session中的登录信息,跳转到登录页。

20231103,

1.pom.xml

<dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>

2.applicationContext.xml

<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
          id="multipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <!-- 10M -->
        <property name="maxUploadSize" value="10485760"/>
        <!-- 40K -->
        <property name="maxInMemorySize" value="40960"/>
    </bean>

3.FileController.java

@Controller
public class FileController {
    @RequestMapping("/upload")
    public String upload(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        String filename = file.getOriginalFilename();
        if (filename == null || filename.isEmpty()) {
            return "redirect:/index.jsp";
        }
        String path = request.getServletContext().getRealPath("upload");
        if (path!=null && !path.isEmpty()) {
            File realPath = new File(path);
            if (!realPath.exists()) {
                realPath.mkdir();
            }
            InputStream in = file.getInputStream();
            FileOutputStream out = new FileOutputStream(new File(realPath + File.separator + filename));
            int len = 0;
            byte[] buffer = new byte[1024];
            while((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
                out.flush();
            }
            out.close();
            in.close();
            return "redirect:/index.jsp";
        }
        return "redirect:/index.jsp";
    }

    @RequestMapping("/uploadByTransferTo")
    public String uploadByTransferTo(@RequestParam("fileForTransferTo") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        String filename = file.getOriginalFilename();
        if (filename != null && !filename.isEmpty()) {
            String path = request.getServletContext().getRealPath("/upload");
            if (path != null && !path.isEmpty()) {
                File realPath = new File(path);
                if (!realPath.exists()) {
                    realPath.mkdir();
                }
                file.transferTo(new File(realPath, filename));
            }
        }
        return "redirect:/index.jsp";
    }

    @RequestMapping("download")
    public String download(HttpServletResponse response, HttpServletRequest request) throws Exception {
        String path = request.getServletContext().getRealPath("/upload");
        if (path != null && !path.isEmpty()) {
            String filename = "zhangsan.png";
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            InputStream in = new FileInputStream(new File(path, filename));
            OutputStream out = response.getOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
                out.flush();
            }
            out.close();
            in.close();
        }
        return null;
    }
}

4.index.jsp

<form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
    <input type="file" name="file"/>
    <input type="submit" value="upload"/>
  </form>
  <form action="${pageContext.request.contextPath}/uploadByTransferTo" enctype="multipart/form-data" method="post">
    <input type="file" name="fileForTransferTo"/>
    <input type="submit" value="uploadByTransferTo"/>
  </form>
  <a href="${pageContext.request.contextPath}/download">download</a>

5.效果:

点击第一行“选择文件”,选择zhangsan.png,点击“upload”。点击第二行“选择文件” ,选择lisi.png,点击“uploadByTransferTo”。可以在upload文件夹下看到已成功上传的这两个文件。

点击第三行“download”,可以下载zhangsan.png:

20231104,

 

posted on 2023-07-12 19:53  平凡力量  阅读(50)  评论(0编辑  收藏  举报