html中的<form th:action="@{/index}" method="get">,controller层使用RequestMapping如何接受
时间: 2024-05-22 21:12:42 浏览: 68
在Controller层中,可以使用@GetMapping或@RequestMapping注解来接受GET请求,并使用@RequestParam注解来获取form表单中提交的参数。例如:
@GetMapping("/index")
public String index(@RequestParam("param1") String param1, @RequestParam("param2") String param2) {
// 处理请求逻辑
return "index";
}
其中,@RequestParam注解中的参数名需要与form表单中的参数名一致。如果form表单中的参数名与方法参数名一致,则可以省略@RequestParam注解。例如:
@GetMapping("/index")
public String index(String param1, String param2) {
// 处理请求逻辑
return "index";
}
相关问题
代码 现有一个用户信息管理网站,项目名称xmvc01,需要完成登录和用户内容展示两个功能。 1.登录功能:根据输入数据和数据库user表的数据进行比较,登录成功显示用户列表,登录失败返回登录页面2.用户列表:用户登录成功,以表格的形式显示user表所有数据信息。用户没有登录,将返回录页面现有项目结构如下内容:仅限院校复习接课使用经允洋请勿 仅限院 授课信描述 com.neu.pojo.User 对应数据表user的javaBean comneu.controller.LoginController用于用户登录功能 是否完成 是 否 用于用户列表显示访问路径(/users)否comneu.controller.UserController com.neudao.UserMapper 用户持久层接口月 com/neu/mapper/UserMapper.xmlmybatis配置文件 4
以下是可能的代码实现,仅供参考:
User.java
```java
package com.neu.pojo;
public class User {
private Integer id;
private String username;
private String password;
// 省略getter和setter方法
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
}
}
```
LoginController.java
```java
package com.neu.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.neu.pojo.User;
import com.neu.service.UserService;
@Controller
public class LoginController {
@Autowired
private UserService userService;
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String showLoginForm() {
return "loginForm";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(String username, String password, Model model) {
User user = userService.findUserByUsernameAndPassword(username, password);
if (user != null) {
model.addAttribute("users", userService.findAllUsers());
return "userList";
} else {
model.addAttribute("error", "用户名或密码错误");
return "loginForm";
}
}
}
```
UserController.java
```java
package com.neu.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.neu.service.UserService;
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/users", method = RequestMethod.GET)
public String showUserList(Model model) {
model.addAttribute("users", userService.findAllUsers());
return "userList";
}
}
```
UserService.java
```java
package com.neu.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.neu.dao.UserMapper;
import com.neu.pojo.User;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User findUserByUsernameAndPassword(String username, String password) {
return userMapper.findUserByUsernameAndPassword(username, password);
}
public List<User> findAllUsers() {
return userMapper.findAllUsers();
}
}
```
UserMapper.java
```java
package com.neu.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.neu.pojo.User;
public interface UserMapper {
User findUserByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
List<User> findAllUsers();
}
```
UserMapper.xml
```xml
<?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="com.neu.dao.UserMapper">
<resultMap type="com.neu.pojo.User" id="userResultMap">
<id column="id" property="id" />
<result column="username" property="username" />
<result column="password" property="password" />
</resultMap>
<select id="findUserByUsernameAndPassword" resultMap="userResultMap">
select * from user where username=#{username} and password=#{password}
</select>
<select id="findAllUsers" resultMap="userResultMap">
select * from user
</select>
</mapper>
```
loginForm.jsp
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<h1>用户登录</h1>
<form action="${pageContext.request.contextPath}/login" method="post">
<p>
<label>用户名:</label> <input type="text" name="username" required>
</p>
<p>
<label>密码:</label> <input type="password" name="password" required>
</p>
<p>
<button type="submit">登录</button>
</p>
<p style="color: red">${error}</p>
</form>
</body>
</html>
```
userList.jsp
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户列表</title>
</head>
<body>
<h1>用户列表</h1>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>用户名</th>
<th>密码</th>
</tr>
</thead>
<tbody>
<c:forEach var="user" items="${users}">
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.password}</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
```
以上代码可能有些细节需要根据您的实际情况进行修改,希望能给您提供一些帮助。
创建一个 Maven 项目,添加所需的依赖,包括 Spring、SpringMVC、MyBatis、CXF 等。 配置 Spring 配置文件,包括数据源和 MyBatis 的配置、事务管理器的配置、CXF 的配置等。 创建一个实体类和相应的 Mapper 接口,使用 MyBatis 实现数据的 CRUD 操作。 创建一个 Service 层,实现业务逻辑,调用 Mapper 层的方法进行数据操作。 创建一个 Controller 层,使用 SpringMVC 实现请求的映射和响应的处理。 配置 CXF 的服务端和客户端,实现 WebService 的发布和调用。 创建一个 JSP 页面,使用 JSTL 标签库和 EL 表达式实现页面的渲染。 部署项目到 Tomcat 等 Web 容器中,访问 JSP 页面,测试项目是否正常运行。具体代码
由于这个项目比较复杂,我无法在这里给出完整的代码。但是,我可以提供一些代码片段来帮助你理解每个步骤的实现方式。
1. Maven 项目配置
在 pom.xml 文件中添加以下依赖:
```xml
<dependencies>
<!-- Spring Framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-core</artifactId>
<version>3.3.6</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.3.6</version>
</dependency>
</dependencies>
```
2. Spring 配置文件
在 applicationContext.xml 文件中添加以下配置:
```xml
<!-- 数据源配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- MyBatis 配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.example.demo.entity" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory" />
</bean>
<!-- 事务管理器配置 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- CXF 配置 -->
<jaxws:server id="demoService" address="/DemoService">
<jaxws:serviceBean>
<bean class="com.example.demo.service.impl.DemoServiceImpl" />
</jaxws:serviceBean>
</jaxws:server>
```
3. 实体类和 Mapper 接口
创建一个实体类 Demo,代码如下:
```java
public class Demo {
private Integer id;
private String name;
private Integer age;
// getter 和 setter 略
}
```
创建一个 Mapper 接口 DemoMapper,代码如下:
```java
public interface DemoMapper {
void insert(Demo demo);
void update(Demo demo);
void deleteById(Integer id);
Demo selectById(Integer id);
List<Demo> selectAll();
}
```
使用 MyBatis 的 XML 文件实现 Mapper 接口的方法,代码如下:
```xml
<mapper namespace="com.example.demo.mapper.DemoMapper">
<insert id="insert" parameterType="com.example.demo.entity.Demo">
INSERT INTO demo(name, age) VALUES(#{name}, #{age})
</insert>
<update id="update" parameterType="com.example.demo.entity.Demo">
UPDATE demo SET name = #{name}, age = #{age} WHERE id = #{id}
</update>
<delete id="deleteById" parameterType="java.lang.Integer">
DELETE FROM demo WHERE id = #{id}
</delete>
<select id="selectById" parameterType="java.lang.Integer" resultType="com.example.demo.entity.Demo">
SELECT * FROM demo WHERE id = #{id}
</select>
<select id="selectAll" resultType="com.example.demo.entity.Demo">
SELECT * FROM demo
</select>
</mapper>
```
4. Service 层
创建一个 Service 接口 DemoService,代码如下:
```java
public interface DemoService {
void addDemo(Demo demo);
void updateDemo(Demo demo);
void deleteDemo(Integer id);
Demo getDemoById(Integer id);
List<Demo> getAllDemo();
}
```
创建一个 Service 实现类 DemoServiceImpl,代码如下:
```java
@Service
@Transactional
public class DemoServiceImpl implements DemoService {
@Autowired
private DemoMapper demoMapper;
@Override
public void addDemo(Demo demo) {
demoMapper.insert(demo);
}
@Override
public void updateDemo(Demo demo) {
demoMapper.update(demo);
}
@Override
public void deleteDemo(Integer id) {
demoMapper.deleteById(id);
}
@Override
public Demo getDemoById(Integer id) {
return demoMapper.selectById(id);
}
@Override
public List<Demo> getAllDemo() {
return demoMapper.selectAll();
}
}
```
5. Controller 层
创建一个 Controller 类 DemoController,代码如下:
```java
@Controller
@RequestMapping("/demo")
public class DemoController {
@Autowired
private DemoService demoService;
@RequestMapping(value = "/addDemo", method = RequestMethod.POST)
@ResponseBody
public String addDemo(@RequestBody Demo demo) {
demoService.addDemo(demo);
return "success";
}
@RequestMapping(value = "/updateDemo", method = RequestMethod.POST)
@ResponseBody
public String updateDemo(@RequestBody Demo demo) {
demoService.updateDemo(demo);
return "success";
}
@RequestMapping(value = "/deleteDemo/{id}", method = RequestMethod.GET)
@ResponseBody
public String deleteDemo(@PathVariable Integer id) {
demoService.deleteDemo(id);
return "success";
}
@RequestMapping(value = "/getDemoById/{id}", method = RequestMethod.GET)
@ResponseBody
public Demo getDemoById(@PathVariable Integer id) {
return demoService.getDemoById(id);
}
@RequestMapping(value = "/getAllDemo", method = RequestMethod.GET)
@ResponseBody
public List<Demo> getAllDemo() {
return demoService.getAllDemo();
}
}
```
6. CXF 配置
在 applicationContext.xml 文件中添加以下配置:
```xml
<jaxws:client id="demoClient" serviceClass="com.example.demo.service.DemoService"
address="http://localhost:8080/DemoService" />
<bean id="demoService" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
<property name="serviceClass" value="com.example.demo.service.DemoService" />
<property name="address" value="http://localhost:8080/DemoService" />
</bean>
```
7. JSP 页面
创建一个 JSP 页面 demo.jsp,代码如下:
```html
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Demo Page</title>
</head>
<body>
<h1>Demo Page</h1>
<form id="demoForm">
<input type="text" name="name" placeholder="name" />
<input type="text" name="age" placeholder="age" />
<button type="button" onclick="addDemo()">Add</button>
</form>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<c:forEach items="${demoList}" var="demo">
<tr>
<td>${demo.id}</td>
<td>${demo.name}</td>
<td>${demo.age}</td>
<td>
<button type="button" onclick="editDemo(${demo.id})">Edit</button>
<button type="button" onclick="deleteDemo(${demo.id})">Delete</button>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<script>
function addDemo() {
var name = $("input[name='name']").val();
var age = $("input[name='age']").val();
$.ajax({
url: "${pageContext.request.contextPath}/demo/addDemo",
type: "POST",
contentType: "application/json",
data: JSON.stringify({name: name, age: age}),
success: function(result) {
location.reload();
}
});
}
function editDemo(id) {
// TODO: 实现编辑逻辑
}
function deleteDemo(id) {
$.ajax({
url: "${pageContext.request.contextPath}/demo/deleteDemo/" + id,
type: "GET",
success: function(result) {
location.reload();
}
});
}
</script>
</body>
</html>
```
8. 部署项目
将项目打包成 WAR 文件,部署到 Tomcat 等 Web 容器中,启动 Tomcat,访问 demo.jsp 页面,测试项目是否正常运行。
以上是一个简单的示例,具体实现方式可能会因为需求的不同而有所差异。
阅读全文