SpringMVC(二)注解例子—Java基础篇

1.遇到的问题

ClassNotFoundException异

首先:替换相应的jackson包

其次:修改spring -mvc中jackson的相应配置

2.pow.xml

<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.jike</groupId>
<artifactId>SpringMVC</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringMVC Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>


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


<!-- https://mvnrepository.com/artifact/org.springframework/spring-oxm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>




<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>




<!-- 原来的1.x版本只有两个包 -->
<!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-core-asl -->
<!-- <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> 
<version>1.9.13</version> </dependency> -->
<!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-lgpl -->
<!-- <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-lgpl</artifactId> 
<version>1.9.13</version> </dependency> -->


<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>


</dependencies>
<build>
<finalName>SpringMVC</finalName>
</build>
</project>


3.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">


<display-name>Archetype Created Web Application</display-name>


<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-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>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SpringMvc</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>


<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>

4.spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
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
      http://www.springframework.org/schema/util 
      http://www.springframework.org/schema/util/spring-util.xsd">


<!--自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.jike.*" />


<!-- 扩充了注解驱动,可以将请求参数绑定到控制参数 -->
<!-- <mvc:annotation-driven /> -->


<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> 
<property name="messageConverters"> <util:list id="beanList"> <ref bean="mappingJacksonHttpMessageConverter" 
/> </util:list> </property> </bean> -->




<!-- <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> 
<property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> 
</list> </property> </bean> -->
<!-- <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> 
<property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> 
</list> </property> </bean> -->




<!-- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
</bean>
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</list>
</property>
</bean>
</beans>

5.index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<a href="loginPage.html">登录</a>
</body>
</html>

6.login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<form action="<%=path%>/doLogin.html" method="post">
username: <input type="text" name="username" /><br /> password: <input
type="password" name="password" /><br /> <input type="submit"
value="submit" /> <input type="reset" value="reset" />
</form>
<font color="red">${error}</font>
</body>
</html>

7.success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<h3>${user.username},恭喜您,登录成功!</h3>
<a href="doLogout.html">退出</a>
</body>
</html>

8.LoginController.java

package com.jike.controller;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;


import com.jike.bean.User;
import com.jike.service.LoginService;


@Controller
@SessionAttributes("user")
public class LoginController {


@Resource
LoginService service;


@RequestMapping("loginPage")
public String toLoginPage() {
return "login.jsp";
}


@RequestMapping(value = "doLogin", method = RequestMethod.POST)
public String doLogin(@RequestParam String username, @RequestParam String password, HttpServletRequest request,
ModelMap map) {


String url = "";


try {
User user = service.doLogin(username, password);
map.put("user", user);
url = "success.jsp";
} catch (Exception e) {
request.setAttribute("error", e.getMessage());
url = "login.jsp";
}


return url;
}


@RequestMapping("doLogout")
public String doLogout(SessionStatus status) {
status.setComplete();
return "login.jsp";
}
}

9.LoginService.java

package com.jike.service;


import javax.annotation.Resource;


import org.springframework.stereotype.Service;


import com.jike.bean.User;
import com.jike.dao.UserDao;


@Service
public class LoginService {


@Resource
UserDao dao;


public User doLogin(String username, String password) throws Exception {


if (username == null || "".equals(username)) {
throw new Exception("用户名不能为空");
}


if (password == null || "".equals(password)) {
throw new Exception("密码不能为空!");
}


User user = dao.selectByUserName(username);
if (user == null) {
throw new Exception("用户名不存在!");
}


if (!user.getUsername().equals(username) || !user.getPassword().equals(password)) {
throw new Exception("用户名或密码错误!");
}


return user;
}


}

10.UserDao.java

package com.jike.dao;


import org.springframework.stereotype.Repository;


import com.jike.bean.User;


@Repository
public class UserDao {


public User selectByUserName(String username) {
User user = null;
if (username.equals("admin")) {
user = new User();
user.setUsername(username);
user.setPassword("123456");


}
return user;
}
}

11.User.java

package com.jike.bean;


public class User {


private String username;
private String password;


public String getUsername() {
return username;
}


public void setUsername(String username) {
this.username = username;
}


public String getPassword() {
return password;
}


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


}    

12.JsonController.java

package com.jike.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import com.jike.bean.User;


@Controller
public class JsonController {


@ResponseBody
@RequestMapping("getJson")
public User getUserInfo() {
User user = new User();
user.setUsername("admin");
user.setPassword("123456");
return user;
}

}

13.PathvariableController.java

package com.jike.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.ResponseBody;


import com.jike.bean.User;


@Controller
public class PathvariableController {
@ResponseBody
@RequestMapping("/pathvariable/{username}")
public User getUserInfo(@PathVariable String username) {
User user = new User();
user.setUsername(username);
user.setPassword("123456");
return user;
}


@ResponseBody
@RequestMapping("/pathvariable2/{username}")
public User getUserInfo(@PathVariable Integer username) {
User user = new User();
user.setUsername(username + "");
user.setPassword("123456");
return user;
}

}


猜你喜欢

转载自blog.csdn.net/qidiantianxia/article/details/80606539