struts2找不到action_第一次用上Struts2框架做Web开发的体验……
SliiyStruts2
又名 sb-struts2,因為struts真的太難用了(也許在很多年前是很好用的,但是現(xiàn)在看來,被其他框架秒成渣)
前言
想不到我還是得和這struts框架打交道啊,從一開始學(xué)web的時候就十分抵制這類古老,使用反人類的框架,不過為了幫女朋友做個學(xué)校的作業(yè),還是得搞一下,然而,半小時就寫好的業(yè)務(wù)代碼,因為我不熟悉這個框架和Java的這套體系,調(diào)試了半天才成功run起來……(心好累)
開始
首先使用idea創(chuàng)建struts2項目,但是坑來了,idea創(chuàng)建的少了一個包,請自行去maven倉庫下載,具體是少了這個包
javassist-3.26.0-GA.jar接著就可以開始寫代碼了……
關(guān)于Struts2框架的學(xué)習(xí)參考:
- Struts2入門這一篇就夠了
這篇寫得很好,很詳細,里面還有例子,跟著做就可以自己實現(xiàn)一個簡單的struts框架了……
配置
先寫一個最簡單的IndexAction,這里主要是做數(shù)據(jù)庫的初始化工作,代碼如下:
package cn.deali.action;import cn.deali.utils.Database; import com.opensymphony.xwork2.ActionSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory;public class IndexAction extends ActionSupport {private final static Logger logger = LoggerFactory.getLogger(IndexAction.class);@Overridepublic String execute() throws Exception {System.out.println("Index Action");logger.info("Index Action");// 初始化數(shù)據(jù)庫if (Database.init()) {Database.eraseData = false;return SUCCESS;} elsereturn ERROR;} }寫完了Action之后還要給一個配套的jsp頁面,這叫做MVC設(shè)計模式,前后端分離(偽)……
<%--Created by IntelliJ IDEA.User: DealiAxyDate: 2019/11/17Time: 10:23 --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>用戶管理系統(tǒng)</title> </head> <body> <h1>用戶管理系統(tǒng)</h1><a href="Login.action">登錄</a> <a href="SignIn.action">注冊</a> <a href="User.action">修改密碼</a></body> </html>其他的代碼由于篇幅關(guān)系我就沒放上來,本文最后有GitHub地址,有需要可以參考
之后就可以配置struts2了,就像這樣……
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN""http://struts.apache.org/dtds/struts-2.5.dtd"><struts><package name="cn.deali.action" namespace="/" extends="struts-default"><default-action-ref name="Index"/><action name="Index" class="cn.deali.action.IndexAction" method="execute"><result name="success">main.jsp</result><result name="error">error.jsp</result></action></package> </struts>其中的<default-action-ref name="Index"/>是我后來學(xué)到的,默認action,一開始我以為和其他框架一樣,定義一個“/”路由就可以了,結(jié)果自己坑了自己,調(diào)試了半天都不行。
參考資料:
- struts2設(shè)置默認首頁
日志記錄
一開始用的是log4j,感覺有點坑啊,然后想起來之前用過slf4j,雖然兩個不是同個概念的,不過slf4j+slf4j-simple,是真的好用,方便,(ps:需要性能更好的可以用logback,hhh),log4j配置真的麻煩,而且嵌入到tomcat服務(wù)器,反正我這只是做個作業(yè),不用搞太麻煩。
而且slf4j的輸出模板也很好用,至少不會像log4j那么麻煩要拼接字符串了。
關(guān)于日志記錄的操作參考:
- Log4j.properties配置詳解加示例 - 簡約人生的博客 - CSDN博客
- log4j 配置
- SLF4J使用和與Log4J對比
- 使用SLF4J和Logback
- Java日志框架:slf4j作用及其實現(xiàn)原理
關(guān)于我自己的Log4J的配置我這也放上來吧,雖然最后沒用上。
# 配置根Logger:設(shè)定日志記錄的最低級別, log4j.rootLogger=DEBUG, stdout, logfile,ERROR log4j.category.org.springframework=ERROR log4j.category.org.apache=INFO log4j.logger.org.hibernate=ERROR # 輸出到控制臺 log4j.appender.stdout=org.apache.log4j.ConsoleAppender # 指定日志信息的最低輸出級別,默認為DEBUG log4j.appender.stdout.Threshold=ERROR # 表示所有消息都會被立即輸出,設(shè)為false則不輸出,默認值是true log4j.appender.stdout.ImmediateFlush=true # 可以靈活自定義布局模式 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout # 默認值是System.out。 log4j.appender.stdout.Target=System.out # 設(shè)定以怎樣的格式顯示消息 log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n數(shù)據(jù)庫
數(shù)據(jù)庫又是喜聞樂見的SQLite了,反正每次我都是用這個,hhh……
關(guān)于Java使用SQLite,可以參考:
- 在Java中使用Sqlite數(shù)據(jù)庫
附上我的SQLiteHelper實用類代碼:
package cn.deali.utils.sqlite; import org.slf4j.Logger; import org.slf4j.LoggerFactory;import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List;/*** sqlite幫助類,直接創(chuàng)建該類示例,并調(diào)用相應(yīng)的接口即可對sqlite數(shù)據(jù)庫進行操作* <p>* 本類基于 sqlite jdbc v56** @author haoqipeng*/ public class SQLiteHelper {private final static Logger logger = LoggerFactory.getLogger(SQLiteHelper.class);private Connection connection;private Statement statement;private ResultSet resultSet;private String dbFilePath;/*** 構(gòu)造函數(shù)** @param dbFilePath sqlite db 文件路徑* @throws ClassNotFoundException* @throws SQLException*/public SQLiteHelper(String dbFilePath) throws ClassNotFoundException, SQLException {this.dbFilePath = dbFilePath;connection = getConnection(dbFilePath);}/*** 獲取數(shù)據(jù)庫連接** @param dbFilePath db文件路徑* @return 數(shù)據(jù)庫連接* @throws ClassNotFoundException* @throws SQLException*/public Connection getConnection(String dbFilePath) throws ClassNotFoundException, SQLException {Connection conn = null;Class.forName("org.sqlite.JDBC");conn = DriverManager.getConnection("jdbc:sqlite:" + dbFilePath);return conn;}/*** 執(zhí)行sql查詢** @param sql sql select 語句* @param rse 結(jié)果集處理類對象* @return 查詢結(jié)果* @throws SQLException* @throws ClassNotFoundException*/public <T> T executeQuery(String sql, ResultSetExtractor<T> rse) throws SQLException, ClassNotFoundException {try {resultSet = getStatement().executeQuery(sql);T rs = rse.extractData(resultSet);return rs;} finally {destroyed();}}/*** 執(zhí)行select查詢,返回結(jié)果列表** @param sql sql select 語句* @param rm 結(jié)果集的行數(shù)據(jù)處理類對象* @return* @throws SQLException* @throws ClassNotFoundException*/public <T> List<T> executeQuery(String sql, RowMapper<T> rm) throws SQLException, ClassNotFoundException {List<T> rsList = new ArrayList<T>();try {resultSet = getStatement().executeQuery(sql);while (resultSet.next()) {rsList.add(rm.mapRow(resultSet, resultSet.getRow()));}} finally {destroyed();}return rsList;}/*** 執(zhí)行數(shù)據(jù)庫更新sql語句** @param sql* @return 更新行數(shù)* @throws SQLException* @throws ClassNotFoundException*/public int executeUpdate(String sql) throws SQLException, ClassNotFoundException {try {int c = getStatement().executeUpdate(sql);return c;} finally {destroyed();}}/*** 執(zhí)行多個sql更新語句** @param sqls* @throws SQLException* @throws ClassNotFoundException*/public void executeUpdate(String... sqls) throws SQLException, ClassNotFoundException {try {for (String sql : sqls) {getStatement().executeUpdate(sql);}} finally {destroyed();}}/*** 執(zhí)行數(shù)據(jù)庫更新 sql List** @param sqls sql列表* @throws SQLException* @throws ClassNotFoundException*/public void executeUpdate(List<String> sqls) throws SQLException, ClassNotFoundException {try {for (String sql : sqls) {getStatement().executeUpdate(sql);}} finally {destroyed();}}private Connection getConnection() throws ClassNotFoundException, SQLException {if (null == connection) connection = getConnection(dbFilePath);return connection;}private Statement getStatement() throws SQLException, ClassNotFoundException {if (null == statement) statement = getConnection().createStatement();return statement;}/*** 數(shù)據(jù)庫資源關(guān)閉和釋放*/public void destroyed() {try {if (null != connection) {connection.close();connection = null;}if (null != statement) {statement.close();statement = null;}if (null != resultSet) {resultSet.close();resultSet = null;}} catch (SQLException e) {logger.error("Sqlite數(shù)據(jù)庫關(guān)閉時異常", e);}} }public interface ResultSetExtractor<T> {public abstract T extractData(ResultSet rs); }public interface RowMapper<T> {public abstract T mapRow(ResultSet rs, int index) throws SQLException; }還有我的數(shù)據(jù)庫工廠類,哈哈:
package cn.deali.utils;import cn.deali.utils.sqlite.SQLiteHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory;public class Database {private final static Logger logger = LoggerFactory.getLogger(Database.class);private static SQLiteHelper db;public static boolean eraseData = false;public static SQLiteHelper getInstance() {if (db != null)return db;try {db = new SQLiteHelper("test.db");return db;} catch (Exception ex) {logger.error(ex.getMessage());return null;}}public static boolean init() {logger.info("初始化數(shù)據(jù)庫!");db = getInstance();try {if (eraseData) {db.executeUpdate("drop table if exists user;");db.executeUpdate("create table user(username varchar(20), password varchar(20));");logger.info("創(chuàng)建數(shù)據(jù)表");}return true;} catch (Exception e) {e.printStackTrace();logger.error(e.getMessage());return false;}} }坑
首先是tomcat服務(wù)器在Windows上有控制臺輸出亂碼的問題,很煩,解決的話可以參考:
- 解決Tomcat控制臺輸出信息亂碼
- Tomcat亂碼問題 catalina.bat設(shè)置為UTF-8 控制臺出現(xiàn)亂碼
完整代碼
最后附上GitHub地址,有需要自取,沒啥技術(shù)含量,就是做個小記錄。
地址: https://github.com/Deali-Axy/SillyStruts2
歡迎交流
交流問題請在微信公眾號后臺留言,每一條信息我都會回復(fù)哈~
- 微信公眾號:畫星星高手
- 打代碼直播間:https://live.bilibili.com/11883038
- 知乎:https://www.zhihu.com/people/dealiaxy
- 簡書:https://www.jianshu.com/u/965b95853b9f
總結(jié)
以上是生活随笔為你收集整理的struts2找不到action_第一次用上Struts2框架做Web开发的体验……的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 城市轨道交通运营票务管理论文_解读新版《
- 下一篇: 大一java期末考笔试_大学java期末