springmvc练习:@RestController,@RequestMapping, @RequestParam, @PathVariable

main
lsrong 2 years ago
parent fa2fbf70c3
commit 3985475cdf

@ -0,0 +1,38 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

@ -0,0 +1,129 @@
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.msb</groupId>
<artifactId>springmvc_01</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>springmvc_01 Maven Webapp</name>
<properties>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<!--spring核心容器包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.5</version>
</dependency>
<!--spring切面包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.5</version>
</dependency>
<!--aop联盟包-->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<!--德鲁伊连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<!--springJDBC包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.5</version>
</dependency>
<!--spring事务控制包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.5</version>
</dependency>
<!--spring orm 映射依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.3.5</version>
</dependency>
<!--Apache Commons日志包-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!--log4j2 日志-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.14.0</version>
<scope>test</scope>
</dependency>
<!--lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<!--spring test测试支持包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.5</version>
<scope>test</scope>
</dependency>
<!--junit5单元测试-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<!--springMVC支持包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.5</version>
</dependency>
<!--jsp 和Servlet 可选-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
</dependencies>
</project>

@ -0,0 +1,29 @@
package com.msb.controller;
import com.msb.pojo.Person;
import com.msb.pojo.Pet;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
//@Controller
@RestController // @Controller+@ResponseBody两个注解的结合
public class AjaxController {
/*
* @ResponseBody
* 1,
* 2使ObjectMapperJSON
*/
@RequestMapping("/testAjax")
// @ResponseBody
public Pet testAjax(Person person){
System.out.println(person);
return new Pet("Tom", "Cat");
}
}

@ -0,0 +1,46 @@
package com.msb.controller;
import com.msb.pojo.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
public class DataController {
/*
* 使HttpServletRequest javax.servlet
**/
@RequestMapping("/getParamByServlet")
public String getParamByServlet(HttpServletRequest req, HttpServletResponse resp){
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("username: "+username+" password: "+password);
return "success";
}
/*
* HttpServletRequest SpringMVC,
*
* ,@RequestParma
* */
@RequestMapping("/getParamByArgName")
public String getParamByArgName(@RequestParam("username")String username, @RequestParam("password")String password){
System.out.println("username: "+username+" password: "+password);
return "success";
}
@RequestMapping("/getDataByPojo")
public String getDataByPojo(Person p){
System.out.println("Person:"+ p);
return "success";
}
}

@ -0,0 +1,56 @@
package com.msb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class PathController {
// restful 请求链接地址,绑定参数
@RequestMapping("/testPathVar/{id}/{username}")
public String testPathValue(@PathVariable("id") Integer id, @PathVariable("username") String username){
System.out.println("id:"+id);
System.out.println("username:"+username);
System.out.println("testPathValue");
return "success";
}
// get请求
@RequestMapping(value = "/testGet/{id}", method = RequestMethod.GET)
public String testGet(@PathVariable("id") Integer id){
System.out.println("id:"+id);
System.out.println("testGet");
return "success";
}
// post请求
@RequestMapping(value = "/testPost/{id}", method = RequestMethod.POST)
public String testPost(@PathVariable("id") Integer id){
System.out.println("id:"+id);
System.out.println("testPost");
return "success";
}
// put请求
@RequestMapping(value = "/testPut/{id}", method = RequestMethod.PUT)
public String testPut(@PathVariable("id") Integer id){
System.out.println("id:"+id);
System.out.println("testPut");
return "success";
}
// delete请求
@RequestMapping(value = "/testDelete/{id}", method = RequestMethod.DELETE)
public String testDelete(@PathVariable("id") Integer id){
System.out.println("id:"+id);
System.out.println("testDelete");
return "success";
}
}

@ -0,0 +1,79 @@
package com.msb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
public class ResponseController {
@RequestMapping("testVoid")
public void testVoid(){
System.out.println("void controller");
}
@RequestMapping("demo1")
public void testDemo1(HttpServletRequest req, HttpServletResponse resp) throws Exception {
// 请求转发
// req.getRequestDispatcher("/forwardPage.jsp").forward(req, resp);
//响应重定向
resp.sendRedirect(req.getContextPath()+"/redirectPage.jsp");
}
/*
* DispatcherServlet
* forward: ,
* forward,
* */
@RequestMapping("demo2")
public String demo2(){
// "forward:forwardPage.jsp"
return "/forwardPage.jsp";
}
/*
* DispatcherServlet
* redirect: ,
* redirect,
* /.
* */
@RequestMapping("demo3")
public String demo3(){
return "redirect:redirectPage.jsp";
}
// View 转发
@RequestMapping("demo4")
public View demo4(HttpServletRequest request){
View view = null;
// view = new InternalResourceView("/forwardPage.jsp"); // 请求转发
view = new RedirectView(request.getContextPath() + "/redirectPage.jsp"); // 响应重定向
return view;
}
// ModelAndView
@RequestMapping("demo5")
public ModelAndView demo5(HttpServletRequest request){
ModelAndView mv = new ModelAndView();
// 请求转发
// mv.setViewName("forward:forwardPage.jsp");
// mv.setView(new InternalResourceView("/forwardPage.jsp"));
// 响应重定向
// mv.setViewName("redirect:redirectPage.jsp");
mv.setView(new RedirectView(request.getContextPath()+"/redirectPage.jsp"));
return mv;
}
}

@ -0,0 +1,31 @@
package com.msb.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
private String pname;
private String page;
private Integer gender;
private Integer[] hobby;
// 日期转换
// @DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birthday;
// List参数
private List<Pet> petList;
// Map参数
private Map<String, Pet> petMap;
}

@ -0,0 +1,13 @@
package com.msb.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Pet {
private String petName;
private String petType;
}

@ -0,0 +1,22 @@
package com.msb.util;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateConverter implements Converter<String, Date> {
private final SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyy-MM-dd");
@Override
public Date convert(String s) {
Date date = null;
try {
date = dateFormat.parse(s);
} catch (ParseException e) {
throw new RuntimeException("Failed to convert date");
}
return date;
}
}

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="Console" />
</Root>
</Loggers>
</Configuration>

@ -0,0 +1,51 @@
<?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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<!--配置spring包扫描-->
<context:component-scan base-package="com.msb"/>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- <property name="prefix" value="/WEB-INF/view/"/>-->
<!-- <property name="suffix" value=".jsp"/>-->
</bean>
<!-- 配置数据转换工厂-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<array>
<bean class="com.msb.util.StringToDateConverter"/>
</array>
</property>
</bean>
<!--这里配置转换服务工厂-->
<mvc:annotation-driven conversion-service="conversionService"/>
<!--配置静态资源放行-->
<!--mapping url中的路径 location= 对应的路径到项目中哪个目录中去找对应的资源-->
<mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
<!--<mvc:resources mapping="/css/**" location="/css/"></mvc:resources>
<mvc:resources mapping="/img/**" location="/img/"></mvc:resources>-->
<!--<mvc:resources mapping="/static/**" location="/static/"></mvc:resources>-->
</beans>

@ -0,0 +1,16 @@
<%--
Created by IntelliJ IDEA.
User: lsrong
Date: 2023/11/10
Time: 22:29
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>
this is success page, good
</body>
</html>

@ -0,0 +1,54 @@
<?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">
<!--配置hiddenHttpMethodFilter ,将POST请求转换为PUT或者DELETE请求-->
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Spring 中提供的字符编码过滤器-->
<filter>
<filter-name>encFilter</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>encFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--初始化参数,指定springMVC配置文件的路径-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<!--匹配所有的资源,除了JSP-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

@ -0,0 +1,20 @@
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery.min.js"></script>
<script>
$(function(){
$("#btn").click(function(){
$.get("testAjax",{pname:"晓明",page:"10"},function(data){
console.log(data)
})
})
})
</script>
</head>
<body>
<input id="btn" type="button" value="testJSON">
</body>
</html>

@ -0,0 +1,64 @@
<%--
Created by IntelliJ IDEA.
User: lsrong
Date: 2023/11/10
Time: 22:47
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>
<form action="getParamByServlet">
<p>getParamByServlet</p>
<p>用户名<input type="text" name="username"></p>
<p>密码<input type="password" name="password"></p>
<input type="submit">
</form>
<hr>
<form action="getParamByArgName">
<p>getParamByArgName</p>
<p>用户名<input type="text" name="username"></p>
<p>密码<input type="password" name="password"></p>
<input type="submit">
</form>
<hr>
<form action="getDataByPojo">
<p>getDataByPojo</p>
<p>姓名<input type="text" name="pname"></p>
<p>年龄<input type="text" name="page"></p>
<p>性别:
<input type="radio" name="gender" value="1" >男
<input type="radio" name="gender" value="0" >女
</p>
<p>爱好
<input type="checkbox" name="hobby" value="1"> 篮球
<input type="checkbox" name="hobby" value="2"> 足球
<input type="checkbox" name="hobby" value="3"> 羽毛球
</p>生日
<p>
<input type="text" name="birthday">
</p>
宠物List:
<p>
宠物1: 名字:<input type="text" name="petList[0].petName" >类型:<input type="text" name="petList[0].petType">
</p>
<p>
宠物2: 名字:<input type="text" name="petList[1].petName" >类型:<input type="text" name="petList[1].petType">
</p>
宠物Map:
<p>
宠物1: 名字:<input type="text" name="petMap['a'].petName" >类型:<input type="text" name="petMap['a'].petType">
</p>
<p>
宠物2: 名字:<input type="text" name="petMap['b'].petName" >类型:<input type="text" name="petMap['b'].petType">
</p>
<input type="submit">
</form>
</body>
</html>

@ -0,0 +1,16 @@
<%--
Created by IntelliJ IDEA.
User: lsrong
Date: 2023/11/10
Time: 23:21
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>
this is a forward page
</body>
</html>

@ -0,0 +1,5 @@
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

File diff suppressed because one or more lines are too long

@ -0,0 +1,35 @@
<%--
Created by IntelliJ IDEA.
User: lsrong
Date: 2023/11/10
Time: 22:29
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>
<form action="testGet/10" method="GET">
<input type="submit" value="testGET">
</form>
<hr>
<form action="testPost/10" method="POST">
<input type="submit" value="testPost">
</form>
<hr>
<form action="testPut/10" method="POST">
<input type="hidden" name="_method" value="PUT">
<input type="submit" value="testPut">
</form>
<hr>
<form action="testDelete/10" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="submit" value="testDelete">
</form>
<hr>
</body>
</html>

@ -0,0 +1,16 @@
<%--
Created by IntelliJ IDEA.
User: lsrong
Date: 2023/11/10
Time: 23:21
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>
this is a redirect page
</body>
</html>
Loading…
Cancel
Save