SpringMVC-注解版本

2023-12-13 11:42:46

依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
</dependency>

web.xml

<?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">
    <!--1.注册DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--关联springmvc的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!--启动级别-1-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--/ 匹配所有的请求,不包括.jsp-->
        <!--/* 匹配所有的请求,包括.jsp-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--POST请求容易乱码-->
	<!--配置Spring-MVC的乱码过滤器-->
	<filter>
	    <!--过滤器名称-->
	    <filter-name>encoding</filter-name>
	    <!--映射Spring提供的乱码过滤器,也可以映射自定义过滤器-->
	    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	</filter>
	<filter-mapping>
	    <filter-name>encoding</filter-name>
	    <!--'/*'过滤所有的请求,'/'不会过滤.jsp-->
	    <url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

关联springmvc的配置文件

<?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
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--自动扫描包,让注解生效-->
    <context:component-scan base-package="org.example.controller"/>
    <!--让mvc不处理静态资源-->
    <mvc:default-servlet-handler/>
    <!--支持mvc注解驱动,提供映射器和适配器-->
    <!--<mvc:annotation-driven/>--><!--不添加任何配置-->
	<mvc:annotation-driven><!--添加配置,处理JSON乱码-->
	    <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 id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!--后缀-->
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Controller

// 添加注解将类交给spring接管,完成映射,请求会来到这里匹配
// @Controller:类中的方法返回值如果为字符串,会被视图解析器解析
// @RestController:不会被视图解析器解析,只会返回字符串
@Controller
// 这里配置请求路径需要先拼这个父路径,再拼子路径
@RequestMapping("/hello")
public class HelloController {
    // 配置请求路径
    // 不同请求方式:@GetMapping、@PostMapping、@DeleteMapping、@PutMapping
    // @RequestMapping支持所有请求方式
    @RequestMapping("/h1")
    public String hello1(Model model){
        // 封装数据
        model.addAttribute("msg","hello");
        // 请求转发
        return "hello";
        // 请求转发地址栏不会变,重定向会变化
	    // 没有视图解析器的请求转发:return "forward:/index.jsp";
	    // 重定向不会被视图解析器解析:return "redirect:/index.jsp";
    }
    // @PathVariable注解支持RestFul风格
    @RequestMapping(value = "/h2/{b}/{a}",method = RequestMethod.POST)
    public String hello2(@PathVariable int a,@PathVariable int b, Model model){
        return "hello";
    }
    // @RequestParam可以给请求参数起别名,用别名发送请求
    // 如果请求参数名是对象属性名,那么就会给属性赋值
    @RequestMapping("/h3")
    public String hello3(@RequestParam("username") String name, Model model){
        return "hello";
    }
	// 注解方式处理JSON乱码
	// @RequestMapping(value = "/j1",produces = "application/json;charset=utf8")
	@RequestMapping("/j1")
	@ResponseBody // 不走视图解析器,返回字符串
	public String json1() throws JsonProcessingException {
	    return new ObjectMapper().writeValueAsString(new User(1,"张三",20));
	}
}

通用编码过滤器

// 解决get和post请求 全部乱码的过滤器
public class GenericEncodingFilter implements Filter {
    @Override
    public void destroy() {}
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException{
        //处理response的字符编码
        HttpServletResponse myResponse=(HttpServletResponse) response;
        myResponse.setContentType("text/html;charset=UTF-8");
        // 转型为与协议相关对象
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // 对request包装增强
        HttpServletRequest myrequest = new MyRequest(httpServletRequest);
        chain.doFilter(myrequest, response);
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
}
//自定义request对象,HttpServletRequest的包装类
class MyRequest extends HttpServletRequestWrapper {
    private HttpServletRequest request;
    //是否编码的标记
    private boolean hasEncode;
    //定义一个可以传入HttpServletRequest对象的构造函数,以便对其进行装饰
    public MyRequest(HttpServletRequest request) {
        super(request);// super必须写
        this.request = request;
    }
    // 对需要增强方法 进行覆盖
    @Override
    public Map getParameterMap() {
        // 先获得请求方式
        String method = request.getMethod();
        if (method.equalsIgnoreCase("post")) {
            // post请求
            try {
                // 处理post乱码
                request.setCharacterEncoding("utf-8");
                return request.getParameterMap();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else if (method.equalsIgnoreCase("get")) {
            // get请求
            Map<String, String[]> parameterMap = request.getParameterMap();
            if (!hasEncode) { // 确保get手动编码逻辑只运行一次
                for (String parameterName : parameterMap.keySet()) {
                    String[] values = parameterMap.get(parameterName);
                    if (values != null) {
                        for (int i = 0; i < values.length; i++) {
                            try {
                                // 处理get乱码
                                values[i] = new String(values[i]
                                        .getBytes("ISO-8859-1"), "utf-8");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                hasEncode = true;
            }
            return parameterMap;
        }
        return super.getParameterMap();
    }
    //取一个值
    @Override
    public String getParameter(String name) {
        Map<String, String[]> parameterMap = getParameterMap();
        String[] values = parameterMap.get(name);
        if (values == null) {
            return null;
        }
        return values[0]; // 取回参数的第一个值
    }
    //取所有值
    @Override
    public String[] getParameterValues(String name) {
        Map<String, String[]> parameterMap = getParameterMap();
        String[] values = parameterMap.get(name);
        return values;
    }
}

文章来源:https://blog.csdn.net/h_e_l_l_o_______/article/details/134902853
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。