IDEA上开发JavaEE
新建项目,使用spring项目创建,导入包
IDEA项目结构
模块-源 指定项目的文件夹作用
添加 Web 部署配置文件web.xml (创建完后下方会有Create Artifact)
构建(Artifact):
IDEA部署web项目,配置tomcat服务器
https://www.cnblogs.com/helldiriver/p/11352197.html
比如把config文件夹变成 资源 在代码里才能直接读取,否则要指定位置。
库 可以添加lib包,可直接导入外部包
Facet 构建、运行Spring的配置->会链接到applicationContext.xml
IDEA目录类型
Source roots (or source folders)
通过这个类指定一个文件夹,你告诉IntelliJ IDEA,这个文件夹及其子文件夹中包含的源代码,可以编译为构建过程的一部分。
Test source roots (or test source folders; shown as rootTest)
这些根类似于源根,但用于用于测试的代码(例如用于单元测试)。测试源文件夹允许您将与测试相关的代码与生产代码分开。
通常,源和测试源的编译结果被放置在不同的文件夹中。
Resource roots
用于应用程序中的资源文件(图像、各种配置XML和属性文件等)。
在构建过程中,资源文件夹的所有内容都复制到输出文件夹中,如下所示。
类似于源,您可以指定生成资源。您还可以指定输出文件夹中的文件夹,您的资源应该复制到。
Test resource roots
(或测试资源文件夹;如roottestresourceij;只有在java模块)是资源文件与您的测试源有关。在所有其他方面,这些文件夹类似于资源文件夹
spring项目结构
- lib
- applicationContext.xml ->spring的配置
- mybatis-config.xml ->mybatis的配置
- springmvc-config.xml ->
- WebContent/WEB-INF/web.xml
po类-> User 用户对象类
mapper(DAO层):
UserMapper.java 接口
UserMapper.xml
查询sql的语句
Service():
注入usermapper
传入参数,再传递给UserMapper执行sql查询。
IDEA快捷键
ctrl+/ 行注释
ctrl+shift+/区块注释
IDEA类注释和方法注释
文件头注释
打开file->setting->Editor->File and Code Templates->Includes->File Header
类注释:setting -> Editor -> File and Code Templates -> Files -> Class
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#parse("File Header.java")
/**
*@program: ${PROJECT_NAME}
*@ClassName :${NAME}
*@Description:${description}
*@Author :${USER}
*@Date :${YEAR}-${MONTH}-${DAY} ${HOUR}:${MINUTE}
**/
public class ${NAME} {
}
方法注释
idea 自动生成类注释和方法注释
https://segmentfault.com/a/1190000021208735
SpringMVC
IDEA建立Spring MVC Hello World 详细入门教程
https://www.cnblogs.com/wormday/p/8435617.html
Springmvc-config.xml / dispatcher-servlet.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
<?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">
<!-- 配置包扫描器,扫描@Controller注解的类 -->
<context:component-scan base-package="com.ocelot.controller"/>
<!-- 加载注解驱动 -->
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value=""/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:annotation-driven/>
</beans>
Controller
获取参数
SpringMVC中的Controller如何获取请求中的参数
https://blog.csdn.net/a909301740/article/details/80411114
-
直接在函数名写形参可以获取
-
public void getParamByReq(HttpServletRequest request, HttpServletResponse response) { String username = request.getParameter("username"); String password = request.getParameter("password"); System.out.println(username); System.out.println(password); }
AJAX请求问题 POST GET
Ajax请求的参数
https://www.cnblogs.com/whoknows1/p/9838498.html
$.ajax({
type:"POST",
url:"${pageContext.request.contextPath}/loginP",
data :{username:name,password:pass},
dataType : "json",
success: function(data){
console.log("data" + data);
if(data != null){
//zeroModal.success("登录成功!");
if(data.result =="success"){
$("#user_name").val("");
$("#password").val("");
$(location).attr('href', '${pageContext.request.contextPath}/calendar');
}else{
$("#login_form").removeClass('shake_effect');
setTimeout(function()
{
$("#login_form").addClass('shake_effect')
},1);
}
}
},
error:function(e){
$("#login_form").removeClass('shake_effect');
setTimeout(function()
{
$("#login_form").addClass('shake_effect')
},1);
}
});
Session问题
Spring MVC中Session的正确用法之我见
https://www.cnblogs.com/waytofall/p/3460533.html\1. Spring框架会在调用完Controller之后、渲染View之前检查Model的信息,并把@SessionAttributes()注释标明的属性加入session中
\2. @ModelAttribute在声明Controller的参数的时候,可以用来表明此参数引用某个存在在Model中的对象,如果这个对象已经存在于Model中的话(Model可以在调用Controller之前就已经保存有数据,这应该不仅仅因为HandlerInterceptor或者@ModelAttribute标记的方法已经显式的将一些对象加入到了Model对象中,也因为Spring会默认将一些对象加入到Model中,这一点很重要)。
\3. 如果Session中已经存在某个对象,那么可以直接使用ModelAttribute声明Controller的参数,在Controller中可以直接使用它。
可以用Model 也可以用ModelMap modelMap,HttpSession httpSession
跳转到另一个Controller
-
//使用 ModelAndView对象 @RequestMapping("/t1") public ModelAndView test1(){ ModelAndView mv = new ModelAndView(); mv.addObject("msg","modelandview is nice"); mv.setViewName("test"); return mv; } or return new ModelAndView("redirect:/index")
-
//使用springmvc 但不用视图解析器 @RequestMapping("/t3") public String test3(HttpServletRequest request){ request.setAttribute("msg","Controller Test3"); return "redirect:index.jsp"; //重定向不能携带参数值 }
-
//使用servletAPI //请求转发 request 可携带参数 //页面重定向 response 不能携带参数 @RequestMapping("/t2") public void test2(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { request.setAttribute("msg","servletAPI is nice"); //请求转发进行页面的跳转 request.getRequestDispatcher("index.jsp").forward(request,response); }
SpringMVC的学习
https://www.cnblogs.com/xbfchder/p/11320767.html
传入类型转换问题
Optional int parameter ‘reserveId’ is present but cannot be translated into a null value due to being declared as a primitive type.
原本用的是int,改成Integer也不行
@RequestMapping(value = "/reserve")
@ResponseBody
public Map<String, Object> reserveActivity(Integer reserveId,ModelMap map){...}
有说加注解@RequestPram的
Mybatis
- 应用程序找Mybatis要数据
- mybatis从数据库中找来数据
2.1 通过mybatis-config.xml 定位哪个数据库
2.2 通过Category.xml执行对应的select语句
2.3 基于Category.xml把返回的数据库记录封装在Category对象中
2.4 把多个Category对象装在一个Category集合中 - 返回一个Category集合
mybatis-config.xml
其作用主要是提供连接数据库用的驱动,数据库名称,编码方式,账号密码
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
以及别名,自动扫描com.how2java.pojo下的类型,使得在后续配置文件Category.xml中使用resultType的时候,可以直接使用Category,而不必写全com.how2java.pojo.Category
<typeAliases>
<package name="com.how2java.pojo"/>
</typeAliases>
映射Category.xml
<mappers>
<mapper resource="com/how2java/pojo/Category.xml"/>
</mappers>
完整如下:
<?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.how2java.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/how2java/pojo/Category.xml"/>
</mappers>
</configuration>
分别配置:
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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-db.properties4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<!--读取db.properties -->
<context:property-placeholder location="classpath:WEB-INF/db.properties"/>
<!-- 配置数据源 -->
<bean id="dataSource"
class="org.apache.commons.dbcp2.BasicDataSource">
<!--数据库驱动 -->
<property name="driverClassName" value="${jdbc.driver}" />
<!--连接数据库的url -->
<property name="url" value="${jdbc.url}" />
<!--连接数据库的用户名 -->
<property name="username" value="${jdbc.username}" />
<!--连接数据库的密码 -->
<property name="password" value="${jdbc.password}" />
<!--最大连接数 -->
<property name="maxTotal" value="${jdbc.maxTotal}" />
<!--最大空闲连接 -->
<property name="maxIdle" value="${jdbc.maxIdle}" />
<!--初始化连接数 -->
<property name="initialSize" value="${jdbc.initialSize}" />
</bean>
<!-- 事务管理器,依赖于数据源 -->
<bean id="transactionManager" class=
"org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!--开启事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--配置MyBatis工厂 -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据源 -->
<property name="dataSource" ref="dataSource" />
<!--指定核心配置文件位置 -->
<property name="configLocation" value="classpath:WEB-INF/mybatis-config_chinaday.xml"/>
</bean>
<!-- Mapper代理开发(基于MapperFactoryBean) -->
<bean id="chinadayMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="cn.nickdlk.activitycalendar_back.mapper.activityMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<context:component-scan base-package="cn.nickdlk.activitycalendar_back.service" />
<!-- Mapper代理开发(基于MapperScannerConfigurer) -->
<!-- <bean id='chinadaymapper' class="org.mybatis.spring.mapper.MapperScannerConfigurer">-->
<!-- <property name="basePackage" value="cn.nickdlk.javaee.mapper" />-->
<!-- </bean>-->
<!-- 开启扫描 -->
</beans>
mybatis-config_activity.xml
<?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="cn.nickdlk.javaee.po" />
</typeAliases>
<mappers>
<mapper resource="cn/nickdlk/javaee/mapper/chinadayMapper.xml" />
</mappers>
</configuration>
Mapper
配置了别名后,type里可以不用写完整的位置,别名指定package会扫描那个包里面的POJO类,以首字母小写命名。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.nickdlk.javaee.mapper.chinadayMapper">
<!--根据日期获取某日疫情数据-->
<select id="findDataByDay" parameterType="Date"
resultType="cn.nickdlk.javaee.po.chinaday">
select * from chinaday where _date = #{_date,jdbcType=DATE}
</select>
<!-- 插入疫情数据 -->
<insert id="addChinadayDate" parameterType="cn.nickdlk.javaee.po.chinaday">
insert into chinaday
values(#{_date},#{confirm},#{suspect},#{dead},#{heal},#{nowConfirm},#{nowSevere},#{importedCase},#{deadRate},#{healRate},#{noInfect})
</insert>
</mapper>
namespace指定命名空间
id 属性是在映射文件中的唯一标识
parameterType 属性用于指定传入参数的类型
resultType属性用于指定返回结果的类型
<resultMap id="给ID名" type="实体类" >
<result column="数据库字段名" property="实体类属性" jdbcType="数据库字段类型" />
</resultMap>
传入类型
MyBatis的传入参数parameterType类型分两种
- 基本数据类型:int、string、long、Date; #{参数} 获取参数中的值
- 复杂数据类型:类(JavaBean、Integer等)和Map #{属性名} ,map中则是#{key}
多参数:
Mybatis (ParameterType) 如何传递多个不同类型的参数
https://www.jianshu.com/p/d977eaadd1ed
方法一:不需要写parameterType参数
public List getXXXBeanList(String xxId, String xxCode);
由于是多参数那么就不能使用parameterType, 改用#{index}是第几个就用第几个的索引,索引从0开始
方法二:基于注解(最简单)
public List getXXXBeanList(@Param(“id”)String id, @Param(“code”)String code);
由于是多参数那么就不能使用parameterType, 这里用@Param来指定哪一个
还有用Map、List封装
转义字符
原符号 替换符号
< <
<= <=
> >
>= >=
& &
' '
" "
<![CDATA[ 这里面是sql语句. 大于号.小于号 ]]> 用这个把大于号.小于号包含起来就可以了
比较时间
<if test="paramsMap.beginDate != null and paramsMap.beginDate != '' ">
and srd.plan_drop_time <![CDATA[>=]]> #{paramsMap.beginDate}
</if>
<if test="paramsMap.endDate != null and paramsMap.endDate != '' ">
and srd.plan_drop_time <![CDATA[<=]]> #{paramsMap.endDate}
</if>
<if test="beginDate!=null and beginDate!=''">
<![CDATA[ a.activity_time >= DATE_FORMAT(#{beginDate}, '%Y-%m-%d') ]]>
</if>
<if test="endDate!=null and endDate!=''">
<![CDATA[ and a.activity_time <= DATE_FORMAT(#{endDate}, '%Y-%m-%d') ]]>
</if>
插入 主键自增 返回自增ID
-
设置表的id(此id必须是int类型),设置为auto_increment自增类型 create table Student( Student_ID int primary key identity(1,1), Student_Name varchar2(10) NOT NULL, Student_Age number(2) NOT NULL ); //插入的代码直接忽略主键 insert into student(student_name,student_age) values('zhangsan',20);
-
//mysql设置使用自增的主键生成策略,并能获取生成的主键值 <insert id="xxx" useGeneratedKeys="true" keyProperty="id">insert into tb(a,b,c) values(#{a},#{b},#{c})</insert> useGeneratedKeys="true" 设置使用自增主键; keyProperty="id" 设置自增主键返回字段(用户在插入数据之后获取相应主键) 字段要与PO类对应
获取自增:
User registerUser = new User(); registerUser.setNick(username); registerUser.setEmail(email); userMapper_.insertUser(registerUser); System.out.println("自增ID "+registerUser.getUserId());
出现个错误:
Mapper method ‘cn.nickdlk.activitycalendar_back.mapper.userMapper.insertUser’ has an unsupported return type: class cn.nickdlk.activitycalendar_back.po.User
delete 、update、insert是不需要设置返回类型的,都是默认返回一个int,所以,此处应该对返回类型进行修改
将Mapper的返回类型改为int或long,增加@Param注解,
public Long insertUser( @Param("User")User registerUser);
<insert id="insertUser" parameterType="map" useGeneratedKeys="true" keyProperty="User.userId">
INSERT INTO user (
user_authority, school, major, classname, name, idnum, phonenum,
email, nick, address, activity_ing, activity_reserve, activity_reserve_ing, activity_done, activity_points_extension_get,
activity_points_credit_get, activity_points_service_get, activity_award_get, activity_publish
) VALUES (
#{User.userAuthority},
#{User.school},
#{User.major},
#{User.classname},
#{User.name},
#{User.idnum},
#{User.phonenum},
#{User.email},
#{User.nick},
#{User.address},
#{User.activityIng},
#{User.activityReserve},
#{User.activityReserveIng},
#{User.activityDone},
#{User.activityPointsExtensionGet},
#{User.activityPointsCreditGet},
#{User.activityPointsServiceGet},
#{User.activityAwardGet},
#{User.activityPublish}
)
</insert>
MyBatis在insert插入对象时,返回自增主键失败
https://blog.csdn.net/daima_caigou/article/details/88582856
错误
java.lang.IllegalArgumentException: invalid comparison: java.util.Date and java.lang.String
解决: mybatis-3.3.0 不能将时间跟空字符串比较
改为:
<if test="beginDate!=null">
<![CDATA[ a.activity_time >= DATE_FORMAT(#{beginDate}, '%Y-%m-%d') ]]>
</if>
<if test="endDate!=null">
<![CDATA[ and a.activity_time <= DATE_FORMAT(#{endDate}, '%Y-%m-%d') ]]>
</if>
mybatis异常invalid comparison: java.util.Date and java.lang.String(date和string无法比较)
https://blog.csdn.net/a443512430/article/details/78028604
测试
根据配置文件mybatis-config.xml得到sqlSessionFactory 。
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
然后再根据sqlSessionFactory 得到session
SqlSession session=sqlSessionFactory.openSession();
最后通过session的selectList方法,调用sql语句listCategory。listCategory这个就是在配置文件Category.xml中那条sql语句设置的id。
执行完毕之后,得到一个Category集合,遍历即可看到数据。
List<Category> cs = session.selectList("listCategory");
for (Category c : cs) {
System.out.println(c.getName());
}
Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource activityMapper.xml
mybatis错误——java.io.IOException: Could not find resource com/xxx/xxxMapper.xml
https://blog.csdn.net/u010648555/article/details/70880425
将mapper.xml移动到config或其他resource文件夹下
Mapped Statements collection does not contain value for cn.nickdlk.activitycalendar_back.mapper
1、mapper.xml中没有加入namespace
2、mapper.xml中的方法和接口mapper的方法不对应 (接口方法)
3、mapper.xml没有加入到mybatis-config.xml中(即总的配置文件),例外:配置了mapper文件的包路径的除外
4、mapper.xml文件名和所写的mapper名称不相同。
使用service测试
这个是访问Spring的service,再在service里访问数据库,service里是用自动注入的方式获取mybatis。
ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext.xml");
chinadayService chinadayService_ = (chinadayService)act.getBean("t");
Activity activity_ = new Activity();
activity_.setActivityAward("2");
activityService_.addActivity(activity_);
通配符的匹配很全面, 但无法找到元素 ‘context:property-placeholder’ 的声明。
配置文件错误 看行数查找有没写错包名
or 复制别的头来用
JSP
SpringMVC session 传递给 JSP
- Controller里访问函数里添加 ModelMap map
- 在控制器上加SessionAttributes注解,把放到model中的对象再放置到Session中
- JSP访问session
Controller:
@Controller
@SessionAttributes({"uname"})
public class ActivityController {
@Autowired
private activityService activityService_;
@RequestMapping(value = "/calendar")
public String calendar(ModelMap map){
System.out.println("calendar");
map.addAttribute("uname", "testssss");
return "pages/calendar/index";
}
}
jap 用 ${key}来接收该值:
<h2>A,${sessionScope.uname }</h2
<h2>B,${uname }</h2
Controller传值给JSP页面 | Voyager-1
http://alanli7991.github.io/2016/08/01/Controller%E4%BC%A0%E5%80%BC%E7%BB%99JSP%E9%A1%B5%E9%9D%A2/
非EL表达式:
如果是对象: 先引入
<%@ page import="java.util.*,cn.nickdlk.activitycalendar_back.po.Activity"%>
再获取
<%
Activity res = (Activity)request.getSession().getAttribute("activityDetail");
%>
jsp引入外部js找不到路径
绝对路径的方式 ${pageContext.request.contextPath} 引入js文件
web文件夹下的js/css文件不输出
jsp引用了js,但是不能生效,路径确定无误,直接访问发现404。查看out文件夹没有输出js文件
解决:将含js的目录设置为源目录
idea下jsp文件使用Link标签无法引入js,css文件【已解决】
https://blog.csdn.net/nbcsdn/article/details/99824615
无法访问静态资源
还是jsp无法找到js的问题
需要设置SpringMVC对静态资源的访问。
解决方法:
在dispatcher-servlet.xml(springMVC-servlet配置)里添加:
<mvc:resources location="pages/" mapping="/pages/**"/>
意思是将location目录下的文件在访问时交给服务器处理,mapping为映射的目录
idea中JSP页面不能访问静态资源(图片,js,css)
https://www.cnblogs.com/hhhd/p/6800325.html
缺少包javax.servlet.jsp.JspWriter
在项目配置-模块-导出添加lib 把Tomcat的包勾上
使用JSON
使用Jackson,导入包
/**
* Spring MVC Controller
* 接收页面请求的JSON数据
* @param user
* @return 返回JSON格式结果
*/
@RequestMapping(value = "/testJSON")
@ResponseBody
public User testJson(@RequestBody User user){
System.out.println(user);
return user;
}
@Test
public void tester() throws IOException {
/* —————————————————— 准备测试数据 —————————————————— */
Person person1 = new Person();
person1.setName("我没有三颗心脏1");
person1.setAge(21);
Person person2 = new Person();
person2.setName("我没有三颗心脏2");
person2.setAge(21);
Person person3 = new Person();
person3.setName("我没有三颗心脏3");
person3.setAge(21);
List<Person> list = new ArrayList<>();
list.add(person1);
list.add(person2);
list.add(person3);
/* ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现的 */
ObjectMapper mapper = new ObjectMapper();
/* —————————————————— 简单的Bean转为JSON —————————————————— */
String jsonString = mapper.writeValueAsString(person1);
System.out.println("简单的Bean转为JSON:" + jsonString);
/* —————————————————— JSON转为简单Bean —————————————————— */
Person personFromJson = mapper.readValue(jsonString, Person.class);
System.out.println("JSON转为简单Bean:" + personFromJson.toString());
/* —————————————————— 带泛型的List转JSON —————————————————— */
String jsonStringFromList = mapper.writeValueAsString(list);
System.out.println("带泛型的List转JSON:" + jsonStringFromList);
/* —————————————————— JSONz转为带泛型的List —————————————————— */
// List<LinkedHashMap<String, Person>> retList = mapper.readValue(jsonStringFromList, List.class);
// for (int i = 0; i < retList.size(); i++) {
// Map<String, Person> map = retList.get(i);
// Set<String> set = map.keySet();
// for (Iterator<String> it = set.iterator(); it.hasNext();) {
// String key = it.next();
// System.out.println(key + ":" + map.get(key));
// }
// }
/* —————————————————— JSONz转为Array数组 —————————————————— */
Person[] retList = mapper.readValue(jsonStringFromList, Person[].class);
for (int i = 0; i < retList.length; i++) {
System.out.println(retList[i].toString());
}
}
------------------结果如下------------------
简单的Bean转为JSON:{"name":"我没有三颗心脏1","age":21}
JSON转为简单Bean:名字为我没有三颗心脏1,年龄21
带泛型的List转JSON:[{"name":"我没有三颗心脏1","age":21},{"name":"我没有三颗心脏2","age":21},{"name":"我没有三颗心脏3","age":21}]
名字为我没有三颗心脏1,年龄21
名字为我没有三颗心脏2,年龄21
名字为我没有三颗心脏3,年龄21
JavaWeb中使用JSON
https://www.cnblogs.com/wmyskxz/p/9099693.html
错误:
错误运行’Tomcat 9.0.33’: Can’t find catalina.jar
构建配置里配置Tomcat
Could not autowire. No beans of ‘UserMapper’ type found.
applicationContext.xml 配置mapper指定错误导致的
<!-- 配置mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.nickdlk.mapper"/>
</bean>
注意包的位置应该指定SQL的位置
访问JSP没有页面
源服务器未能找到目标资源的表示或者是不愿公开一个已经存在的资源表示。
Tomcat在控制台中文乱码
在Tomcat根目录下“conf”子目录下的“logging.properties”文件中所有的“encoding = UTF-8”都修改为“encoding = GBK”,使其支持中文,然后保存重启Tomcat服务器即可解决
idea调试SpringMvc, 出现:java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener错误
项目结构的构件Artifact 查看输出的WEB-INF 下 lib 是否有所需的包 和包是否重复(版本不同)
idea java classpath路径的位置
target->classes即为classpath,任何我们需要在classpath前缀中获取的资源都必须在target->classes文件夹中找到。但是在idea项目中只有被标记为Resource Folders的文件夹下的文件才会被添加至target->classes。
Tomcat下的Web应用有两个预置的classpath :
WEB-INF/classes
WEB-INF/lib
org.apache.catalina.core.ApplicationContext.log No Spring WebApplicationInitializer types detected on classpath
- 实体类添加空的构造函数
2. - 查看classes下的目录下的web.xml
web.xml找不到classpath路径,把左边的在src目录下的文件放到资源目录下。
java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config
主要是因为缺少standard.jar和jstl.jar所致:
直接下载jar包(没有使用maven管理的项目(在下面链接下载jar包,放到项目lib下)
http://repo2.maven.org/maven2/javax/servlet/jstl/
http://repo2.maven.org/maven2/taglibs/standard/
org.apache.catalina.core.StandardContext.listenerStart 配置应用程序监听器[org.springframework.web.context.ContextLoaderListener]错误
org.apache.catalina.core.StandardContext.listenerStart Error configuring
https://blog.csdn.net/ajiu_9999/article/details/91543191
就是在项目结构的构件里将右边的可用元素右键 置于output root
也就是将lib包一同部署
Could not open ServletContext resource
部署后Tomcat Localhost Log里的错误:
严重 [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Servlet.init() for servlet [dispatcher] threw exception
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/dispatcher-servlet.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource
…………
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/dispatcher-servlet.xml]
web.xml配置的问题
没有指定servlet.xml的位置 默认找WEB-INF目录下去了 (?)
在web.xml里的servlet添加指定位置
<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:config/springmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
.0.1] org.apache.catalina.core.ApplicationContext.log Servlet.init() for servlet [dispatcher] threw exception
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/dispatcher-servlet.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource
…………
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/dispatcher-servlet.xml]
web.xml配置的问题
没有指定servlet.xml的位置 默认找WEB-INF目录下去了 (?)
在web.xml里的servlet添加<init-param>指定位置
<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:config/springmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>